繁体   English   中英

尝试在Jest规范中模拟异步提取功能时出错

[英]Errors when trying to mock an async fetch function in Jest spec

我正在为我的应用程序编写测试,但是在尝试模拟异步提取功能时遇到问题。 无论我尝试什么,我都会得到:

asyncFetch.mockReturnValue is not a function

这使我相信该函数没有被嘲笑。 但是,我不知道问题出在哪里。

这是测试:

 import emailSignin from 'api/emailSignin'; jest.mock('api/helpers/asyncFetch'); describe('API Auth', () => { describe('login', () => { it('has a happy path', async () => { const asyncFetch = require('api/helpers/asyncFetch').default; asyncFetch.mockReturnValue({ json: () => 'it worked', }); const response = await emailSignin('bob', 'password'); expect(response).toEqual('it worked'); }); }); }); 

这是我要模拟的模块:

 import { ClientError, ServerError, ValidationError, } from 'api/helpers/errors'; async function asyncFetch(url, requestConfig = {}) { const response = await fetch(url, requestConfig); const responseBody = await response.json(); const { statusText, status } = response; switch (status) { case 400: case 401: case 403: throw new ClientError(statusText, status); case 422: throw new ValidationError(statusText, status, responseBody.errors); case 500: case 501: case 502: case 503: case 504: case 505: throw new ServerError(statusText, status); default: return response; } } export default asyncFetch; 

任何帮助将不胜感激!

要开玩笑地模拟模块,您可以在初始的mock调用中像这样进行操作:

jest.mock('api/helpers/asyncFetch', ()=>({
  json: () => 'it worked'
}))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM