1

I have app.js on express and mailgun, i need to test the success of sending mailgun with jest.

////////////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;

I do post from frontend to beckend and then mailgun sending.

MB i shoult to mock mailgun sending or response to mailgun api.

Dobby Dimov
  • 944
  • 8
  • 10

1 Answers1

0

What you are trying to achieve here is actually integration testing.

From unit testing perspective, mock mailgun.messages().send() function to make sure it receives the right parameters. And your code can handle different responses, e.g. success and error

See answers here on how to organize integration testing: How are integration tests written for interacting with external API?

Eriks Klotins
  • 4,042
  • 1
  • 12
  • 26