为什么Jest mock的函数无返回值?如何mock new关键字创建的对象
问题修复方案
1. selector返回undefined修复
你在测试代码中重新对selector变量赋值为新的mock函数,而validator模块内部引用的是jest.mock生成的原有mock实例,新赋值的mock函数并不会生效,导致调用后返回undefined。
不需要重新赋值selector,直接在jest.mock生成的原有mock实例上设置返回值即可,同时你调用selector用了await,直接使用异步返回的mockResolvedValue即可,无需混写同步返回方法。
2. new创建的构造函数实例mock方法
Jest对构造函数的mock会自动收集所有生成的实例到构造函数.mock.instances数组中,你可以通过自定义构造函数的mock实现,直接返回带mock方法的实例即可满足需求。
修改后的完整测试代码
const {validator} = require('./index'); const FastestValidator = require("fastest-validator"); const { selector } = require("../selector"); jest.mock('../selector'); jest.mock('fastest-validator'); test('testing schema validator', async () => { // 模拟selector返回的schema,注意要返回对象,因为后续代码会遍历schema的key const mockSchema = { message: { type: 'string' } }; selector.mockResolvedValue(mockSchema); // 模拟FastestValidator实例的compile方法,以及compile返回的校验函数 const mockCheckFn = jest.fn().mockResolvedValue({ message: '字段校验错误' }); FastestValidator.mockImplementation(() => { return { compile: jest.fn(() => mockCheckFn) }; }); const testData = { message: 'you ' }; // 校验失败的预期返回,用toMatchObject匹配部分属性即可,避免额外属性导致断言失败 const failedResult = { success: false }; await expect(validator(testData)).resolves.toMatchObject(failedResult); // 可选:添加调用断言验证逻辑符合预期 expect(selector).toHaveBeenCalledWith(testData); expect(FastestValidator).toHaveBeenCalledTimes(1); expect(FastestValidator.mock.instances[0].compile).toHaveBeenCalledWith(mockSchema); expect(mockCheckFn).toHaveBeenCalled(); });
额外注意事项
你业务代码里的判断逻辑存在语法错误:else if (validatingInboundData && typeof boolean),这里typeof boolean返回的是undefined,会导致这个分支永远无法触发,需要修改为else if (typeof validatingInboundData === 'boolean')。
内容的提问来源于stack exchange,提问作者amarnath harish
相关产品推荐
相关产品推荐

