How to write a basic test in Jest?
Here is a simple example of a basic unit test in Jest.
1. There is a regular function
sum.js:
js
function sum(a, b) {
return a + b;
}
module.exports = sum;2. Write the test
sum.test.js:
js
const sum = require("./sum");
test("correctly adds two numbers", () => {
expect(sum(2, 3)).toBe(5);
});3. Running the test
The package.json should have a script:
json
{
"scripts": {
"test": "jest"
}
}Then in the terminal:
javascript
npm testWhat's happening here
test(...)- describes the checkexpect(...)- takes the actual result of the functiontoBe(...)- compares it with the expected value
If sum(2, 3) returns 5, the test passes. If it returns anything else, Jest shows an error and points out where the mismatch is.
That is a basic test: function → expected result → comparison.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.