Search code examples
angularunit-testingkarma-jasmine

What is 'should create' test case in Jasmine


I'm new to Unit testing in Angular using Jasmine and Karma. I'm an intern. I was going through a spec file. I want to know what is meant by should create in this context. TimeselectorComponent is the component that I want to test. I took the code from my senior. The code is like this:

import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
...

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    beforeEach(async(() => {

        TestBed.configureTestingModule({
            imports: [
                ...
            ],
            providers: [...],
            declarations: [TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

    it('should create', () => {
        expect(fixture.componentInstance).toBeTruthy();
    });

    // other test cases
});

There are other test cases also but for now I'm curious about 'should create' case. My understanding says that it is trying to test whether the component was initialized/created or not. Please correct me if I'm wrong. Please tell me more about the above code. Would like to know about compileComponent() method also. I checked this link but could understand only a little:

compileComponents() is asynchronous, we must use async()

I'm going through this question also:

Error: Please call “TestBed.compileComponents” before your test


Solution

  • String inside each it block is a test case name. The first test case is should create, which you combine it with string in describe i.e. TimeSelectorComponent, it becomes TimeSelectorComponent should create. This test case is checking whether TimeSelector component is initialized or not. You can also change this string as per your convenience or how you want to write test cases.

    Compilecomponents is a method which compiles all components you have mentioned in your test bed. Take task takes time, that's why its asynchronous so that your main thread isn't blocked and if you want to do, you can do some other setup parallely. That's why that async keyword is mandatory so that before each can wait till all async tasks executing inside are finished. Because test case will fail if our components are not ready.