Search code examples
typescriptunit-testingframeworks

How to write a unit test in Typescript?


I am new to software testing, and I was wondering how to write a unit test in Typescript.

I know someting about testing, that you have methods like Asser or assertEquals but how to do this in Typescript and do I need to pay attention the staticly typed classes?

I would like to unit test this funtion

function calculateAverage(...numbers: number[]): number {
     let sum = 0
     for (var n in numbers) {
         sum += n
     }
     return sum/numbers.length
}

So what framework should I use to produce some test that look like this:

assertEquals(calculateAverage(1,2,3), 2) // Actual and expected result

Anyone has an advice for what unit testing framework to use?


Solution

  • there are a few javascript testing frameworks, that you can also use in typescript, like mocha or jest. You often need to install the types as dependency, for example

    $ npm i -D @types/mocha
    

    but there are also fully in typescript written testing frameworks, but the often have a smaller community. So I recommend to start with jest or mocha. I personally prefer mocha in combination with chai as assertion library. My tests look like this:

    it( 'logStack === false', async () => {
        const customOptions: LogUpTsOptions = { quiet: true, logStack: false };
        const logger = new LogUpTs( customOptions );
        expect( await logger.error( new Error( 'first' ) ) ).to.eql( '[ERROR] first' );
        expect( await logger.log( 'second' ) ).to.eql( '[LOG] second' );
    } );
    

    tests for logupts

    Mocha works in nodejs and the browser (I sometimes use the karma runner for testing the browser).

    If you run your unit tests in nodejs, I recommend to install the following packages:

    • mocha // mocha as testing framework
    • @types/mocha // needed to use mocha in typescript
    • chai // needed for expect
    • @types/chai // needed to use chai in typescript
    • source-map-support // add source-map-support to nodejs
    • ts-node // run typescript directly in nodejs
    $ TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' mocha --opts ./mocha.opts
    

    my mocha.opts file:

    --require ts-node/register
    --require source-map-support/register
    --recursive
    src/**/*.spec.ts
    

    If you need something more "works out of the box" I think jest might be the right testing framework for you.