本文介绍了如何在mailgun-js的Node.js应用中使用Jest创建手动模拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

app/src/emails/account.js中的代码

code in app/src/emails/account.js

const mailgun = require("mailgun-js");
const DOMAIN = "sxxxxxxxxxxxxxxxxxxxxxxxxxxx.mailgun.org";
const mg = mailgun({apiKey: process.env.MAILGUN_API_KEY, domain: DOMAIN});

const sendWelcomeEmail = async (email, name) => {
    const dataForMail = {
        to: email,
        from: '[email protected]',
        subject: 'Testing!',
        text: `Welcome to the app, ${name}, let me know how you get along with the app.`,

    }

    mg.messages().send(dataForMail)

}

app/test/__ mocks __/mailgun-js中的代码:

code in app/test/__mocks__/mailgun-js:

module.exports = {
    messages() {

    },
    send() {

    },
    mailgun() {

    }

}

每当我开玩笑时,它说"mailgun不是函数".如何为该构造函数创建手动模拟?

Whenever I run jest, it says 'mailgun is not a function'. How can I create a manual mock for this constructor?

推荐答案

我的模拟对象是对象,而不是函数.测试双打需要匹配他们要替换的事物的接口;在这种情况下,它必须是一个函数,该函数使用messages方法返回对象(使用send方法返回对象).我的模拟完全不符合该结构. (非常感谢@jonrsharpe将此告知)mailgun-js.js需要以相同的方式进行编辑.

My mock is an object, not a function. Test doubles need to match the interface of the thing they're replacing; in this case, it needs to be a function that returns an object with a messages method (which returns an object with the send method). My mock doesn't match that structure at all. (Big thanks to @jonrsharpe for informing this)mailgun-js.js needs to be edited the same way.

module.exports = function(apiKey, domain) {
    const object2 = {
        send() {

        }
    }

    const object1 = {
        messages () {
            return object2
        }
    }
    return object1
}

这篇关于如何在mailgun-js的Node.js应用中使用Jest创建手动模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:37