O'Reilly logo

TypeScript Blueprints by Ivo Gabe de Wolff

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Writing unit tests

Functional written code is usually easier to test with a unit test. A unit test is an automated test that checks whether a small piece of code is working. We will use the ava test runner, which we can install using NPM:

npm install ava --save-dev
npm install ava -g

At the time of writing, ava does not have type definitions bundled. We will quickly add some types for it in lib/test/ava.d.ts:

declare module "ava" { 
  function test(name: string, run: (t: any) => void): void; 
  namespace test {} 
  export = test; 
} 

We can now write some tests for the factorial function. In lib/test/utils.ts, we write a test case. Any test file will have the following structure:

import * as test from "ava"; import { factorial } from "../model/utils"; test("factorial", ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required