我不明白我如何测试用jest发送mailgun的成功

时间:2018-05-25 09:40:33

标签: javascript testing jest mailgun

我在express和mailgun上有app.js,我需要测试用jest发送mailgun的成功。

////////////app.js///////
var express = require('express');
var bodyParser = require('body-parser')

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Adding headers to support CORS
app.use('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Accept, Origin, Content-Type, access_token');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

console.log("Preparing server!")

// Handling request
app.post('/get-client-data', function (req, res) {

    //  console.log("Got a request: ", req.body);

    var postQuery = req.body.query;
    var name = postQuery.name;
    var email = postQuery.email;
    var message = postQuery.message;

    var mailgun = require("mailgun-js");
    var api_key = 'some key';
    var DOMAIN = 'some Domain';
    var mailgun = require('mailgun-js')({ apiKey: api_key, domain: DOMAIN });

    var data = {
        from: 'Mailgun <postmaster@' + DOMAIN + '>',
        to: 'Sales team <some@sales.io>',
        subject: 'Name of client: ' + name + ', email: ' + email,
        text: message,
    };

    mailgun.messages().send(data, function (error, body) {
        console.log(body);
    });
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ 'response': 'email has been sent' }));
});

app.listen(3000, function () {
    console.log('backend is listening on port 3000!');
});

module.exports = app;

我从前端发布到beckend然后发送邮件。

MB我应该模仿mailgun发送或回复mailgun api。

1 个答案:

答案 0 :(得分:0)

您在这里尝试实现的是集成测试。

从单元测试的角度来看,模拟mailgun.messages().send()函数以确保它接收正确的参数。您的代码可以处理不同的响应,例如成功与错误

请在此处查看有关如何组织集成测试的答案:How are integration tests written for interacting with external API?