在node.js中使用Jest和Mock测试Sendgrid实现 [英] Test Sendgrid implementation with Jest and Mock in node.js

查看:74
本文介绍了在node.js中使用Jest和Mock测试Sendgrid实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在nodejs应用程序中使用sendGrid电子邮件,我想开玩笑地对其进行测试.

I use sendGrid email in my nodejs app and I would like to test it with jest.

这是我的应用代码:

mail.js

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const simplemail = () => {
  const msg = {
    to: 'receiver@mail.com',
    from: 'sender@test.com',
    subject: 'TEST Sendgrid with SendGrid is Fun',
    text: 'and easy to do anywhere, even with Node.js',
    html: '<strong>and easy to do anywhere, even with Node.js</strong>',
    mail_settings: {
      sandbox_mode: {
        enable: true,
      },
    },
  };
  (async () => {
    try {
      console.log(await sgMail.send(msg));
    } catch (err) {
      console.error(err.toString());
    }
  })();
};

export default simplemail;

这是我为了测试而做的事情:

Here is what I've done to test it with jest:

mail.test.js

mail.test.js

import simplemail from './mail';
const sgMail = require('@sendgrid/mail');
jest.mock('@sendgrid/mail', () => {
  return {
    setApiKey: jest.fn(),
    send: jest.fn(),
  };
});
describe('#sendingmailMockedway', () => {
  beforeEach(() => {
    jest.resetAllMocks();
  });
  it('Should send mail with specefic value', async () => {
    // sgMail.send.mockResolvedValueOnce([{}, {}]);
    await expect(sgMail.send).toBeCalledWith({
      to: 'receiver@mail.com',
      from: 'sender@test.com',
      subject: 'TEST Sendgrid with SendGrid is Fun',
      text: 'and easy to do anywhere, even with Node.js',
    });
  });
});

我需要在此文件上修复代码覆盖率,以便进行尽可能多的测试,测试邮件是否已发送,是否有错误或是否存在错误,这就是为什么我在mail.js中添加了

I need to fix my code coverage on this file so to put as much test as possible and test if the mail is sent and catch if there is error or now, that's why I've added in mail.js

mail_settings: {
  sandbox_mode: {
    enable: true,
  },
},

我想用玩笑来测试它并模拟sendgrid,但是如何?

I would like to test it with jest and mock sendgrid it but how?

推荐答案

由于在simplemail函数中使用了IIFE和async/await,因此在我们在单元测试中断言IIFE之前,请使用setImmediate函数确保IIFE已执行情况.

Because you use IIFE and async/await in simplemail function, Use setImmediate function to make sure the IIFE is executed before we assert it in unit test case.

这是单元测试解决方案:

Here is the unit test solution:

index.js:

const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const simplemail = () => {
  const msg = {
    to: "receiver@mail.com",
    from: "sender@test.com",
    subject: "TEST Sendgrid with SendGrid is Fun",
    text: "and easy to do anywhere, even with Node.js",
    html: "<strong>and easy to do anywhere, even with Node.js</strong>",
    mail_settings: {
      sandbox_mode: {
        enable: true
      }
    }
  };
  (async () => {
    try {
      console.log(await sgMail.send(msg));
    } catch (err) {
      console.error(err.toString());
    }
  })();
};

export default simplemail;

index.spec.js:

import simplemail from "./";
const sgMail = require("@sendgrid/mail");

jest.mock("@sendgrid/mail", () => {
  return {
    setApiKey: jest.fn(),
    send: jest.fn()
  };
});

describe("#sendingmailMockedway", () => {
  afterEach(() => {
    jest.resetAllMocks();
    jest.restoreAllMocks();
  });
  it("Should send mail with specefic value", done => {
    const logSpy = jest.spyOn(console, "log");
    const mResponse = "send mail success";
    sgMail.send.mockResolvedValueOnce(mResponse);
    simplemail();
    setImmediate(() => {
      expect(sgMail.send).toBeCalledWith({
        to: "receiver@mail.com",
        from: "sender@test.com",
        subject: "TEST Sendgrid with SendGrid is Fun",
        text: "and easy to do anywhere, even with Node.js",
        html: "<strong>and easy to do anywhere, even with Node.js</strong>",
        mail_settings: {
          sandbox_mode: {
            enable: true
          }
        }
      });
      expect(logSpy).toBeCalledWith(mResponse);
      done();
    });
  });

  it("should print error when send email failed", done => {
    const errorLogSpy = jest.spyOn(console, "error");
    const mError = new Error("network error");
    sgMail.send.mockRejectedValueOnce(mError);
    simplemail();
    setImmediate(() => {
      expect(sgMail.send).toBeCalledWith({
        to: "receiver@mail.com",
        from: "sender@test.com",
        subject: "TEST Sendgrid with SendGrid is Fun",
        text: "and easy to do anywhere, even with Node.js",
        html: "<strong>and easy to do anywhere, even with Node.js</strong>",
        mail_settings: {
          sandbox_mode: {
            enable: true
          }
        }
      });
      expect(errorLogSpy).toBeCalledWith(mError.toString());
      done();
    });
  });
});

单元测试结果覆盖率100%:

Unit test result with 100% coverage:

 PASS  src/stackoverflow/59108624/index.spec.js (6.954s)
  #sendingmailMockedway
    ✓ Should send mail with specefic value (9ms)
    ✓ should print error when send email failed (17ms)

  console.log node_modules/jest-mock/build/index.js:860
    send mail success

  console.error node_modules/jest-mock/build/index.js:860
    Error: network error

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        8.336s

源代码: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59108624

这篇关于在node.js中使用Jest和Mock测试Sendgrid实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