Closed tamas-szekeres closed 5 years ago
I have written a quick test to verify that field mocking works as expected when nothing special is around it:
it('plain mock', () => { const translateMock = mock(TranslateService); const translateInstance = instance(translateMock); when(translateMock.currentLang).thenReturn('de'); when(translateMock.instant('aa')).thenReturn('bb'); console.log("currentLang-direct", translateInstance.currentLang); console.log("instant-direct", translateInstance.instant('aa')); });
Which works as expected:
console.log test.spec.ts:12 currentLang-direct de console.log test.spec.ts:13 instant-direct bb
Then a second one using the testbed:
it('through angular', () => { const translateMock = mock(TranslateService); const translateInstance = instance(translateMock); when(translateMock.currentLang).thenReturn('de'); when(translateMock.instant('aa')).thenReturn('bb'); TestBed.configureTestingModule({ declarations: [AppComponent], providers: [ {provide: TranslateService, useValue: translateInstance} ] }).compileComponents(); const componentInstance = TestBed.createComponent(AppComponent).componentInstance; console.log("currentLang-indirect", componentInstance.getCurrentLanguage()); console.log("instant-indirect", componentInstance.getTranslation()); });
With the following component:
import {Component, OnInit} from '@angular/core'; import {TranslateService} from "@ngx-translate/core"; @Component({ template: 'app.component' }) export class AppComponent implements OnInit { constructor(private translate: TranslateService) { } ngOnInit(): void {} getCurrentLanguage() { return this.translate.currentLang; } getTranslation() { return this.translate.instant("aa"); } }
Unfortunately the field mock somehow gets lost in the second case:
console.log test.spec.ts:30 currentLang-indirect undefined console.log test.spec.ts:31 instant-indirect bb
In your TestBed test, if you try useFactory: () => translateInstance instead of useValue. That usually works for me.
useFactory: () => translateInstance
useValue
Looks good, thanks.
I have written a quick test to verify that field mocking works as expected when nothing special is around it:
Which works as expected:
Then a second one using the testbed:
With the following component:
Unfortunately the field mock somehow gets lost in the second case: