Title: Angular - spy not recognising function being called
Tags: angular;unit-testing;typescript;karma-jasmine
Question: I'm trying to test one of my feature modules but I'm struggling. My last test fails because the spy doesn't think that the method is called. Not even if I move the this.translate.use(this.currentLanguage.i18n) call outside of the subscribe block.
This is the feature component:
export class LanguagesComponent implements OnDestroy, OnInit {
public languages = [
id: '0',
name: this.translate.stream('LANGUAGES.SWEDISH'),
i18n: 'sv',
flag: {
src: './assets/img/sv.svg'
}
},
id: '1',
name: this.translate.stream('LANGUAGES.ENGLISH'),
i18n: 'en',
flag: {
src: './assets/img/en.svg'
}
public currentLanguage: any;
private storageSubscription: Subscription;
constructor(
private cs: ClientStorage,
private notifications: NotificationsApi,
private router: Router,
private translate: TranslateService
) {}
ngOnInit() {
const storedLanguage: any = this.cs.getItem(AppConstants.currentLanguage);
this.currentLanguage = FindObjectByQuery(this.languages, 'i18n', storedLanguage);
// Listen for when the language changes from other places than this component
this.storageSubscription = this.cs.logger$
.filter(data =&gt; data &amp;&amp; data.key === AppConstants.currentLanguage)
.subscribe((currentLanguage: any) =&gt; {
if (currentLanguage) {
this.currentLanguage = FindObjectByQuery(this.languages, 'i18n', currentLanguage.value);
// Set the current language to use
this.translate.use(this.currentLanguage.i18n);
}
}
);
ngOnDestroy() {
this.storageSubscription.unsubscribe();
selectLanguage(language: any): void {
this.cs.setItem(AppConstants.currentLanguage, language.i18n);
this.router.navigate(['dashboard']);
this.notifications.newNotification({message: this.translate.instant('NOTIFICATIONS.LANGUAGES.CHANGED'), theme: 'success'});
And these are my tests so far:
describe('[UNIT] LanguagesComponent', () =&gt; {
let component: LanguagesComponent;
let fixture: ComponentFixture<LanguagesComponent&gt;;
let translate: Location;
beforeEach(() =&gt; {
TestBed.configureTestingModule({
imports: [
ModuleImports
],
providers: [
TranslateService
],
schemas: [NO_ERRORS_SCHEMA],
declarations: [LanguagesComponent, DummyComponent]
});
fixture = TestBed.createComponent(LanguagesComponent);
component = fixture.componentInstance;
translate = TestBed.get(TranslateService);
// Make sure ngOnInit runs
fixture.detectChanges();
it('should create the component', async(() =&gt; {
expect(component).toBeTruthy();
}));
it('should have a current language when the component has loaded', () =&gt; {
expect(component.currentLanguage).toBeTruthy();
it('should have the needed properties in the current language', () =&gt; {
const currentLanguage = component.currentLanguage;
expect(currentLanguage.id).toBeTruthy();
expect(currentLanguage.name).toBeTruthy();
expect(currentLanguage.i18n).toBeTruthy();
expect(currentLanguage.flag.src).toBeTruthy();
it('should call the use method of TranslateService with the current language i18n property', () =&gt; {
const spy = spyOn(translate, 'use').and.callThrough();
expect(spy).toHaveBeenCalledWith(component.currentLanguage.i18n);


Here is another answer: In your test you created a spy and then you immediately trying to verify the call. But there was no call.
There can be two possible solution for this.
Move your spyOn before fixture.detect changes in beforeEach.
After creating the spy, call/trigger appropriate method which will/should trigger the expected call. In this case fixture.detectChanges needs to be called.
Note: I didn't run your tests for any other issues but the basic issue is the missing call between spy creation and spy use.
Comment for this answer: Thank you! I moved my `fixture.detectChanges()` AFTER my spy declaration inside of my synchronous `beforeEach()` block and it is now working as expected.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:08/23/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<angular><unit-testing><typescript><karma-jasmine>', 'Title': 'Angular - spy not recognising function being called', 'ViewCount': 1505, 'id': 45833546, 'user_AboutMe': '<p>I love green numbers.</p>\n', 'user_AccountId': 5050145.0, 'user_DisplayName': 'Chrillewoodz', 'user_Reputation': 25720.0, 'user_Views': 1456.0, 'user_id': 4054974.0}}