我有一個非常簡單的模擬作業示例,可以正確更新值,但我的測驗仍然失敗。
fetchStuff.js:
const fetchStuff = async (entity, service) => {
entity = await service.get();
console.log('entity is an expected result!', entity); // this consoles out the expected value correctly.
}
fetchStuff.spec.js:
it('should...', () => {
const expected = 'this will show up in console';
const service.get = jest.fn().mockImplementation(() => expected);
let entity;
fetchStuff(entity, service);
expect(entity).toEqual(expected) // entity = 'undefined'
});
每次,我都看到console.log函式中列印出預期的結果,但出于某種原因,expect(entity)總是undefined.
我嘗試過 with 之類的東西flush-promise,我嘗試過洗掉await. 我什至看過done()我們傳入done的技術it,即it('should...', done => {...})
不知道為什么我不能得到正確的預期,即使控制臺顯示了預期的結果。
PS。我知道這不尊重功能范式或純功能。請忽略這一點。
uj5u.com熱心網友回復:
您正在使用異步函式,但在解決承諾之前立即進行測驗。如果您使用異步呼叫,您需要在測驗中使用 async/await,例如 main 函式中的 await。
it('should...', async () => {
const expected = 'this will show up in console';
const service.get = jest.fn().mockImplementation(() => expected);
let entity;
await fetchStuff(entity, service);
expect(entity).toEqual(expected) // entity = 'undefined'
});
但是,根據對您問題的評論,代碼可能不會回傳您期望的內容,因此對 async/await 的這種更改不會自行解決問題。
const fetchStuff = async (entity, service) => {
entity = await service.get();
console.log('entity is an expected result!', entity);
return entity;
}
it('should...', async () => {
const expected = 'this will show up in console';
const FakeService = jest.fn().mockResolvedValue(expected),
const entity = await FakeService();
expect(entity).toBe(expected) ;
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/422897.html
標籤:
