Skip to content

Unit Tests

ethanwu155 edited this page Jul 14, 2020 · 3 revisions

Unit Testing

Unit Testing is an integral part of code development. When we unit test, we are exercising a single unit of code in isolation. For MyLog14, we will be using the following testing frameworks: Jasmine & Karma.

File Structure

In Ionic4 + Angular projects, Unit Tests are written in spec files. spec files are named after the source they are testing. For example the following file record.ts will have a corresponding testing file named record.spec.ts. Both files will be in the same folder.

Running Unit Tests

To run unit tests open command line or terminal and run: npm test

When unit tests are run, Jasmine/Karma will run every single unit test. To tests individual Unit Tests in projects do the following:

fdescribe('sample unit test', () => {  .....  }) 

Alternatively, you may install the following extensions on VSCode to run tests within IDE:

Writing Unit Tests

Basic Structure of Unit Test

Unit tests can be broken down in 3 parts: describe, it & expect(). describe defines the overall test. it contains descriptive label of expected behavior. expect() is the matcher function that compares the actual value with an expected value and returns true/false or pass/fail. For example:

describe('divide', () => {`
  it('calculates 4 / 2 properly' () => { expect(4/2).toBe(2) });
};

Unit Testing Pages and Components

When unit testing pages and components we need to utilize Angular Component Testing guidelines. This involves importing TestBed from @angular/core/testing and declaring TestBed in beforeEach block in Unit Test. The following is a general template:

import { TestBed } from '@angular/core/testing';
import { Page } from './page';

describe('Page', () => {
  beforeEach(() => TestBed.configureTestingModule({}));
  it('should create', () => { .... });
}

Mocking

In ideal situations, unit tests test code independent of any dependencies. This can be done through mocking. Jasmine framework provides a means of mocking objects through spies.

Method:

  • spyOn()
  • createSpy()

Mocking Example

Say we want to write a unit test for the String.toUpperCase()

describe('String.toUpperCase()', () => {
  it("should make string uppercase", () => {
    var spytoUpperCase = spyOn(String.prototype, 'toUpperCase')
    expect(utils.toUpperCase).toBeDefined();
  });
});

Sample Hello World Unit Test

Method to Test

function helloworld() {
  return 'Hello World!';
}

Jasmine Test spec

describe('Hello World', () => {
  it('says hello', () => {
    expect(helloworld()).toEqual('Hello World!');
  });
});

Built-In Matchers

View Jasmine documentation for more details. Some common matchers are the following:

  • toBe()
  • toEqual()
  • toBeTruthy() / toBeFalsy()
  • toBeNull()
  • toBeUndefined() / toBeDefined()