方法一:回調函數
這是非常常見的通用處理方式,比如你有一個fetchData(callback)的
function用來獲取數據,並且在獲取完成的時候調用callback 函數,你想測試返回的數據是“peanut butter” ,默認情況下當fetchData執行完成的時候Jest的測試就完成了,這並不是你所期望的那樣的去運行。
代碼示例:fetechData.js文件代碼
import axios from 'axios' export const fetchData = (fn)=>{ axios.get("http://www.192.168.0.188:8080/demo.json").then(response)=>{ fn(response.data) //返回success:true }); }
對應的測試用例fetechData.test.js文件代碼
test('test fetchData返回結果為{successs:data}',(done)=>{
fetchData(data)=>{
expect(data).toEqual({
success:true
})
done();//回調函數,測試用例執行完成執行done
}
})
方法一:使用Promise方法
代碼示例:fetechData.js文件代碼
export const fetchData=()=>{
return axios.get('http://www.192.168.0.188:8080/demo.json');
}
對應的測試用例fetechData.test.js文件代碼
test('test fetchData返回結果為{successs:data}',()=>{
return fetchData().then((response)=>{
expect(response.data).toEqual({
success:true
})
}
})
也可以修改為
test('test fetchData返回結果為{successs:data}',()=>{ return expect(fetchData()).resolve.toMatchObject({ data:{ success:true } }) })
測試404錯誤,接口不存在時
test('test fetechData返回404',()=>{ expect.assertion(1)//1表示expect執行個數 return fetchData().catch(e=>{ console.log('e',e); expect(e.toString().indexOf('404')>-1).toBe(true) }) })
也可以修改為:
test('test fetechData返回404',()=>{ return expect(fetchData()).rejects.toThrow(); })
第三種:使用 Async/Await
我相信大家最Async/Await 是比較熟悉的,你可以在測試中使用異步和等待。要編寫一個async測試,只需在傳遞到測試的函數前面使用async關鍵字。例如上面同樣的fetchData場景可以使用下面的實現:
//測試接口正常
test('test fetchData返回結果為{successs:data}',async ()=>{ await expect(fetchData()).resolve.toMatchObject({ data{ success:true } }) })
測試異常用例
//測試404
test('test fetechData返回404',async ()=>{ await expect(fetchData()).rejects.toThrow(); })