-
Notifications
You must be signed in to change notification settings - Fork 9
Unit Tests
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.
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.
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:
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) });
};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', () => { .... });
}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()
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();
});
});function helloworld() {
return 'Hello World!';
}describe('Hello World', () => {
it('says hello', () => {
expect(helloworld()).toEqual('Hello World!');
});
});View Jasmine documentation for more details. Some common matchers are the following:
toBe()toEqual()toBeTruthy() / toBeFalsy()toBeNull()toBeUndefined() / toBeDefined()