7

有谁知道如何在 nodejs 中测试邮件通知模块?我想测试里面的逻辑n.on()

const notifier = require('mail-notifier');

const imap = {
  user: 'mailId',
  password: 'password',
  host: 'host',
  port: 'port',
  tls: true,
  tlsOptions: { rejectUnauthorized: false }
};

const n = notifier(imap);

n.on('mail', async function (mail) {
  console.log('mail:', mail);
}).start();
4

2 回答 2

2

假设您的代码存在于notifier.js其中,可以完全按如下方式进行测试:

// mock 'mail-notifier'
jest.mock('mail-notifier', () => {
  // create mock for 'start'
  const startMock = jest.fn();
  // create mock for 'on', always returning the same result
  const onResult = { start: startMock };
  const onMock = jest.fn(() => onResult);
  // create mock for 'notifier', always returning the same result
  const notifierResult = { on: onMock };
  const notifierMock = jest.fn(() => notifierResult);
  // return the mock for notifier
  return notifierMock;
});

// get the mocks we set up from the mocked 'mail-notifier'
const notifierMock = require('mail-notifier');
const onMock = notifierMock().on;
const startMock = onMock().start;
// clear the mocks for notifier and on since we called
// them to get access to the inner mocks
notifierMock.mockClear();
onMock.mockClear();

// with all the mocks set up, require the file
require('./notifier');

describe('notifier', () => {

  it('should call notifier with the config', () => {
    expect(notifierMock).toHaveBeenCalledTimes(1);
    expect(notifierMock).toHaveBeenCalledWith({
      user: 'mailId',
      password: 'password',
      host: 'host',
      port: 'port',
      tls: true,
      tlsOptions: { rejectUnauthorized: false }
    });
  });

  it('should call on with mail and a callback', () => {
    expect(onMock).toHaveBeenCalledTimes(1);
    expect(onMock.mock.calls[0][0]).toBe('mail');
    expect(onMock.mock.calls[0][1]).toBeInstanceOf(Function);
  });

  it('should call start', () => {
    expect(startMock).toHaveBeenCalledTimes(1);
    expect(startMock).toHaveBeenCalledWith();
  });

  describe('callback', () => {

    const callback = onMock.mock.calls[0][1];

    it('should do something', () => {
      // test the callback here
    });

  });

});
于 2018-08-09T18:49:05.450 回答
1

假设您只是想测试回调是否被触发,那么您可以使用模拟函数,例如

const mailCallback = jest.fn();
n.on('mail', mailCallback).start();
...
expect(mailCallback.mock.calls.length).toBe(1); // or however many calls you expect
于 2018-08-07T11:52:42.923 回答