2017-03-07 45 views
0
运行单元测试时需要考虑

我有下面的代码在我的服务器上的文件:如何更改服务需要在嘲笑的NodeJS

// Internal modules 
const authenticationService = require('../services/authenticationService'); 
// Setup 
app.use(bodyParser.urlencoded({ 
    extended: true 
})); 
app.use(bodyParser.json()); 

// Init routing 
require('./controllers/authenticationController')(app, authenticationService); 

app.listen(8081, (err) => { 
    if (err) throw new Error('Could not start the server'); 
}); 

现在,这是罚款,并将努力。但是如果我运行单元测试并想用冒号版本替换authenticationService呢?对我的API执行测试时,我不想打我的真实数据库。我是否构造了这个错误,或者我应该如何处理这个问题?我知道我可以使用不同的模拟模块伪造authenticationService,但老实说,我不太喜欢使用sinon等。这次我宁愿写自己的模拟服务。任何想法/帮助?

+2

第一件事应该是导出应用程序变量,以便它可以被测试。在这种情况下,我认为[proxyquire](https://www.npmjs.com/package/proxyquire)可以帮助你。您可以在链接中找到文档。基本上它允许你从你的测试中需要应用程序,并为你的依赖项传递模拟变量 – Richnologies

+0

Proxyquire似乎可以完成这项工作。感谢您的输入。 – tjugg

回答

1

Sinon是构建模拟/存根对象的好方法。

但它需要你注入模拟/存根对象插入到servrice代码和前提是,该代码与依赖倒置原则

所以我觉得rewire模块可以帮助你保持一致。通过使用rewire,您可以轻松实现覆盖依赖关系,而无需修改现有代码。

1

你需要的是dependency injection。而不是直接做

require('../services/authenticationService'); 

在你的模块中,你的模块应该接受authenticationService作为依赖。所以,如果你封装你的代码放到一个模块,说SomeModule.js:

module.exports = function SomeModule(authenticationService, app, otherDependencies /* such as bodyParser etc. as needed. */) { 
    this.start = function(port) { 
    // your code goes here 
    // more code 
    app.listen(8081, (err) => { 
     if (err) throw new Error('Could not start the server'); 
    }); 
    } 
} 

然后在你的产品代码,你可以这样调用:

var myModule = new SomeModule(require('../services/authenticationService'), app /* and all other dependencies required by SomeModule.*/); 
module.start(8081); 

并在测试代码,你可以叫它像这样:

var myModule = new SomeModule(require('../mocks/mockAuthenticationService'), app /* and all other dependencies required by SomeModule.*/); 
module.start(8081);