如何正确覆盖__mocks__文件夹中定义的Jest模拟函数?
解决Jest中__mocks__默认模拟无法覆盖的问题
你遇到的错误核心原因是:mocks/fetchStuff.ts里的registerAccount只是普通的模拟函数,不是Jest官方的mock函数类型,自然没有mockResolvedValue这类专属方法。下面给你两种解决思路:
思路一:修改__mocks__实现,让它支持覆盖
把__mocks__里的registerAccount定义成Jest的mock函数,这样后续就能直接在测试用例里覆盖它的返回值:
// __mocks__/fetchStuff.ts export const registerAccount = jest.fn().mockResolvedValue({ defaultMockData: '默认返回值' });
之后在测试用例里就可以正常覆盖了:
import { registerAccount } from '../fetchStuff'; jest.mock('../fetchStuff'); test('覆盖默认模拟返回值', async () => { registerAccount.mockResolvedValue({ customData: '自定义返回值' }); const result = await registerAccount(); expect(result).toEqual({ customData: '自定义返回值' }); });
思路二:临时禁用__mocks__的自动读取
如果不想改动默认的__mocks__实现,也可以在单个测试文件里临时禁用该模块的自动mock,改用自定义实现:
方法1:用jest.unmock禁用自动mock
import { registerAccount } from '../fetchStuff'; // 禁用该模块的自动mock,不再读取__mocks__里的内容 jest.unmock('../fetchStuff'); // 手动重新定义mock jest.mock('../fetchStuff', () => ({ registerAccount: jest.fn().mockResolvedValue({ customData: '自定义返回值' }) })); test('临时禁用默认mock', async () => { const result = await registerAccount(); expect(result).toEqual({ customData: '自定义返回值' }); });
方法2:直接用jest.mock的factory函数覆盖
在jest.mock里传入自定义的工厂函数,会直接忽略__mocks__文件夹里的默认实现:
// 直接传入factory函数,覆盖__mocks__里的内容 jest.mock('../fetchStuff', () => ({ registerAccount: jest.fn().mockResolvedValue({ customData: '自定义返回值' }) })); import { registerAccount } from '../fetchStuff'; test('用factory函数覆盖默认mock', async () => { const result = await registerAccount(); expect(result).toEqual({ customData: '自定义返回值' }); });
内容的提问来源于stack exchange,提问作者Jordan
相关产品推荐
相关产品推荐

