Setting up Jest (Unit test) with Typescript - adonisv79/bytecommander.com GitHub Wiki
This assumes you are done with the previous guides on how to setup a typescript project. While some companies do not require strict unit testing and code coverage, it is up to us to ensure that our codes are clean and secured from ourselves messing it up. So as always, make sure what your functions should do, make the code that ensures the rules are followed and alert you when someone or yourself has made something that breaks the rule. this is the essence of Unit Testing. One of the best unit testing framework now are Mocha (with Chai) and Jest but I prefer the latter for no reason in particular other than the popularity of it. to start, run the following
npm i jest ts-jest @types/jest -D
this will install jest and its dependencies for typescript. now, This will not work yet until we configure jest to work for typescript by setting up a jest config file. you can manually create this or just run the following:
npx ts-jest config:init
this creates a new file 'jest.config.js' with the following basic content
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
if you have ESLint in the typescript project, make sure to update '.eslintrc' to include jest in the environment
{
"env": {
"jest": true
}
}
lastly, update package.json script to include a test script
{
"scripts": {
"test": "jest"
}
}
create a file in the src folder named 'jest-sample.ts and enter the following in it
export function sum(a: number, b: number): number {
return a + b;
}
export default class A { }
create a file in the src folder named 'jest-sample.test.ts and enter the following in it
import { sum } from './jest-sample';
test('Adds 1 + 2 to be 3', () => {
expect(sum(1, 2)).toBe(3);
});
test('Adds -99 and 99 to be 0', () => {
expect(sum(-99, 99)).toBe(0);
});
test('Adds -99 and 99 not to be NaN', () => {
expect(sum(-99, 99)).not.toBe(NaN);
});
test('Not Null check', () => {
expect(sum(234, 1)).not.toBeNull();
});
test('truthy check', () => {
expect(sum(234, 1)).toBeTruthy();
});
test('falsy check', () => {
expect(sum(234, 1)).not.toBeFalsy();
});
// comparison
test('Adds 1 + 2 to be greater than 1', () => {
expect(sum(1, 2)).toBeGreaterThan(1);
});
test('Adds 1 + 2 to be greater than or equal to 3', () => {
expect(sum(1, 2)).toBeGreaterThanOrEqual(3);
});
// for floating points
test('adding floating point numbers', () => {
// expect(value).toBe(0.3); This won't work because of rounding error
expect(sum(0.1, 0.2)).toBeCloseTo(0.3); // This works.
});
// regex
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'beer',
];
test('the shopping list has beer on it', () => {
expect(shoppingList).toContain('beer');
expect(new Set(shoppingList)).toContain('beer');
});
// exceptions
function compileAndroidCode() {
throw new Error('you are using the wrong JDK');
}
test('compiling android goes as expected', () => {
expect(compileAndroidCode).toThrow();
expect(compileAndroidCode).toThrow(Error);
// You can also use the exact error message or a regexp
expect(compileAndroidCode).toThrow('you are using the wrong JDK');
expect(compileAndroidCode).toThrow(/JDK/);
});
// Async/Await
async function fetchData(err: boolean): Promise<string> {
if (!err) {
return 'success';
}
throw new Error('Forced error');
}
test('the data is success', async () => {
const data = await fetchData(false);
expect(data).toBe('success');
});
test('the fetch fails with an error', async () => {
expect.assertions(1);
try {
await fetchData(true);
} catch (e) {
expect(e.message).toMatch('Forced error');
}
});
run the following in the terminal
npm run test
you will receive the following output
PASS src/jest-sample.test.ts
√ Adds 1 + 2 to be 3 (3ms)
√ Adds -99 and 99 to be 0 (1ms)
√ Adds -99 and 99 not to be NaN
√ Not Null check (1ms)
√ truthy check
√ falsy check
√ Adds 1 + 2 to be greater than 1
√ Adds 1 + 2 to be greater than or equal to 3
√ adding floating point numbers
√ there is no I in team (1ms)
√ the shopping list has beer on it
√ compiling android goes as expected (4ms)
√ the data is peanut butter (1ms)
√ the fetch fails with an error (1ms)
Test Suites: 1 passed, 1 total
Tests: 14 passed, 14 total
Snapshots: 0 total
Time: 3.425s, estimated 4s
Ran all test suites.
References: