Supposed I have a code
const SomeEmailModule = require('SomeEmailModule')
const emailModule = new SomeEmailModule()
async function sendEmail(htmlBody) {
await emailModule.send(htmlBody)
return htmlBody
}
and when I used it on test using jest
const SomeEmailModule = require('SomeEmailModule')
it('can test', async () => {
const emailModule = new SomeEmailModule()
jest.spyOn(emailModule, 'send').mockImplementation()
......some code
)
the module doesn't actually mock the method send it stills do the original functionality of the method any idea why it happened?
Okay after some testing
const mockSend = jest.fn()
SomeEmailModule.prototype.send = mockSend
this solution works however I want to know how this one works while the other one doesn't
this one also works
const mockSend = jest.spyOne(SomeEmailModule.prototype, 'send').mockImplementation()
Because the emailModule instance of the SomeEmailModule class in your test case is different from the one in the file under test.
jest.spyOn(emailModule, 'send').mockImplementation();
You just install a spy on the emailModule instance created in the test case, but the emailModule instance in the file under test is not spied.
But installing spy on SomeEmailModule.prototype.send() will work, because all instances share the same prototype.