(一)准备接口
事先准备好一个接口,返回值长这样(上)
(二)回调函数式
正常应该这么写
index.js
import axios from 'axios'
export function getData (fn) {
axios.get('http://www.mockhttp.cn/mock/test/zfb').then((res) => {
fn(res)
})
}
index.test.js
import { getData } from '../code/index'
test('获取index', () => {
getData((res) => {
expect(res).toEqual(0)
})
})
expect 写里面------
这个结果永远是通过的,因为异步的话不会等接口返回就执行了,所以都通过
正确写法
等着请求回来再判断
(三)返回一个Promise
index.js
export function getData () {
return new Promise((reject, resolve) => {
setTimeout(() => {
resolve({ success: true })
}, 2000)
})
}
index.test.js
import { getData } from '../code/index'
test('获取异步', () => {
getData().then((res) => {
expect(res).toEqual({
"success": false
})
})
})
但仍然通过了
正确写法 要加return
(四)接口不存在的测试
import { getData } from '../code/index'
test('获取异步', () => {
expect.assertions(1) // 必须执行一次expect 才能通过
return getData().catch((res) => {
console.log(res.toString().indexOf('404') > -1)
})
})