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:
npm install --save-dev mocha @types/mocha chai @types/chai ts-node typescript
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 { expect } from 'chai';
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 --require 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.3.0",
"@types/mocha": "^10.0.0",
"chai": "^4.4.0",
"mocha": "^11.7.0",
"ts-node": "^10.9.0",
"typescript": "^6.0.0"
},
"scripts": {
"test": "mocha --require ts-node/register 'src/**/*.test.ts'"
}
}
If you want to run a single test, run
mocha --require 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 ...