Jest is an open-source testing framework that has become increasingly popular recently. Developed by Facebook and built into the popular packagecreate-react-app
. Jest comes with built-in mocking and assertion abilities. In addition, Jest runs your tests concurrently in parallel, providing a smoother, faster test run.
Setting up a new project with Jest
Using npm: npm i -D jest
Using yarn:yarn add --dev jest
Simple Jest Test:
In package.json
{
"scripts": {
"test": "jest"
}
}
In functions.js file
const functions = {
add: (num1, num2) => num1 + num2
};
module.exports=functions;
In functions.test.js file
const functions=require('./functions');
describe("Addition", () => {
it("should add two numbers ", () => {
expect(functions.add(2,2,)).toBe(4);
});
});
Run yarn test or npm test, see the results below
PASS ./functions.test.js
Addition
✓ should add two numbers (11ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.035s
Ran all test suites.
Failure scenario:
const functions=require('./functions');
describe("Addition", () => {
it("should add two numbers ", () => {
expect(functions.add(2,2,)).toBe(5); #here expecting 5 instead of 4.
});
});
FAIL ./functions.test.js
Addition
✕ should add two numbers (9ms)
● Addition › should add two numbers
expect(received).toBe(expected) // Object.is equality
Expected: 5
Received: 4
4 | describe("Addition", () => {
5 | it("should add two numbers ", () => {
> 6 | expect(functions.add(2,2,)).toBe(5);
| ^
7 | });
8 | });
9 |
at Object.toBe (functions.test.js:6:33)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 3.692s
Ran all test suites.
npm ERR! Test failed. See above for more details.