Easy coding
Published in

Easy coding

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.

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

Let’s get started by not wasting much time staring at the girl above ;)

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

{   
"scripts":
{
"test": "jest"
}
}

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-

multiply.js

export const doMultiply = function (num1, num2) {   return num1 * num2;}

multiply.test.js

import {doMultiply} from './multiply';test('Multiplies 2 * 2 to equal 4', () => { 
expect(doMultiply(2, 2)).toBe(4);
});
test('Multiplies 3 * 2 to equal 6', () => {
expect(doMultiply(3, 2)).toBe(6);
});

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-

Result after running “yarn test”.

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 testor npm run test , you should see the following result-

Result after adding a wrong test case.

You just successfully wrote your first test using Jest!

Hope you have finished with much satisfaction.

I’d like to conclude with a big thank you. Thank you for reading my first story on medium and for being a part of my early journey.
With love,

Neha Soni

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Neha Soni

Neha Soni

Software Developer, Coder, Blogger.