how to write a test with jest in javascript

To write a test with Jest in JavaScript, follow these steps:

  1. Make sure Jest is installed in your project. If not, install it by running the following command in your terminal:
index.tsx
npm install --save-dev jest
28 chars
2 lines
  1. Create a file named myfile.test.js (or any name you prefer) in your project's directory. This will be your test file.

  2. Write your test code in this file. Here's an example:

index.tsx
// myfile.test.js

// Function to be tested
function add(a, b) {
  return a + b;
}

// Test case
test('adds 1 + 2 to equal 3', () => {
  expect(add(1, 2)).toBe(3);
});
168 chars
12 lines
  1. In your terminal, run the following command to start the tests:
index.tsx
npm test
9 chars
2 lines

Jest will look for any files that end with .test.js in your project directory and run the tests inside them. If everything is working correctly, you should see a green message indicating that the test has passed.

Congratulations, you have just written your first test with Jest in JavaScript!

gistlibby LogSnag