我们创建了这样一个 math.js 的测试文件。其中 describe 类似 Jasmine 中的 describe, 属于 test suite 的描述,而每个 test 或者 it 则描述了每个 test case。
1
2
3
4
5
6
7
8
9
10
// math.test.js
describe("math",()=>{test("#should return result as a+b",()=>{// test code
});it("#should return result as a*b",()=>{//test code
});});
// 内置断言
test("two plus two is four",()=>{expect(2+2).toBe(4);});test("object assignment",()=>{constdata={one:1};data["two"]=2;expect(data).toEqual({one:1,two:2});});test("adding positive numbers is not zero",()=>{for(leta=1;a<10;a++){for(letb=1;b<10;b++){expect(a+b).not.toBe(0);}}});//
// Custom断言
expect.extend({toBeDivisibleBy(received,argument){constpass=received%argument==0;if(pass){return{message:()=>`expected ${received} not to be divisible by ${argument}`,pass:true};}else{return{message:()=>`expected ${received} to be divisible by ${argument}`,pass:false};}}});test("even and odd numbers",()=>{expect(100).toBeDivisibleBy(2);expect(101).not.toBeDivisibleBy(2);expect({apples:6,bananas:3}).toEqual({apples:expect.toBeDivisibleBy(2),bananas:expect.not.toBeDivisibleBy(2)});});
// fooBar.js
exportconstgetFooResult=()=>{// foo logic here
};exportconstgetBarResult=()=>{// bar logic here
};// caculate.js
import{getFooResult,getBarResult}from"./math";exportconstgetFooBarResult=()=>getFooResult()+getBarResult();
// foo.js
module.exports=function(){// some implementation;
};// test.js
jest.mock('../foo');// this happens automatically with automocking
constfoo=require('../foo');// foo is a mock function
foo.mockImplementation(()=>42);foo();// > 42
// request.js
consthttp=require('http');exportdefaultfunctionrequest(url){returnnewPromise(resolve=>{// This is an example of an http request, for example to fetch
// user data from an API.
// This module is being mocked in __mocks__/request.js
http.get({path:url},response=>{letdata='';response.on('data',_data=>(data+=_data));response.on('end',()=>resolve(data));});});}
// __mocks__/request.js
constusers={4:{name:'Mark'},5:{name:'Paul'},};exportdefaultfunctionrequest(url){returnnewPromise((resolve,reject)=>{constuserID=parseInt(url.substr('/users/'.length),10);process.nextTick(()=>users[userID]?resolve(users[userID]):reject({error:'User with '+userID+' not found.',}),);});}
我们创建了这样一个mock文件,该文件指明了request的mock。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// __tests__/user-test.js
jest.mock('../request');import*asuserfrom'../user';// The assertion for a promise must be returned.
it('works with promises',()=>{expect.assertions(1);returnuser.getUserName(4).then(data=>expect(data).toEqual('Mark'));});it('works with resolves',()=>{expect.assertions(1);returnexpect(user.getUserName(5)).resolves.toEqual('Paul');});