【发布时间】:2017-05-02 15:29:54
【问题描述】:
我正在尝试模拟从测试中导出为模块的方法服务。 这是我用“sinon”做的事情,但我想尽可能多地使用jest。
这是一个经典的测试,我有一个“身份验证”服务和一个“邮件”服务。
“身份验证”服务可以注册新用户,每次新注册后,它都会要求邮件服务向新用户发送一封“欢迎邮件”。
所以测试我的身份验证服务的注册方法,我想断言(并模拟)邮件服务的“发送”方法。
如何做到这一点?这是我尝试过的,但它调用了原始的 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);
}
});
});
});
});
【问题讨论】:
标签: javascript jestjs