Overview

Jasmine is a BDD framework for testing javascript code, it doesn’t depend on any UI Library like AngularJS or ReactJS. Just like another test framework, Jasmine has unit test assertion supported by the matchers object, each matcher implements a boolean comparison between the actual value and the expected value. 

In writing unit test sometimes we encounter a situation where the default matchers can’t really help us to write the code efficiently so we need to define a custom matcher, and since angular 2 written in typescript then every native javascript library (or object extended from it) included must have a declaration file otherwise the typescript compiler will thrown error.

Example

First thing to do is writing unit test script that have spec ‘should contain id and en otherwise system will crash’:

The unit test script above will failed during execution because we don’t have the LanguageService class yet, let’s create it:

Now it’s time to create our custom matcher:

To make our custom matcher recognized by typescript compiler we need typescript declaration file:

Finally import the custom array matcher into unit test script, don’t forget to add reference path of the declaration file:

 

This tutorial has been tested with the following library:

  • Angular 2.4.0
  • Jasmine 2.4.1
  • Typescript 2.0.10

External resources:

https://jasmine.github.io/2.0/custom_matcher.html

https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html