如何使用Jest模拟mailgun.messages()。send()?

时间:2019-12-24 04:36:17

标签: javascript node.js typescript jestjs

我正在使用mailgun-js Api发送邮件。我写了一个集成测试而不是单元测试。现在,我需要为包装在sendEmail类中的Mailgun方法编写单元测试用例。我不知道如何模拟mailgun.messages().send()。有人可以帮我吗?

mailgun.ts

/**
 * @file Mailgun Email Operations.
 */

import mg from 'mailgun-js';
import config from 'config';

// Get database name from configuration file
const mailgunConfig: mg.ConstructorParams = config.get('Mailgun.config');

// Setup Mailgun Service
const mailgun = mg(mailgunConfig);

// Mailgun Service class
export class Mailgun {
    /**
     * Static function to send an email.
     * @param {mg.messages.SendData} emailParams - parameters to sent an email.
     * @returns {Promise<mg.messages.SendResponse>} - maligun response with message and id.  
     */
    static sendEmail = (emailParams: mg.messages.SendData): Promise<mg.messages.SendResponse> => {
        return mailgun.messages().send(emailParams);
    };
}

mailgun.test.ts

/**
 * @file Mailgun Test Case.
 */

// Import External Modules
import dotenv from 'dotenv';
// Load Configuration
dotenv.config({path: '.env'});
// Import Internal Modules
import { Mailgun } from '../../../../api/core/services/email/mailgun';

// sendEmail Test Suite
describe('Send Email', () => {
    it('returns the promise of queued object with id and message keys when valid email is passed',async () => {
    // Preparing
        const emailParam = {
            from: 'noreply@shop.techardors.com',
            to: 'ecomm@api.com',
            subject: 'TechArdors Shopping: One-time passcode to reset the password',
            html: '<p>Please enter the passcode <strong>5124</strong> to reset the password. It expires in 5 minutes from the time it is requested.</p>'
        };
        // Executing
        const result = await Mailgun.sendEmail(emailParam);
        // Verifying
        expect(result.message).toBe('Queued. Thank you.');
        expect(result).toHaveProperty('id');
        expect(result).toHaveProperty('message');
    });
});

1 个答案:

答案 0 :(得分:1)

您需要使用jest.mock()模拟mailgun-js模块。

例如

mailgun.ts

import mg from 'mailgun-js';

// Get database name from configuration file
const mailgunConfig: mg.ConstructorParams = {
  apiKey: '123',
  domain: 'example.com',
};

// Setup Mailgun Service
const mailgun = mg(mailgunConfig);

// Mailgun Service class
export class Mailgun {
  /**
   * Static function to send an email.
   * @param {mg.messages.SendData} emailParams - parameters to sent an email.
   * @returns {Promise<mg.messages.SendResponse>} - maligun response with message and id.
   */
  static sendEmail = (emailParams: mg.messages.SendData): Promise<mg.messages.SendResponse> => {
    return mailgun.messages().send(emailParams);
  };
}

mailgun.test.ts

import { Mailgun } from './mailgun';
import mg from 'mailgun-js';

jest.mock('mailgun-js', () => {
  const mMailgun = {
    messages: jest.fn().mockReturnThis(),
    send: jest.fn(),
  };
  return jest.fn(() => mMailgun);
});

// sendEmail Test Suite
describe('Send Email', () => {
  it('returns the promise of queued object with id and message keys when valid email is passed', async () => {
    // Preparing
    const emailParam = {
      from: 'noreply@shop.techardors.com',
      to: 'ecomm@api.com',
      subject: 'TechArdors Shopping: One-time passcode to reset the password',
      html:
        '<p>Please enter the passcode <strong>5124</strong> to reset the password. It expires in 5 minutes from the time it is requested.</p>',
    };
    const mailgun = mg({} as any);
    (mailgun.messages().send as jest.MockedFunction<any>).mockResolvedValueOnce({
      id: '222',
      message: 'Queued. Thank you.',
    });
    // Executing
    const result = await Mailgun.sendEmail(emailParam);
    // Verifying
    expect(result.message).toBe('Queued. Thank you.');
    expect(result).toHaveProperty('id');
    expect(result).toHaveProperty('message');
    expect(mailgun.messages).toBeCalled();
    expect(mailgun.messages().send).toBeCalledWith(emailParam);
  });
});

带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/59463875/mailgun.test.ts (7.587s)
  Send Email
    ✓ returns the promise of queued object with id and message keys when valid email is passed (7ms)

------------|----------|----------|----------|----------|-------------------|
File        |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
------------|----------|----------|----------|----------|-------------------|
All files   |      100 |      100 |      100 |      100 |                   |
 mailgun.ts |      100 |      100 |      100 |      100 |                   |
------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.723s

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