Jest - Javascript testing

Jest - Javascript testing

2018-12-03 THUDM team Eunbi Choi

  1. Getting Started

    a. install jest

    npm install --save-dev jest

    b. edit package.json

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

    c. write a test file named sum.test.js

    test('adds 1 + 2 to equal 3', () => {
     expect(1+2).toBe(3);
    });

    d. run the test from command line

    npm test --

  2. API - Expect Methods

    a. Value

    // methods used frequently
    expect(n).toBe();
    expect(n).not.toBe();
    expect(n).toEqual();
    expect(n).toStrictEqual();
    expect(n).toBeNull();
    expect(n).toBeDefined();
    expect(n).toBeUndefined();
    expect(n).toBeTruthy();
    expect(n).toBeFalsy();

    b. Numbers

    expect(value).toBeGreaterThan(3); expect(value).toBeGreaterThanOrEqual(3.5);
    expect(value).toBeLessThan(5);
    expect(value).toBeLessThanOrEqual(4.5);

    c. Arrays

    expect(shoppingList).toContain('beer');

    d. Exceptions

    expect(compileAndroidCode).toThrow();
    expect(compileAndroidCode).toThrow(ConfigError);

    e. Promises

    expect(fetchData()).resolves.toBe('peanut butter');
    expect(fetchData()).rejects.toMatch('error');

    Complete method reference is here https://jestjs.io/docs/en/expect

  3. Setup and Teardown

    If you have some work you need to do repeatedly for many tests, you can use beforeEach and afterEach.

    If you need to setup or teardown once, you can use beforeAll and afterAll.

    beforeEach(() => {
     initializeCityDatabase();
    });
    afterEach(() => {
     clearCityDatabase();
    });
    beforeAll(() => {
     return initializeCityDatabase();
    });
    afterAll(() => {
     return clearCityDatabase();
    });
  4. Scoping - describe block

    By default, the before and after blocks apply to every test in a file. You can also group tests together using a describe block. When they are inside a describe block, the before and afterblocks only apply to the tests within that describe block.

    describe('matching cities to foods', () => {
     beforeEach(() => {
       return initializeFoodDatabase();
    });

     test('Vienna <3 sausage', () => {
       expect(isValidCityFoodPair('Vienna', 'WienerSchnitzel')).toBe(true);
    });

     test('San Juan <3 plantains', () => {
       expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
    });
    });
  5. Test Express.js with Supertest - test HTTP request

    First of all, you need to install babel-cli, babel-preset-env, jest, supertest and superagent.

    Test GET

    const request = require('supertest');
    const app = require('../app');

    describe('Test GET /', () => {
       test('It should return 200 status code', () => {
           return request(app).get('/').then(res => {
               expect(res.statusCode).toBe(200);
          });
      });
    });

    Test POST

    describe('Test GET /', () => {
       test('It should return some res', (done) => {
           return request(app)
              .post('/wechat?open_id=abc')
              .type('xml')
              .send('<xml>' +
                     '<ToUserName>testuser</ToUserName>' +
                     '<FromUserName>testuser</FromUserName>' +
                     '<CreateTime>1348831860</CreateTime>' +
                     '<MsgType>text</MsgType>' +
                     '<Content>testcontent</Content>' +
                     '<MsgId>1234567890</MsgId>' +
                     '</xml>');
              })
              .then(res => {
                   setTimeout(() => {
                   expect(res.text).toMatch('some res');
                   done();
                  }, 500);
              });

          });
      });
    });
  6. Mock function

    Mock functions make it easy to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new, and allowing test-time configuration of return values.

    jest.fn([implementation]) return a new, unused mock function.

    I used mock function to record all log strings in a string instead of printing it on command line. Below example is mocking console.log.

    let log_output = "";
    const storeLog = input => (log_output += input);

    test('It should save all log strings in log_output', () => {
       console.log = jest.fn(storeLog); // mock function
       execute_some_func()
          .then(() => {
          expect(log_output).toMatch('Success');
      });
    });
  7. Built-in code coverage reports

    The jest command line runner has a number of useful options. Below is one useful option coverage.

    --coverage: Indicates that test coverage information should be collected and reported in the output.

    We can easily create code coverage reports using --coverage. No additional setup or libraries needed! Jest can collect code coverage information from entire projects, including untested files.

  8. Reference

posted @ 2018-12-03 22:50  THUDMTEAM  阅读(274)  评论(0编辑  收藏  举报