嘲笑正在testing的方法内部的一个函数

我想testing一个方法在我的代码执行一组不同的function…和其中一个内部函数被调用时,发送电子邮件。

我想要的是避免这个function在运行testing时发送电子邮件。 有没有办法做到这一点?

我想在我的代码中远离类似以下的东西:

if (app.get('env') !== 'test') 

我使用承诺 ,我想testing的function如下所示:

 var emailService = require('../path/to/custom/service.js'); // This is the method I want to test exports.sendKeyByEmail = function(email) { return _getByEmail(email) // finds a user given an email .then(function(user) { if (!user) { throw new UserNotFoundError(); } user.key = _generateKey(); // generates a random hash return user.save(); // saves the user (mongoose stuff...) }) .then(function(user) { // This is what I would like to mock during testing return emailService.sendKey(user.email, user.key); }); } 

emailService.sendKey()方法是发送电子邮件并返回Promise的方法。 在testing期间,我希望它直接返回一个完成的Promise Promise.resolve() ,而不是真的发送一封电子邮件。

我昨天回答了一个问题 :不是将两个问题结合到一个私有方法或隐藏函数中,而是将它们分成两个类,并将电子邮件实现传递给外部类。 这将允许您在testing期间提供一个模拟emailService ,并且相当整洁地解决您的问题。

当设置这个时,我是构造函数dependency injection的粉丝,因为它给你的DI的好处没有做任何棘手的事情(如reflection)。 有了ES6参数,你也可以提供一个默认值,当你不嘲笑任何东西。

非常粗略地说,你可以做一些事情:

 var defaultEmailService = require('../path/to/custom/service.js'); // This is the method I want to test exports.sendKeyByEmail = function(email, emailService = defaultEmailService) { return _getByEmail(email) // finds a user given an email .then(function(user) { if (!user) { throw new UserNotFoundError(); } user.key = _generateKey(); // generates a random hash return user.save(); // saves the user (mongoose stuff...) }) .then(function(user) { // This is what I would like to mock during testing return emailService.sendKey(user.email, user.key); }); } 

在你的testing中,只需传递一个模拟emailService ,返回可预测的结果,而无需触摸networking。