Javascript

What is Jest and How to use it in testing?


Spring Datafication 2022. 10. 8. 13:38

Jest is a JavaScript testing framework maintained by Facebook, Inc. Jest is well known for its speed, reliability, and ease of use.
It works out of the box for most JavaScript projects. Jest is a complete and ready to set-up JavaScript testing solution. It lets you write tests with an approachable, familiar and feature-rich API that gives you results quickly. Jest is well-documented, requires little configuration and can be extended to match your requirements.

How to use Jest in testing?

Pre-requisites

- Node.js
- npm
- Jest

In this example lets see how we can use jest in testing our typescript code. So we need to install jest and typescript.

npm install --save-dev jest

or just this command for both jest and typescript

npm i -D jest typescript

package.json

Our package.json file should look like this for our dependencies.

{
  "name": "fas-typeScripting",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "doc": "doc"
  },
  "scripts": {
    "test": "jest"
  },
  "repository": {
    "type": "git"
  },
  "keywords": [],
  "author": "Fas",
  "license": "ISC",
  "dependencies": {
    "@types/jest": "^29.1.2",
    "@types/node": "^16.11.6",
    "jest": "^29.0.0",
    "ts-jest":  "^29.0.0",
    "typescript": "^4.5.2"
  },
  "devDependencies": {
    "jest": "^29.0.3",
    "jest-environment-jsdom": "^29.0.3",
    "typescript": "^4.8.3"
  }

}

Jest Configuration

Jest configuration is done in the package.json file. We can also create a separate configuration file for jest. In this example we will be using the jest.config.js file for jest configuration.

module.exports = {
    preset: "ts-jest",
    testEnvironment: "node"
};

or use the command npx ts-jest config:init to create a jest.config.js file.

Write a test

regular-expression-matching (Leetcode-H)
our code in separate file(regular-expression-matching.ts) and import it in our test file.

export default  function isMatch(s: string, p: string): boolean {
    if(p.length==0){
        return s.length==0;
    }
    if(p.length==1){
        return s.length==1&&(p[0]==s[0]||p[0]=='.');
    }
    if(p[1]!='*'){
        if(s.length==0){
            return false;
        }
        return (p[0]==s[0]||p[0]=='.')&&isMatch(s.substring(1),p.substring(1));
    }
    while(s.length>0&&(p[0]==s[0]||p[0]=='.')){
        if(isMatch(s,p.substring(2))){
            return true;
        }
        s=s.substring(1);
    }
    return isMatch(s,p.substring(2));
}

The test file

The test file should be in the same directory as the code file. The test file should have the same name as the code file with the .test extension. In this example we will be using the regular-expression-matching.test.ts file for testing our code.

import isMatch from './c10RegularExpressionMatching'

describe('isMatch', () => {
    it('isMatch', () => {
        expect(isMatch("aa","a")).toEqual(false);
        expect(isMatch("aa","a*")).toEqual(true);
        expect(isMatch("ab",".*")).toEqual(true);
        expect(isMatch("aab","c*a*b")).toEqual(true);
        expect(isMatch("mississippi","mis*is*p*.")).toEqual(false);
    });
});

Common Bash Commands in testing

Run your tests

npm test

Coverage reports

npm test -- --coverage

Continuous Integration

npm test -- --ci --coverage

Update snapshots

npm test -- -u

Run tests from one file

npm test -- FileName

Run tests with a test name pattern

npm test -- -t 'pattern'

Run tests in band

npm test -- --runInBand

Run tests in a specific environment

npm test -- --env=jsdom

Run tests with a specific config

npm test -- --config=customConfig.json

Run tests with a specific global setup file

npm test -- --globalSetup=customSetup.js

Run tests with a specific global teardown file

npm test -- --globalTeardown=customTeardown.js

Run tests with a specific reporter

npm test -- --reporters=default

Run tests with a specific test results processor

npm test -- --testResultsProcessor=customProcessor.js

Run tests with a specific test sequencer

npm test -- --testSequencer=customSequencer.js

Run tests with a specific watch plugins

npm test -- --watchPlugins=customPlugin.js

Common jest functions

afterAll(fn, timeout)

How the afterAll function works is that it runs after all the tests in the file have been executed. It is used to clean up the resources that were used in the tests. It is also used to close the database connection or to close the server connection.

afterAll(() => {
    console.log('afterAll');
});

afterEach(fn, timeout)

The afterEach function is used to clean up the resources that were used in the tests. It is also used to close the database connection or to close the server connection.

afterEach(() => {
  console.log('afterEach');
});

beforeAll(fn, timeout)

The beforeAll function is used to initialize the resources that will be used in the tests. It is also used to open the database connection or to open the server connection.

