美文网首页
jest简介

jest简介

作者: antlove | 来源:发表于2020-10-15 17:23 被阅读0次

一、 环境准备
yarn init
package.json 如下

{
  "name": "jest",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "axios": "^0.20.0",
    "jest": "^26.5.3"
  }
}

二、hello world 案例
sum.js

function sum(a, b) {
    return a + b;
}
module.exports = sum;

sum.test.js

const sum = require('./sum');

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

执行 yarn test


image.png

三、 expect 常用API

方法 描述
toBe 使用Object.is比较
toEqual 比较对象,递归检测对象或者数组的每个字段
toBeCloseTo 用于比较浮点数
toContain 判定数组中是否包含指定的值
toThrow 判定数组是否会抛出错误,可以指定错误信息

四、 测试异步方法
只是罗列了Promise 和 .resolves / .rejects 2 中方法。点击链接查看更多详情

const fetchData = () => {
    return new Promise((resolve, reject) => {
        resolve(20);
        // reject('error');
    });
};

test('async test', () => {
    /* promise  */
    // return fetchData().then(data => {
    //    expect(data).toBe(20);
    // });

    // expect.assertions(1); // 确保 fetchData.resolve时 可以判定这次测试是失败的
    // return fetchData().catch(e => expect(e).toMatch('error'));

    /* .resolves / .rejects */
    // return expect(fetchData()).resolves.toBe(20);
    // return expect(fetchData()).rejects.toMatch('error');
});

五、 mock简单使用

const axios = require('axios');
const request = () => axios.get('/users.json').then(resp => resp.data);

jest.mock('axios');

test('mock', () => {
    const users = [{name: 'Bob'}];
    const resp = {data: users};
    axios.get.mockResolvedValue(resp);
    return request().then(data => expect(data).toEqual(users));
});

六、小技巧
在一个测试单元(xxx.test.js文件)中使用test.only 那其他的test将被跳过

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

相关文章

网友评论

      本文标题:jest简介

      本文链接:https://www.haomeiwen.com/subject/xjhopktx.html