Simple test
Contents
In this chapter, you’ll add code, and test it with Jest.
How it works
-
Test files import from sources and defines test cases with assertions.
-
Test files written for Jest uses
describe
and (test
/it
) functions to organize the test cases. -
The
expect
function is used to write assertions and returns an object which contains a bunch of Jest matchers. -
The test below uses the
toEqual
matcher, see https://jestjs.io/docs/using-matchers for more matchers.
Source code
Add the source file to your project:
src/main/resources/lib/myproject/fibonacci.ts
export function fibonacci(n: number): number[] {
const fib = [0, 1];
for (let i = fib.length; i < n; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
return fib;
}
Source code should (as always) be placed within the /src/main/resources section of your project |
The test
Now, add your test file:
src/jest/server/fibonacci.test.ts
import {
describe,
expect,
test as it
} from '@jest/globals';
import { fibonacci } from '/lib/myproject/fibonacci';
describe('fibonacci', () => {
it('should return the first 10 numbers in the fibonacci sequence', () => {
expect(fibonacci(10)).toEqual([0, 1, 1, 2, 3, 5, 8, 13, 21, 34]);
});
});
By default, your tests should be placed in /src/jest . |
Execution
Run the tests:
npm run cov src/jest/server/fibonacci.test.ts
This should produce an output looking something like this:
> tutorial-jest@1.0.0 test
> jest --no-cache --coverage src/jest/server/fibonacci.test.ts
PASS SERVER src/jest/server/fibonacci.test.ts
fibonacci
✓ should return the first 10 numbers in the fibonacci sequence (3 ms)
--------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
fibonacci.ts | 100 | 100 | 100 | 100 |
--------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.029 s
Ran all test suites matching /src\/jest\/server\/fibonacci.test.ts/i.