DEV Community

Discussion on: Angular unit testing 101 (with examples)

Collapse
 
likepeach789 profile image
peach777

Great article! one question hope you could help me. All my components are written in app module. When i try to test one component(TestComponent), in the test.component.spec.file, i wrote below code. because i already declare the TestComponent in AppModule and used some third party components, i directly import it. When i run the test case, i didn't see 'fixture' getting printed in the console and the application throws error, TestBed.createComponent() failed and i don't know why...

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [],
imports: [AppModule]
})
.compileComponents();
fixture = TestBed.createComponent(TestComponent);
console.log('fixture');
console.log(fixture);
}));

Error:
TypeError: Cannot read property 'get' of undefined
error properties: Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 34127873, rootNodeFlags: 33554433, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 33554433, childFlags: 573440, directChildFlags: 573440, childMatchedQueries: 0, matchedQueries: Object({ }), matchedQueryIds: 0, references: Object({ }), ngContentIndex: null, childCount: 1, bindings: [ ], bindingFlags: 0, outputs: [ Object({ type: 0, target: 'document', eventName: 'click', propName: null }) ], element: Object({ ns: '', name: 'app-click-map-page', attrs: [ ], template: null, componentProvider: Object({ nodeIndex: 1, parent: , renderParent: , bindingIndex: 0, outputIndex: 1, checkIndex: 1, flags: 573440, childFlags: 0, directChildFlags: 0, childMatchedQueries: 0, matchedQueries: Object, matchedQueryIds: 0, references: Object, ...
at
at new SharedService (localhost:9876/_karma_webpack_/src...)

Collapse
 
mustapha profile image
Mustapha Aouas

Hi,

When you import the appModule, you are importing all the exported properties of the appModule.

Do you have your testComponent in the exports array of the appModule ?

Collapse
 
likepeach789 profile image
peach777

Yes I export it.. TestComponent extend another class and that class is using Injector to get service without using constructor.. The error happens at: AppModule.Injector.get(TestService) this line, said Cannot read property 'get' of undefined.

I create a question of this on stackoverflow, stackoverflow.com/questions/588577...

Maybe you could help give some advice. Thanks tons. : )