Reputation: 1996
I use ng2-translate in my Angular 5 project and I am trying to create a unit test for one component.
I always import TranslateModule.forRoot( *...* )
in my Tests and the tests will work using the translate pipe in my views.
In two cases though, the above error is thrown, during unit tests: I don't see any difference to the other working tests.
× should create (44ms) TypeError: Cannot read property 'subscribe' of undefined at TranslatePipe.transform (webpack:///./node_modules/ng2-translate/src/translate.pipe.js?:74:75) at Object.eval [as updateRenderer] (ng:///DynamicTestModule/MyComponent.ngfactory.js:127:70) at Object.debugUpdateRenderer [as updateRenderer] (webpack:///./node_modules/@angular/core/esm5/core.js?:14951:21) at checkAndUpdateView (webpack:///./node_modules/@angular/core/esm5/core.js?:14065:14)
Any reasons why this could happen? I don't use TranslateService, but I use the pipe in the template. Did anyone encounter the same problem?
Upvotes: 10
Views: 8529
Reputation: 5727
Let me extend @Agata's answer for jasmine users:
describe('MyTestComponent', () => {
// ...
const translateService = jasmine.createSpyObj<TranslateService>('translateService', ['instant', 'get']);
const translateServiceMock = {
currentLang: 'de',
onLangChange: new EventEmitter<LangChangeEvent>(),
use: translateService.get,
get: translateService.get.and.returnValue(of('')),
onTranslationChange: new EventEmitter(),
onDefaultLangChange: new EventEmitter()
};
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [
// ...
],
imports: [
// ...
TranslateModule.forRoot(),
],
providers: [
// ...
{provide: TranslateService, useValue: translateServiceMock}
]
}).compileComponents();
});
});
Upvotes: 1
Reputation: 386
I had the same issue and I added to TranslateService mock class:
public onLangChange: EventEmitter<any> = new EventEmitter();
public onTranslationChange: EventEmitter<any> = new EventEmitter();
public onDefaultLangChange: EventEmitter<any> = new EventEmitter();
Upvotes: 37