Jest - Javascript testing

本文详细介绍使用 Jest 进行 JavaScript 测试的方法,包括安装配置、编写测试用例、使用 expect 断言方法、设置前后置操作、描述块的使用、HTTP 请求测试以及模拟函数的应用。同时提供代码覆盖率报告的生成方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/THUDM/p/10061580.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值