如何用jest在代码中更深入地模拟函数

时间:2018-01-24 20:43:21

标签: unit-testing jestjs

我试图模仿这个邮件功能,所以每次测试我的代码时都不发送邮件。但嘲笑不起作用。这段代码给了我错误: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);
    });

  });
});

1 个答案:

答案 0 :(得分:1)

mailer中,sendUserInvitationMailundefined,因此没有属性mockImplementation

尝试:

mailer.sendUserInvitationMail = jest.fn().mockImplementation(() => console.log('Mocked mail function called'));

mailer.sendUserInvitationMail = jest.fn(() => console.log('Mocked mail function called'));