I have a component, which has two dependencies: one is LOCALE_ID
defined globally in angular, another is language, defined in the Component as { provide: LANGUAGE_TOKEN, useValue: navigator.language }
For testing, I am both overriding them in TestBed for all tests, so tests don't get anything injected from the Chrome browser doing the karma tests, and tests don't have different result based on testing environment:
TestBed.configureTestingModule({
declarations: [
MyComponent, RouterStubComponent,
],
imports: [
MatToolbarModule, RouterTestingModule, MatIconModule, MatButtonModule,
],
providers: [
{provide: LOCALE_ID, useValue: 'en-US' },
]
}).compileComponents();
TestBed.overrideProvider(LOCATION_TOKEN, {useValue: locationStub});
TestBed.overrideProvider(LANGUAGE_TOKEN, {useValue: 'en-US' });
Now I have some logic in the component that depends on locale and browser language, so I need to mock them. Mocking LANGUAGE_TOKEN
was super easy, barely an inconvenience:
it('should redirect to spanish when in spanish browser', () => {
TestBed.overrideProvider(LANGUAGE_TOKEN, {useValue: 'es'});
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(hrefSpy.calls.count()).toBe(1);
expect(hrefSpy.calls.argsFor(0)[0]).toEqual(environment.spanUrl);
});
However override LOCALE_ID
with same code doesn't work.
it('should ...', () => {
TestBed.overrideProvider(LOCALE_ID, {useValue: 'es-ES'});
console.log(TestBed.get(LOCALE_ID)); // en-US!!!!
fixture = TestBed.createComponent(MamanComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(hrefSpy.calls.count()).toBe(1); //FAIL
expect(hrefSpy.calls.argsFor(0)[0]).toEqual(environment.engUrl);//FAIL
});
I was unable to find a working answer in this question either.