Unit Testing in Angular (General Intro)

Table of contents

No heading

No headings in the article.

Unit Testing is where a little to medium part of work is consumed for many developers' life. Many organizations expect the code to be unit tested against a predefined benchmark to avoid surprises at the last minute. “Test Driven Development” is one of the Catchy phrases used in the Industry.

Copywright : Monkeyuser.com

More like the frameworks present in Angular, for Unit testing one can use many existing functionalities to mock/fake the actual properties of the application to simulate the one in the testing side. Jasmine and Karma were some of the famous testing frameworks used to write unit test cases.

Test cases from the angular side are relatively simple and self-understandable. The plain English-like structure also makes the flow easier than actually writing a program.

Suppose you have a component named “HelloWorld”, the test case starts like this,

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

/** Before each method with async**/
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HelloWorldComponent]
    }).compileComponents();
  }));

/** Before each method without async**/
  beforeEach(() => {
    fixture = TestBed.createComponent(HelloWorldComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

/** Actual Testcase method **/
  it('should create', () => {
    expect(component).toBeTruthy();
  });


});

The breakup of the above codes like this

describe('HelloWorldComponent', () => { });

The above line holds the full set of Test-code , in precise a class like structure in language of OOPs. It does not return any value. The structure as per the documentation goes like ,

function describe(description: string, specDefinitions: () => void):

The next part goes to beforeEach method.

beforeEach(action: (done: DoneFn) => void, timeout?: number)

or

beforeEach(async(action: (done: DoneFn) => void, timeout?: number))

beforeEach method is used to run the commonly shared parts which spill across all the test cases/functions. Also, it includes an Overload function of async call, where all the declaration, providers and import part gets placed.

This is similar to @Before function in Junit and [SetUp] in Nunit versions.

The comes the main test method.

it('......testname...',() => {});

This syntax exactly matches with the statement in English , and as per the example, it goes like “it should have created the component”