mockImplementation() 仍然调用方法的原始功能

mockImplementation() still calling the original functionality of the method

假设我有一个代码

const SomeEmailModule = require('SomeEmailModule')
const emailModule = new SomeEmailModule()


async function sendEmail(htmlBody) {
    await emailModule.send(htmlBody)
    return htmlBody
}

当我使用 jest

进行测试时
const SomeEmailModule = require('SomeEmailModule')

it('can test', async () => {

    const emailModule = new SomeEmailModule()
    jest.spyOn(emailModule, 'send').mockImplementation()
    ......some code
) 

该模块实际上并没有模拟该方法send它仍然执行该方法的原始功能知道它为什么会发生吗?


经过一些测试后没问题

const mockSend = jest.fn()
SomeEmailModule.prototype.send = mockSend

这个解决方案有效,但是我想知道这个解决方案是如何工作的,而另一个则没有


这个也可以

const mockSend = jest.spyOne(SomeEmailModule.prototype, 'send').mockImplementation()

因为您的测试用例中 SomeEmailModule class 的 emailModule 实例与被测文件中的实例不同。

jest.spyOn(emailModule, 'send').mockImplementation();

你只是在测试用例中创建的 emailModule 实例上安装了一个间谍,但是被测文件中的 emailModule 实例没有被侦测到。

但是在 SomeEmailModule.prototype.send() 上安装 spy 会起作用,因为所有实例共享相同的原型。