Unit Test with Jasmine - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki

Jasmine is the testing framework used by Angular team. Therefore, it would be good to use it for testing our Angular project.

Jasmine

Structure

describe beforeAll/afterAll beforeEach/afterEach it expect Pending/Focus

  • xit

  • pending

  • fit

  • fdescribe

Matcher

expect(actual).toBe(matcher);
  • String
  • Existence
  • Object
  • Array
  • Custom

Spy

  • Track function invocation
  • Parameter lists for all invocations
  • Can call through
  • Can call another function
  • Can return arbitrary value
  • Can throw Error

Mock the clock and Date

  • setTimeout - setInterval
  • Set Date

Asynchronous

  • Default timeout = 5 seconds
  • Done

Setup Jasmine

Server (Node)

Install

npm install jasmine --save

Create configuration file

"node_modules/.bin/jasmine" init

Run

Add a task test into package.json

"scripts": {
    "test": "jasmine"
  }

Run the tests with command: npm test

Combine with compile script for compiling typescript files:

"scripts": {
    "compile": "tsc -p .",
    "test": "jasmine"
  }

Continuous Testing

  • Install nodemon which monitors file changes and restart the application when there are changes. ` npm install nodemon --save-dev '
  • Configure nodemone nodemon.json json { "verbose": true, "ignore": ["*.ts", "node_modules/"] }
  • Add npm script to run test when there are changes
"scripts": {
    "compile": "tsc -p .",
    "testwatch": "nodemon -x npm run test"
  }