Consider this code:
import {
Component,
OnInit,
Renderer,
OnDestroy
} from '@angular/core';
import { TranslateService } from 'ng2-translate/ng2-translate';
export class AppComponent implements OnInit, OnDestroy {
constructor( private translate: TranslateService, renderer: Renderer ) {
this.globalKeyListenFunc = renderer.listenGlobal('document', 'keydown', (event) => {
if (event.keyCode === 18) { // ALT-Key
event.preventDefault();
}
});
...
}
How can I test such a component with a jasmine test?
I tried following test:
describe('App', () => {
let injector: Injector;
let backend: MockBackend;
let connection: MockConnection;
let translate: TranslateService;
let renderer: Renderer;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule, TranslateModule.forRoot()],
providers: [
AppComponent,
{provide: XHRBackend, useClass: MockBackend},
Renderer
]
});
injector = getTestBed();
backend = injector.get(XHRBackend);
translate = injector.get(TranslateService);
renderer= injector.get(Renderer);
backend.connections.subscribe((c: MockConnection) => connection = c);
});
it('should have fore languages', inject([ AppComponent ], (app: AppComponent) => {
app.ngOnInit();
expect(app.supportedLanguages.length).toBe(4);
}));
The error I get:
TypeError: undefined is not a constructor (evaluating 'renderer.listenGlobal') in config/spec-bundle.js
It seams that the Renderer instance has not the same behavior as in a real browser environment. As usual in a CI environment, I am using the PhantomJS browser to execute the test.
AppComponent
todeclarations
inTestBed.configureTestingModule(...)
and removeRenderer
andAppComponent
fromproviders
. – Poetize