How to write test cases in Javascript?

Writing the test cases in Javascript is not nexus until we find the right way of less code with more concepts.

Shyam Verma
How to write test cases in Javascript?

(image: 1-question.png)

Let’s get started to get the answer to the above question by not wasting much time.

I am using the Jest library to write test cases. Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

First, you need to integrate the Jest library in order to work with it, so do this by command-

(If you choose yarn)

yarn add --dev jest

(If you choose npm)

npm install --save-dev jest

Next, add the following section to your package.json

Now create a directory of name tests and create two files inside it which will have names
multiply.js and multiply.test.js .

Drop the below code snippets in respected files-

Let’s understand the definitions of the keywords we have used here.

**expect-**This is a function that will be in use every time you want to test value, and it will take the function name (with or without arguments) you want to test.**toBe-**This is the matcher. When Jest runs, it will track all the failing matchers so that it can print out apt error messages.

In the above code, you can also use, “toStrictEqual” matcher. For example-

test('Multiplies 2*2 to equal 4', () => {

expect(doMultiply(2, 2)).toStrictEqual(4);

});

Now, it’s time to grab the fruit of our efforts. Let’s run the last following command to see the output-

(If you are using yarn)

yarn test

(If you are using npm)

npm run test

you will see that Jest has printed the testing results for you, it should be-

(image: 2-right-result.png)

Let’s add one more test case and pass the wrong result expectations into it.

test('Multiplies 3*3 to equal 6', () => {

expect(doMultiply(3, 3)).toBe(6);

});

After running the same test commands either yarn test or
npm run test ,
you should see the following result-

(image: 3-wrong-result.png)

You just successfully wrote your first test using Jest!

(image: 4-congo.gif)

Hope you have finished with much satisfaction.

Thanks, for reading.

Shyam Verma

Shyam Verma

Full Stack Developer & Founder

Shyam Verma is a seasoned full stack developer and the founder of Ready Bytes Software Labs. With over 13 years of experience in software development, he specializes in building scalable web applications using modern technologies like React, Next.js, Node.js, and cloud platforms. His passion for technology extends beyond coding—he's committed to sharing knowledge through blog posts, mentoring junior developers, and contributing to open-source projects.