DEV Community

Cover image for Write test cases in JS
NEHA SONI
NEHA SONI

Posted on

Write test cases in JS

Writing the test cases in JS 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?

Image description

Let's get started this.

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, so do this by command-

(If you choose yarn)

yarn add --dev jest
Enter fullscreen mode Exit fullscreen mode

(If you choose npm)

npm install --save-dev jest
Enter fullscreen mode Exit fullscreen mode

Next, add the following section to your package.json

{   
   "scripts": 
      {
         "test": "jest" 
      }
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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); 
});
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

(If you are using npm)

npm run test
Enter fullscreen mode Exit fullscreen mode

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

Image description

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);
});
Enter fullscreen mode Exit fullscreen mode

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

Image description

You just successfully wrote your first test using Jest!

Image description

Hope you have finished with much satisfaction.

With love,

Neha Soni

Top comments (0)