DEV Community

Cover image for Angular unit testing 101 (with examples)

Angular unit testing 101 (with examples)

Mustapha Aouas on August 29, 2019

The more we add features to our software the more it grows in complexity. And as it grows in complexity, more time is required to manually test it....
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. : )

Collapse
 
nicolasomar profile image
Nicolás Omar González Passerino

Thank you for the article Mustapha. I am learning unit testing from 0 in an Angular project I started a month ago and your knowledge is more than appreciated.
Do you have other articles related to unit testing (even at a general level)?

Collapse
 
rebaiahmed profile image
Ahmed Rebai

check medium blogs also there are some great resources :medium.com/search?q=angular%20unit...

Collapse
 
rebaiahmed profile image
Ahmed Rebai

Nice and good explanation , thanks for this great article

Collapse
 
mustapha profile image
Mustapha Aouas

Glad i could help. Thanks for the feedback

Collapse
 
shofol profile image
Anower Jahan Shofol

Nice and clear explanations, Mustapha. I've just started to see Angular testing today, so the thorough explanation really cleared my idea. Thanks :D

Collapse
 
mustapha profile image
Mustapha Aouas

Thanks for the kind words! Glad i could help :)

Collapse
 
dchennaraidu profile image
D Chenna Raidu

TheAngularGuy, now I have something to do this weekend. Thank you

Collapse
 
mustapha profile image
Mustapha Aouas • Edited

Glad to hear that, have fun ;)

Collapse
 
jangelodev profile image
João Angelo

Hi Mustapha Aouas,
Top, very nice and helpful !
Thanks for sharing.

Collapse
 
pratapdev profile image
pratapdev • Edited

can we test modules as well?

Collapse
 
mustapha profile image
Mustapha Aouas • Edited

Of course you can configure your testbed like this:

       TestBed.configureTestingModule({
            imports: [
                HttpModule,
                FeatureModule.forRoot() // or forFeature() or any method of this module
            ]
        });
Enter fullscreen mode Exit fullscreen mode

Then test if all providers are correctly provided by the module with TestBed.get or the new notation TestBed.inject (ng 10+).

Beside from that, i dont know what do you want to test ?

Collapse
 
afifalfiano profile image
Afif Alfiano

Great article!