【问题标题】:How to mock functions deeper in the code with jest如何用玩笑在代码中更深地模拟函数
【发布时间】:2018-01-24 20:43:21
【问题描述】:

我试图模拟这个邮件功能,所以我每次测试我的代码时都不会发送邮件。但是嘲弄是行不通的。这段代码给了我错误:mockImplementation is not a function。

是调用 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);
    });

  });
});

【问题讨论】:

    标签: unit-testing jestjs


    【解决方案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'));
    

    【讨论】:

    • 适用于我在测试文件中进行的一次调用。但是未模拟的 sendUserInvitationMail 仍然被 add 函数调用。
    • 在这种情况下,您的模拟邮件可能看起来像 module.exports = { sendUserInvitationMail: () => {} }
    • 就是这样,不过使用简写,请参阅 OP。
    • @RobIndesteege 如果您将实现提供给jest.mock,它是否有效? – jest.mock(..., () => ({ sendUserInvitationMail: jest.fn(...) }))
    猜你喜欢
    • 1970-01-01
    • 2021-02-07
    • 2019-11-17
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多