How to mock a method with node tap?

Viewed 451

I am trying to mock a method in my test suite that sends an email through a third party API. When I run my test suite I don't want the email to be sent.

Here is what I got so far trying to implement mocks with node tap https://node-tap.org/docs/api/mocks/, but it is not working since It sends an email every time I run the test.

Here is my directory:

    app.js
    src >
         mail >
           service.js
           router.js
           test.spec.js
         services >
           mail >
             index.js

Test file:

const tap = require('tap');
const app = require('../../app');

tap.test('GET /', t => {
  t.teardown(() => app.close());

  t.test("Calling with valid email parameter", ({equal, end, same}) => {
    t.mock("./service", {
      "../services/mail": {
        sendTransactionalEmailWithTemplate:() => {
          return Promise.resolve();
        }
      }
    });
    app.inject({
      method: 'GET',
      url: `/?email=valid@email.com}`
    }, (err, response) => {
      equal(response.statusCode, 200);
      same(response.json(), { message: "Email sent" })
      end();
    });
  });

  t.end();

});

Router file:

const { sendMail } = require("./service");
  
module.exports = function (fastify, opts, done) {
  fastify.get('/', { schema }, handler);
  done();
}

async function handler(request, reply) {
  // handle some verifivations...
  await sendMail (request, reply);
}

Service file:

const { sendTransactionalEmailWithTemplate } = require("../services/mail");

async function sendResetPasswordMail(request, reply) {
      try {
        await sendTransactionalEmailWithTemplate(request.query.email, "email object", "email template");
        reply.send({
          message: "Email sent"
        });
      } catch(error) {
        request.log.error(error);
        reply.status(500).send({
          message: "Email not sent"
        });
      }
}

module.exports = {
  sendMail:sendMail,
}

And the file at ../services/mail uses a third party API to send an email.

So far the mock method is not working because the test sends the email.

0 Answers
Related