Javascript jest
From wikinotes
A test framework for javascript.
Documentation
intro https://jestjs.io/docs/getting-started home https://jestjs.io/ assertions https://jestjs.io/docs/expect#expect
Usage
General
./node_modules/.bin/jest \ --no-coverage \ --colors `# force colours` \ -t $DESCRIBE_REGEX $IT_REGEX `# regex match tests` \ $TEST_FILEPATHDebugger Statements
Run tests, with interactive repl for
debugger;statements where you've entered them in your code.# 1. run test, with server on port 9330 (one variant of these) node --inspect-brk=9330 ./node_modules/jest/bin/jest.js --runInBand some/test.js # OR NODE_OPTIONS='--unhandled-rejections=warn --inspect-brk=9330' jest --runInBand some/test.js # 2. connect to the server in a separate nodejs process node inspect 127.0.0.1:9330 # 3. use one of the provided commands help # show commands// note that: // - logging will occur in the test-runner process // - you'll be at a prompt until you hit a breakpoint in the server list() // show current place in stack repl // enter stack, allow you to 'console.log()' variables .exit / ctrl-c // exit 'repl'
Basics
// ${project}/foo.js function sum(a, b) { return a + b; }// ${project}/foo.test.js const sum = require('./foo.js'); test('1 + 2 is 3', () => { expect(sum(1, 2)).toBe(3); })
Features
Only (focus)
only lets you focus/run just a single test from the file.
it.only('does thing', () => { expect(true).toBe(false) })Each (parametrize tests)
test.each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ])('adds %i + %i to equal %i', (a, b, expected) => { expect(a + b).toBe(expected); });beforeEach / afterEach hooks
let user: User; beforeEach(() => { user = new User(); }); it('has a name', () => { expect(user.name).toBe('foouser'); });Expect Exceptions
// regular functions expect(() => { throw new TypeError('Wrong type'); }).toThrow(TypeError); // async functions await expect(async () => { throw new Error('Async error'); }).rejects.toThrow('Async error'); // or await expect(someAsyncFunction()).rejects.toThrow();Mocks
SpyOn
const mySpy = jest.spyOn(some.obj, 'someFunction'); expect(myspy).toHaveBeenCalled(); expect(myspy).toHaveBeenCalledWith(1, 2, 3); const mod = require('some/module'); const modSpy = jest.spyOn(mod, 'someFunction');Replace the function's behaviour
// for regular functions const spyStringify = jest .spyOn(JSON, 'stringify') .mockImplementation(() => throw Error('oh no!')); // for async functions const spyFoo = jest .spyOn(myMod, 'someAsyncFunc') .mockRejectedValue(new Error('oh no!')); const spyFoo = jest .spyOn(myMod, 'someAsyncFunc') .mockResolvedValue('success!');