cypress-io / cypress

Fast, easy and reliable testing for anything that runs in a browser.
https://cypress.io
MIT License
47.02k stars 3.18k forks source link

Cannot find name '$localize' when using Angular i18n directive #29411

Open JayStolzenwald opened 6 months ago

JayStolzenwald commented 6 months ago

Current behavior

I'm using Angular i18n directive localization, which apparently you already started addressing last year. There is still room for improvement though.

I have this Angular standalone component

import { Component } from '@angular/core';
@Component({
  standalone: true,
  template: '<div>{{localizedHello}}</div>'
})
export class LocalizedHelloComponent {
  constructor() {}
  localizedHello = $localize`Hello World!`;
}

note that I'm using $localize to localise the string inline. I followed this instruction to setup component testing for my Angular component using the latest version of Cypress (13.8.1)

Now, when I run the test without any additional configuration, I get this:

Cannot find name '$localize'.
localizedHello = $localize`Hello World!`;

to fix this, I create cypress/support/index.ts and add

(window as any)['$localize'] = (...args: any[]) => {
  // Just return the input during testing
  return args.join(' ');
};

and refer to it in my cypress.config..ts

  component: {
    //...
    supportFile: 'cypress/support/index.ts'
  }

Now when I run the test again. It's working and I can see my rendered component in the cypress ui.

The error above still shows up in the console though. I can still continue working but obviously it clutters my error console output. The behaviour suggests that the workaround presented here is working but typescript is missing a type definition. I'm not sure where this needs to go and frankly, this should be handled by the cypress-angular framework for me.

Desired behavior

At the very least, cypress for angular should know that $localize exists and add the type. Ideally cypress would come with a standard solution to handle $localize out of the box. Most developers don't want to use Cypress to assert working localization but component functionality. So it would be good to have a standard solution that just returns the source language. If this is not possible, then required steps to set this up manually should be added to the angular component test setup guide.

Any help to get rid of the error output is well appreciated

Test code to reproduce

see above

Cypress Version

13.8.1

Node version

21.7.1

Operating System

13.6.6

Debug Logs

No response

Other

No response

hennihaus commented 1 month ago

To fix this error you must add import '@angular/localize/init'; to your component.ts (your support file for component testing).