Testing is a critical part of the development process. It ensures that your code works as expected, is reliable, and reduces the chances of bugs appearing in production. There are two major types of tests:
Jest is a popular testing framework, especially for React applications. It includes a test runner and assertion library.
Mocha is another popular framework often used with Node.js and allows you to use different assertion libraries like Chai.
Here’s an example of how to write test cases using Jest. Let’s say you have a simple function `add` that adds two numbers together:
// add.js
function add(a, b) {
return a + b;
}
module.exports = add;
// add.test.js
const add = require('./add');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
test('adds -1 + 2 to equal 1', () => {
expect(add(-1, 2)).toBe(1);
});
TDD is an approach where you write tests before the code, following the "Red-Green-Refactor" cycle.
// multiply.test.js
const multiply = require('./multiply');
test('multiplies 2 and 3 to equal 6', () => {
expect(multiply(2, 3)).toBe(6);
});
// multiply.js
function multiply(a, b) {
return a * b;
}
module.exports = multiply;
After writing your tests, you can run them using Jest. To do so, run the following command:
npx jest