javascript – Unit testing using Jasmine and TypeScript

javascript – Unit testing using Jasmine and TypeScript

Heres (in my opinion) the best way to test a ts-node app as of 2018:

npm install --save-dev typescript jasmine @types/jasmine ts-node

In package.json:

{
  scripts: {
    test: ts-node node_modules/jasmine/bin/jasmine
  }
}

In jasmine.json change file pattern to *.ts

spec_files: [**/*[sS]pec.ts],

In your spec files:

import jasmine;
import something from ../src/something;

describe(something, () => {
    it(should work, () => {
        expect(something.works()).toBe(true);
    });
});

To run the tests:

npm test

This will use the locally installed versions of ts-node and jasmine. This is better than using globally installed versions, because with local versions, you can be sure that everyone is using the same version.

Note: if you have a web app instead of a node app, you should probably run your tests using Karma instead of the Jasmine CLI.

Put this at the top of your typescript spec file:

/// <reference path=../../node_modules/@types/jasmine/index.d.ts />
let Jasmine = require(jasmine);

You must install the following Jasmine modules for that to work:

$ npm install jasmine-core jasmine @types/jasmine @ert78gb/jasmine-ts --save-dev

Once you do that, the IDE (such as WebStorm) will recognize Jasmine and its functions such as describe(), it(), and expect().. So you dont need to prefix them with Jasmine. Also, you can run your spec files from the command line using the jasmine-ts module. Install these command line tools globally:

$ npm install -g jasmine @ert78gb/jasmine-ts

Then configure the jasmine command line module so that Jasmine can find its configuration file. Then you should be able to run jasmine-ts and your spec file should run fine from the command line:

./node_modules/.bin/jasmine-ts src/something.spec.ts

.. and, you can configure your IDE to run it like that as well, and debug runs that way should also work (works for me).

Writing your tests this way, you can run a Jasmine test spec on the server side without Karma, or run it in a web browser using Karma. Same typescript code.

javascript – Unit testing using Jasmine and TypeScript

If you have issues with imports, use tsconfig-paths

npm i ts-node tsconfig-paths types/jasmine jasmine --save-dev

Run typescript-enabled jasmine:

ts-node -r tsconfig-paths/register node_modules/jasmine/bin/jasmine.js

Ensure that your jasmine will search .ts files:

spec_files: [
    **/*[sS]pec.ts
],
helpers: [
    helpers/**/*.ts
],

To test your scripts you may also need polyfills if you use them in your project. Create a helper file with required imports, like helpers/global/polifill.ts

import core-js;

Leave a Reply

Your email address will not be published.