Unit Test errors for Karma test runner with Jasmine

Relation between Karma and Jasmine:

Karma is a Test Runner that is being used by Jasmin and related frameworks for Test Driven Development. Karma provides helpful tools that make it easier to us to call our Jasmine tests whilst we are writing code.

Here is a list of some generic errors that a newbie might get while creating Unit Tests in Angular using Karma with Jasmine.

1- Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’

This particular error may occur for executing angular app as well as its unit tests. Reason is same in both cases. I managed to resolve it by importing ‘FormModule’

In case of Unit test error when we execute command #ng test, following is the solution:

  • Open file ‘YOUR_OMPONENT_NAME.spec.ts’, in my case it was ‘app.component.spec.ts’
  • Within ‘TestBed.configureTestingModule’ section, add following line:
    • imports: [ FormsModule ]

This should resolve the error.

If this same error is for angular app other than unit test runner, programmer may need to add the same ‘FormsModule’ in imports section of ‘app.module.ts’

Using Custom Class:

I got similar error while adding a custom class say, ‘Gallery’ in the system. Custom class ‘Gallery’ is required in all the components.

In this case, it is required to import both the external component that is being communicated as well as custom added Gallery class.

I provided component in ‘declarations’ section and class in ‘providers’ section of ‘TestBed.configureTestingModule’ to get resolved this kind of errors.

2- Testing Asynchronous Action:

There is a little trick in testing a function that is using promise to wait for the precise wait to test the function. Angular provides ‘fakeAsync‘ and ‘tick‘ to help for asynchronous testing. Following is an example to try it out.

Function defined in component for Unit Test:

getGalleries(): void {
this.galleryService.getGalleris().then((galleries) => this.galleries = galleries);

Test Code check if there is any item in list of galleries:

it(`should setup galleries length to be more than zero`, fakeAsync(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;

expect(app.galleries.length > 0).toBeTruthy();


Above example is as per my test application. If you have different views about above contents, please provide your input in comments.

Leave a Reply

Your email address will not be published. Required fields are marked *