使用 Jest 时模拟被测试者调用的服务的方法

Lud*_*udo 5 javascript jestjs

我正在尝试模拟我从测试中导出为模块的方法服务。这是我用“sinon”做的事情,但我想尽可能多地使用笑话。

这是一个经典的测试,我有一个“身份验证”服务和一个“邮件程序”服务。

“认证”服务可以注册新用户,每次新注册后,它会要求邮件服务向新用户发送“欢迎邮件”。

所以测试我的身份验证服务的注册方法,我想断言(和模拟)邮件服务的“发送”方法。

怎么做?这是我尝试过的,但它调用了原始的 mailer.send 方法:

// authentication.js

const mailer = require('./mailer');

class authentication {
  register() { // The method i am trying to test
    // ...

    mailer.send();
  }
}

const authentication = new Authentication();

module.exports = authentication;


// mailer.js

class Mailer {
  send() { // The method i am trying to mock
    // ...
  }
}

const mailer = new Mailer();

module.exports = mailer;


// authentication.test.js

const authentication = require('../../services/authentication');

describe('Service Authentication', () => {
  describe('register', () => {
    test('should send a welcome email', done => {
      co(function* () {
        try {
          jest.mock('../../services/mailer');
          const mailer = require('../../services/mailer');
          mailer.send = jest.fn( () => { // I would like this mock to be called in authentication.register()
            console.log('SEND MOCK CALLED !');
            return Promise.resolve();
          });

          yield authentication.register(knownUser);

          // expect();

          done();
        } catch(e) {
          done(e);
        }
      });
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

And*_*rle 7

首先,您必须mailer使用间谍模拟模块,以便稍后进行设置。您要让 jest 知道在您的测试中使用 Promise,请查看文档以了解两种方法。

const authentication = require('../../services/authentication');
const mailer = require('../../services/mailer');
jest.mock('../../services/mailer', () => ({send: jest.fn()})); 

describe('Service Authentication', () => {
  describe('register', () => {
    test('should send a welcome email', async() => {
          const p = Promise.resolve()
          mailer.send.mockImplementation(() =>  p) 
          authentication.register(knownUser);
          await p
          expect(mailer.send).toHaveBeenCalled;
        }
      });
    });
  });
});
Run Code Online (Sandbox Code Playgroud)