Jest入门说明Jest是一个令人愉快的JavaScript测试框架,专注于简单性。它适用于使用以下项目的项目:Babel、TypeScript、Node、React、Angular、Vue等等!失去人性,失去很多;失去动物性,失去一切。--三体使用新项目$mkdirjestTest&&cd./jestTest$npminit-yinstalljest#初始化jest配置$npxjest--init#安装$npminstall-Djest*configurebabel$npminstall-D@babel/core@babel/preset-env$touchbabel.config.jsbabel.config.js内容module.exports={presets:[["@babel/preset-env",{targets:{node:'current'}}],]}创建文件$mkdirsrc&&cd./src$touchindex.jsindex.test.jsmatcherexpect(1+2).toBe(3);//精确匹配expect({one:1}).toEqual({one:1});//深度匹配expect(null).toBeNull();//空匹配expect(undefined).toBeUndefined();//未定义匹配expect(var).toBeDefined();//var是否定义了expect(true).toBeTruthy();//true匹配expect(false).toBeFalsy();//false匹配expect(false).not.toBe(true);//否定匹配expect(1).toBeGreaterThan(0);//大于expect(1).toBeLessThan(2);//小于expect(1).toBeGreaterThanOrEqual(1);//大于或等于expect(1).toBeLessThanOrEqual(1);//小于或等于expect(0.1+0.2).toBeCloseTo(0.3);//floatPointsexpect('toMatch').toMatch(/to/)//是否包含expect([1,2,3]).toContain(1)//是否包含一些元素expect(()=>{thrownewError()}).toThrow();//异常匹配异步回退函数loadData(){returnnewPromise((resolve,reject)=>{resolve({code:200,data:{}});})}//通过返回test('shouldloadData',async()=>{//expect.assertions(1);//必须执行expectreturnloadData().then(res=>{expect(res.code).toBe(200)});});//通过调用参数test('shouldloadData',(deno)=>{loadData().then(res=>{expect(res.code).toBe(200)deno();});});//通过resolvetest('shouldloadData',(deno)=>{returnexpect(loadData()).resolves.toMatchObject({code:200});});hook//开始执行一次beforeAll(()=>{console.log('beforeEach');});//每个测试用例都会执行beforeEach(()=>{console.log('beforeEach');});//每个测试用例执行完后each(()=>{console.log('afterEach');});//钩子被执行afterAll(()=>{console.log('afterAll');});describe('describe',()=>{});test('应该xxx',()=>{});mockconstfunc=jest.fn(()=>{});func.mockReturnValueOnce('value1').mockReturnValueOnce('value2');func.mockReturnValue('value');console.log(func.mock);//mock返回数据mockajaximportajaxfrom'./utils/ajax/ajax'jest.mock('./utils/ajax/ajax');test('shouldmock',async()=>{ajax.get.mockResolvedValue({data:{data:[],code:200}});//模拟数据constdata=awaitloadTestData();expect(data.data).toEqual([]);});
