使用jest在nodejs中测试mail-notifier

Ton*_*hew 7 unit-testing node.js jestjs node-notifier

有谁知道如何测试nodejs中的mail-notifier模块?我想测试里面的逻辑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();
Run Code Online (Sandbox Code Playgroud)

Jam*_*mes 1

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

const mailCallback = jest.fn();
n.on('mail', mailCallback).start();
...
expect(mailCallback.mock.calls.length).toBe(1); // or however many calls you expect
Run Code Online (Sandbox Code Playgroud)