Jest Practice Exercises: Essential Techniques for Mastering the Framework

Here is a short practice on Jest:

  1. Create a new project: Create a new project directory and navigate into it.
  2. Initialize npm: Run npm init to initialize the project with npm and create a package.json file.
  3. Install Jest: Run the following command to install Jest as a development dependency:
cssCopy codenpm install --save-dev jest
  1. 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;
  1. Create a test file: Create a file named add.test.js that contains the test cases for the add 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);
  1. 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.

  1. Write more tests: Try writing more tests for the add function, using different values for a and b. For example, test what happens when a or b 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.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *