【问题标题】:Jest Mock Function?开玩笑模拟功能?
【发布时间】:2017-03-29 05:12:23
【问题描述】:

刚开始使用 jest,文档似乎对 mock 不太清楚。

我有一个带有以下代码的模块。如果我想测试发送邮件功能,但不通过 mailgun 发送实际电子邮件,我需要在这里做什么?我认为在我的测试文件中我需要使用模拟行为,但无法弄清楚如何专门阻止邮件发出,同时还能够检查是否遵循了正确的路线,例如无效的电子邮件地址、抛出的错误等。我需要进一步分解此功能吗?

const Mailgun = require('machinepack-mailgun');
const Emailaddresses = require('machinepack-emailaddresses');
const config = require('../Config');


// Function to send an email
const sendEmail = function (toaddress, toname, sub, msg, cb) {
// Validate the email address is correct and if so send an email. Otherwise log the error and exit.
  Emailaddresses.validate({
    string: toaddress,
  }).exec({
    error(err) {
      return cb(err, null);
    },
    invalid() {
      return cb(new Error('Email address is not valid.'), null);
    },
    success() {
      Mailgun.sendPlaintextEmail({
        apiKey: config.sender.apiKey,
        domain: config.sender.domain,
        toEmail: toaddress,
        toName: toname,
        subject: sub,
        message: msg,
        fromEmail: config.sender.fromEmail,
        fromName: config.sender.fromName,
      }).exec({
        error(err) {
          return cb(err, null);
        },
        success() {
          return cb(null, 'Email Sent.');
        },
      });
    },
  });
};

module.exports.sendEmail = sendEmail;

【问题讨论】:

    标签: unit-testing email jestjs


    【解决方案1】:

    您可以使用自己的实现来模拟 Mailgun

    const Mailgun = require('machinepack-mailgun');
    jest.mock('machinepack-mailgun', () = > ({
      sendPlaintextEmail: jest.fn()
    }))
    it('sends mail and fail', () = > {
      // no add the way `sendPlaintextEmail` should react.
      // in this case return `exec` which always run the `error` part
      Mailgun.sendPlaintextEmail.mockImplementation(() = > ({
        exec: (arg) = > {
          arg.error('someError')
        }
      }))
      const cb = jest.fn()
      sendEmail ('toaddress', 'toname', 'sub', 'msg', cb) 
      expect(Mailgun.sendPlaintextEmail).toHaveBeenCalledWith(...)
      expect(cb).toHaveBeenCalledWith(...)
    })
    

    在上面的示例中,我们模拟了 mailgun 模块,因此 sendPlaintextEmail 是一个间谍。然后我们将模块导入到我们的测试中,这样我们就可以在每个测试中设置间谍的模拟实现。在示例中,我们设置了行为,使其返回 exec 方法,然后您的代码使用 error/success 对象调用该方法。然后模拟只需调用error 部分。之后你可以先测试Mailgun.sendPlaintextEmail被正确的参数调用,然后你可以测试cb"someError"null调用。

    在另一个测试中,您可以设置exec 的行为,这样它就会调用success 方法。

    【讨论】:

    • 谢谢,今晚我会回顾一下,如果没有其他问题,请标记。感谢帮助
    • 似乎遇到错误错误:expect(jest.fn()).toHaveBeenCalledWith(expected) 预期的模拟函数已被调用:["chris@gmail.com", "chris", "subject", "message"] 但它没有被调用。 pastebin.com/rhxtjkLc
    • 您能否通过添加console.log(Mailgun.sendPlaintextEmail) 来检查是否调用了电子邮件验证的成功函数。它打印什么?
    • 另外hasBeenCalledWith 应该是这样的:{ apiKey: config.sender.apiKey, domain: config.sender.domain, toEmail: toaddress, toName: toname, subject: sub, message: msg, fromEmail: config.sender.fromEmail, fromName: config.sender.fromName, } 而不是数组。
    • 看来我已经完成了这项工作。我希望我能告诉你为什么! pastebin.com/Mn6yvMiR 在mailgun 中模拟出无效和错误路由的最佳方法是什么?我是否只是在我的 mockImplementation 中添加其他方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2021-01-01
    • 2017-08-04
    • 2019-05-08
    • 2017-07-14
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多