英文:
mockResolvedValue is not a function on partial mock with Jest/Typescript
问题
我正在尝试部分模拟一个模块,并根据某些测试需要设置模拟方法的返回值。
Jest抛出这个错误:
mockedEDSM.getSystemValue.mockResolvedValue 不是一个函数
TypeError: mockedEDSM.getSystemValue.mockResolvedValue 不是一个函数
我的模拟:
jest.mock('../src/models/EDSM', () => ({
__esModule: true,
...jest.requireActual<typeof import('../src/models/EDSM')>('../src/models/EDSM'),
getSystemValue: jest.fn(),
}));
const mockedEDSM = jest.mocked(EDSM);
在测试中:
it('应该测试', () => {
mockedEDSM.getSystemValue.mockResolvedValue(edsmData);
});
在运行测试时,Typescript在IDE中没有警告,我只在Jest中得到错误。
英文:
I am trying to partially mock a module, and set the return value for the mocked method as needed in certain tests.
Jest is throwing this error:
mockedEDSM.getSystemValue.mockResolvedValue is not a function
TypeError: mockedEDSM.getSystemValue.mockResolvedValue is not a function
My mock:
jest.mock('../src/models/EDSM', () => ({
__esModule: true,
...jest.requireActual<typeof import('../src/models/EDSM')>('../src/models/EDSM'),
getSystemValue: jest.fn(),
}));
const mockedEDSM = jest.mocked(EDSM);
Within tests:
it('should test', () => {
mockedEDSM.getSystemValue.mockResolvedValue(edsmData);
});
Typescript is throwing no warnings in the IDE, I'm only getting errors from Jest when running the tests.
答案1
得分: 0
当然,发帖后立即找到了答案!在测试文件的顶部不需要调用jest.mock
,唯一需要的是在每个测试中(或在before/after
钩子中)对该方法进行spyOn
:
const getSystemValueMock =
jest.spyOn(EDSM, 'getSystemValue')
.mockResolvedValue(edsmData);
英文:
Ah of course, found the answer right after posting this!
No need to call jest.mock
at the top of the test file, the only thing needed is to spyOn the method within each test (or in a before/after hook):
const getSystemValueMock =
jest.spyOn(EDSM, 'getSystemValue')
.mockResolvedValue(edsmData);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论