Step 1: Install packages for unit testing
Unit tests assert
some properties of the code. For example a method add(x,y)
should correctly add x and y.
With a unit test you can then test some sample cases like assert(add(3,4)).equals(7)
.
To get this assert
method and to execute tests in the first place, we need some testing software.
Here we'll choose Mocha and Chai.
To install mocha and chai, you can run:
yarn add mocha @types/mocha chai @types/chai ts-node typescript --dev
You will need to have yarn
installed for this to work,
see install manual.
Step 2: Writing your first unit test
Let's say you have the following unit:
export function add(x: number, y: number) { return x + y; }
Then a first unit test could look like:
import { add } from './math'; import * as mocha from 'mocha'; import * as chai from 'chai'; const expect = chai.expect; describe('My math library', () => { it('should be able to add things correctly' , () => { expect(add(3,4)).to.equal(7); }); });
Step 3: Run the unit test(s)
You can run the test with the following command:
mocha --reporter spec --compilers ts:ts-node/register src/**/*.test.ts
And basically that's it. You should see an output in the console, that looks like this:
You can put this long command into package.json
into
"scripts: { "test": "..."}"
and then run the tests with npm test
.
So the complete package.json at this point would look like:
{ "devDependencies": { "@types/chai": "^4.0.0", "@types/mocha": "^2.2.41", "chai": "^4.0.2", "mocha": "^3.4.2", "ts-node": "^3.1.0" }, "scripts": { "test": "mocha --reporter spec --compilers ts:ts-node/register 'src/**/*.test.ts'" } }
If you want to run a single test, run
mocha --reporter spec --compilers ts:ts-node/register --grep "TestName" 'src/**/*.test.ts'
where "TestName" matches any describe
or it
. What's also quite cool, with
IntelliJ you can setup your unit tests such that you can execute single tests right from the code!
Here is the manual.
Now you can either ...