频道
bg

Jest Getting Started

coding十二月 08, 20201mins
Jest Frontend

概述H1

对于测试,我们一般需要

  • 测试框架 定义测试,调用测试方法,报告测试结果等,比如mocha、chai
  • 启动器 启动测试环境,并在测试环境中运行测试框架,比如karma
  • 断言库 对测试结果进行断言,一般测试框架会自带基础的断言
  • mock库 单元测试需要对mock来模拟外部依赖的调用,比如Sinon.JS

Jest作为一个完整的测试框架,涵盖了上述所有的功能。但是Jest运行在Node环境,并使用jsdom模拟浏览器环境。

快速开始H1

添加依赖

bash

npm install --save-dev jest

package.json添加任务

bash

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

添加测试类

jsx

// 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);
});

运行npm run test

jsx

PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)

预处理H2

如果代码需要运行前,需要预编译、打包处理等。Jest支持配置babel、webpack进行相关处理。

断言H2

Jest使用matchers来进行断言,针对布尔、数字、字符串、数组等对象提供了基本的matcher方法。

异步测试H2

如果需要测试的结果是异步返回的,需要做一些特殊处理

如果在callback中断言,Jest不会等待异步请求结束

jsx

// Don't do this!
test('the data is peanut butter', () => {
function callback(data) {
expect(data).toBe('peanut butter');
}
fetchData(callback);
});

但是如果返回promise,Jest会等待异步请求结束进行断言

jsx

test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});

另外,还可以使用async、await

jsx

test('the fetch fails with an error', async () => {
expect.assertions(1);
try {
await fetchData();
} catch (e) {
expect(e).toMatch('error');
}
});

MockH2

mock 函数H3

jsx

const mockCallback = jest.fn(x => 42 + x);
forEach([0, 1], mockCallback);

mock模块H3

jsx

// users.js
import axios from 'axios';
class Users {
static all() {
return axios.get('/users.json').then(resp => resp.data);
}
}
export default Users;
// users.test.js
import axios from 'axios';
import Users from './users';
jest.mock('axios');
test('should fetch users', () => {
const users = [{name: 'Bob'}];
const resp = {data: users};
axios.get.mockResolvedValue(resp);
// or you could use the following depending on your use case:
// axios.get.mockImplementation(() => Promise.resolve(resp))
return Users.all().then(data => expect(data).toEqual(users));
});

.mock属性H3

jest.mock 相关方法返回的是mock对象,它包含一个.mock属性,包含了mock相关的信息

jsx

// The function was called exactly once
expect(someMockFunction.mock.calls.length).toBe(1);
// The first arg of the first call to the function was 'first arg'
expect(someMockFunction.mock.calls[0][0]).toBe('first arg');
// The second arg of the first call to the function was 'second arg'
expect(someMockFunction.mock.calls[0][1]).toBe('second arg');
// The return value of the first call to the function was 'return value'
expect(someMockFunction.mock.results[0].value).toBe('return value');
// This function was instantiated exactly twice
expect(someMockFunction.mock.instances.length).toBe(2);
// The object returned by the first instantiation of this function
// had a `name` property whose value was set to 'test'
expect(someMockFunction.mock.instances[0].name).toEqual('test');

评论


新的评论

匹配您的Gravatar头像

Joen Yu

@2022 JoenYu, all rights reserved. Made with love.