Here is a short practice on Jest:
- Create a new project: Create a new project directory and navigate into it.
- Initialize npm: Run
npm init
to initialize the project with npm and create apackage.json
file. - Install Jest: Run the following command to install Jest as a development dependency:
cssCopy codenpm install --save-dev jest
- Create a JavaScript file: Create a file named
add.js
that contains a simple function that adds two numbers:
javascriptCopy codefunction add(a, b) {
return a + b;
}
module.exports = add;
- Create a test file: Create a file named
add.test.js
that contains the test cases for theadd
function:
scssCopy codeconst add = require("./add");
test("adds 1 + 2 to equal 3", () => {
expect(add(1, 2)).toBe(3);
});
test("adds 2 + 2 to equal 4", () => {
expect(add(2, 2)).toBe(4);
});
- Run tests: Run the following command to run the tests:
Copy codenpx jest
Jest will display the results of the tests, indicating whether each test passed or failed.
- Write more tests: Try writing more tests for the
add
function, using different values fora
andb
. For example, test what happens whena
orb
is negative, or when one of them is a decimal.
By practicing writing tests with Jest, you can gain a better understanding of how to write effective tests for your JavaScript applications.