jest测试异步请求

function fetchData(fn){
    axios.get('/data').then(data=>{fn(data)})    
}

test('异步请求',(done)=>{
    fetchData(data=>{
    expect(data).toEqual({success:'xx'})
    done()
    })    
})

//如果返回是promise对象,可以用catch或者then
function fn(){
    return axios.get('/data')    
}
test('异步请求成功',()=>{
    fn().then(data=>{exect(data).toEqual({success:'xx'})})    
})
test('异步请求失败',()=>{
    fn().catch(e=>{expect(e.toString().indexOf('404')>-1).toBe(true)
})   
})

//还可以这样
test('测试异步请求',()=>{
    //请求数据
    return expect(fn()).resolves.toMatchObject({data:{success:true}})
    //抛出异常
    return expect(fn).rejects.toThrow()
})

//只测试一个
test.only('测试',()=>{})

判断函数调用情况

function run(callback){
    callback()    
}

test('测试',()=>{
    let fn=jest.fn()
    run(fn)    
    expect(fn).toBeCalled()//判断函数是否被调用
    expect(fn.mock.calls.length).toBe(2)//判断函数是否被调用两次
})
function fn(){
	return axios.get('/data')
	}

//实际没有请求后台数据
import axios from 'axios'
jest.mock('axios')
test.only('测试',async()=>{
	axios.get.mockResolvedValue({data:'hello'})
	await fn().then((data)=>{expect(data).toBe('hello')})
	})

生成快照

test('xx',()=>{
	expect(fn()).toMatchSnapshot({success:'xx'})
	})
//它会先生成一个快照,如果第二次测和第一次的数据不一样就会报错,按u是更新快照,如果返回的是时间
//可以这样
test('xx',()=>{
	expect(fn()).toMatchSnapshot({time:expect.any(Date)})
	})

测试类方法

//util.js
class Util{
    add(){}
 
}
export default Util

//demo.js
import Util from './util'
function Demo(a,b){
    const util=new Util()
    util.add(a)
}
export default Demo

//util.test.js

jest.mock('./util')
import Util from './util'
import Demo from './demo'
test('测试',()=>{
    Demo()
    expect(Util).toHaveBeenCalled()
   expect(Util.mock.instances[0].add).toHaveBeenCalled()
})

测试异步方法

export default fn(callback){
	setTimeout(()=>{callback()},2000)
	}
test('测试',(done)=>{
	fn(()=>{expect(1).toBe(1);
		done()
		})
	})


//避免异步函数等待时间
jest.useFakeTimers()
test('xx',()=>{
	const timer=jest.fn();
	jest.advanceTimersByTime(3000)//快进时间
	fn(timer)
	jest.runAllTimers()//让它同步执行
	expect(timer).toHaveBeenCalledTimes(1)
	})