beforeAll(() => {
  console.log('beforeAll');
});

beforeEach(fn, timeout)

The beforeEach function is used to initialize the resources that will be used in the tests. It is also used to open the database connection or to open the server connection.

beforeEach(() => {
  console.log('beforeEach');
});

describe(name, fn)

The describe function is used to group the tests. It is used to group the tests that are related to each other. It is also used to group the tests that are related to a specific feature.

describe('outer', () => {
  console.log('describe outer-a');

  describe('describe inner 1', () => {
    console.log('describe inner 1');
  });

  console.log('describe outer-b');

  describe('describe inner 2', () => {
    console.log('describe inner 2');
  });

  console.log('describe outer-c');
});

test(name, fn, timeout)

The test function is used to write the test cases. It is used to write the test cases for the code that we have written.

test('this will be used as the description', () => {
  expect(true).toBe(true);
});

test.only(name, fn, timeout)

The test.only function is used to write the test cases. It is used to write the test cases for the code that we have written. The difference between the test function and the test.only function is that the test function will run all the test cases in the file while the test.only function will run only the test cases that are written using the test.only function.

test.only('this will be the only test that runs', () => {
  expect(true).toBe(false);
});

test('this test will not run', () => {
  expect('A').toBe('A');
});

test.skip(name, fn, timeout)

The test.skip function is used to write the test cases. It is used to write the test cases for the code that we have written. The difference between the test function and the test.skip function is that the test function will run all the test cases in the file while the test.skip function will skip the test cases that are written using the test.skip function.

test.skip('this test will not be run', () => {
  expect('A').toBe('A');
});

test.concurrent(name, fn, timeout)

The test.concurrent function is used to write the test cases. It is used to write the test cases for the code that we have written. The difference between the test function and the test.concurrent function is that the test function will run the test cases in the file sequentially while the test.concurrent function will run the test cases in the file concurrently.

test.concurrent('this test runs concurrently with others', () => {
  expect(true).toBe(true);
});

test.concurrent.only(name, fn, timeout)

The test.concurrent.only function is used to write the test cases. It is used to write the test cases for the code that we have written. The difference between the test.concurrent function and the test.concurrent.only function is that the test.concurrent function will run the test cases in the file concurrently while the test.concurrent.only function will run only the test cases that are written using the test.concurrent.only function.

test.concurrent.only('this test runs concurrently with others', () => {
  expect(true).toBe(true);
});

test.concurrent.skip(name, fn, timeout)

The test.concurrent.skip function is used to write the test cases. It is used to write the test cases for the code that we have written. The difference between the test.concurrent function and the test.concurrent.skip function is that the test.concurrent function will run the test cases in the file concurrently while the test.concurrent.skip function will skip the test cases that are written using the test.concurrent.skip function.

test.concurrent.skip('this test runs concurrently with others', () => {
  expect(true).toBe(true);
});

test.each(table)(name, fn, timeout)

The test.each function is used to write the test cases. It is used to write the test cases for the code that we have written. The difference between the test function and the test.each function is that the test function will run the test cases in the file sequentially while the test.each function will run the test cases in the file concurrently.

test.each([
  [1, 1, 2],
  [1, 2, 3],
  [2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
  expect(a + b).toBe(expected);
});

test.each(table).only(name, fn, timeout)

The test.each.only function is used to write the test cases. It is used to write the test cases for the code that we have written. The difference between the test.each function and the test.each.only function is that the test.each function will run the test cases in the file concurrently while the test.each.only function will run only the test cases that are written using the test.each.only function.

test.each([
  [1, 1, 2],
  [1, 2, 3],
  [2, 1, 3],
]).only('.add(%i, %i)', (a, b, expected) => {
  expect(a + b).toBe(expected);
});

test.each(table).skip(name, fn, timeout)

The test.each.skip function is used to write the test cases. It is used to write the test cases for the code that we have written. The difference between the test.each function and the test.each.skip function is that the test.each function will run the test cases in the file concurrently while the test.each.skip function will skip the test cases that are written using the test.each.skip function.

test.each([
  [1, 1, 2],
  [1, 2, 3],
  [2, 1, 3],
]).skip('.add(%i, %i)', (a, b, expected) => {
  expect(a + b).toBe(expected);
});

test.todo

The test.todo function is used to write the test cases. It is used to write the test cases for the code that we have written. The difference between the test function and the test.todo function is that the test function will run the test cases in the file sequentially while the test.todo function will run the test cases in the file concurrently.

test.todo('this test is a todo');

Reference

반응형

'Javascript' 카테고리의 다른 글

ES6 $(this) Problem in jQuery Callback by arrow function  (0) 2022.08.15