Skip to content

Latest commit

 

History

History
87 lines (61 loc) · 2.5 KB

typescript.md

File metadata and controls

87 lines (61 loc) · 2.5 KB

TypeScript

Translations: Español, Français, Italiano, Русский, 简体中文

AVA comes bundled with a TypeScript definition file. This allows developers to leverage TypeScript for writing tests.

Setup

First install TypeScript (if you already have it installed, make sure you use version 2.1 or greater).

$ npm install --save-dev typescript

Create a tsconfig.json file. This file specifies the compiler options required to compile the project or the test file.

{
	"compilerOptions": {
		"module": "commonjs",
		"target": "es2015"
	}
}

Add a test script in the package.json file. It will compile the project first and then run AVA.

{
  "scripts": {
    "test": "tsc && ava"
  }
}

Add tests

Create a test.ts file.

import test from 'ava';

async function fn() {
    return Promise.resolve('foo');
}

test(async (t) => {
    t.is(await fn(), 'foo');
});

Working with context

By default, the type of t.context will be any. AVA exposes an interface RegisterContextual<T> which you can use to apply your own type to t.context. This can help you catch errors at compile-time:

import * as ava from 'ava';

function contextualize<T>(getContext: () => T): ava.RegisterContextual<T> {
    ava.test.beforeEach(t => {
        Object.assign(t.context, getContext());
    });

    return ava.test;
}

const test = contextualize(() => ({ foo: 'bar' }));

test.beforeEach(t => {
    t.context.foo = 123; // error:  Type '123' is not assignable to type 'string'
});

test.after.always.failing.cb.serial('very long chains are properly typed', t => {
    t.context.fooo = 'a value'; // error: Property 'fooo' does not exist on type '{ foo: string }'
});

test('an actual test', t => {
    t.deepEqual(t.context.foo.map(c => c), ['b', 'a', 'r']); // error: Property 'map' does not exist on type 'string'
});

Execute the tests

$ npm test