我试图模仿这个邮件功能,所以每次测试我的代码时都不发送邮件。但嘲笑不起作用。这段代码给了我错误:mockImplementation不是一个函数。
调用sendUserInvitationMail()的add函数。邮件程序模块导出如下所示:
module.exports = {
sendUserInvitationMail,
};
这是测试代码:
require('dotenv').config();
const { startWithCleanDb } = require('../../../utils/test.helpers');
const { add } = require('../invitation.service');
const { ADMIN_LEVELS, TABLES } = require('../../../constants');
const { AuthorizationError } = require('../../../errors');
const knex = require('../../../../db/connection');
const mailer = require('../../../mailer/index');
jest.mock('../../../mailer/index');
beforeEach(() => startWithCleanDb());
mailer.sendUserInvitationMail.mockImplementation(() => console.log('Mocked mail function called'));
mailer.sendUserInvitationMail();
describe('invitation.service', () => {
describe('add', () => {
it('adds an invitation to the db', async () => {
expect.assertions(2);
const result = await add(
{
email: 'tester@test.be',
badgeNumber: '344d33843',
},
{ currentZoneId: 1 },
ADMIN_LEVELS.ADMINISTRATOR,
);
const invitation = (await knex.select('*').from(TABLES.INVITATIONS))[0];
expect(invitation.id).toEqual(result.id);
expect(invitation.email).toEqual(result.email);
});
});
});
答案 0 :(得分:1)
在mailer
中,sendUserInvitationMail
为undefined
,因此没有属性mockImplementation
。
尝试:
mailer.sendUserInvitationMail = jest.fn().mockImplementation(() => console.log('Mocked mail function called'));
或
mailer.sendUserInvitationMail = jest.fn(() => console.log('Mocked mail function called'));