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.

Neha Soni , 12 October, 2020

Is it possible to write test cases in a short time?



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-


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-


You just successfully wrote your first test using Jest!

Hope you have finished with much satisfaction.

Thanks, for reading.

blog comments powered by Disqus