abd*_*_05 4 javascript unit-testing mocha.js node.js express
我正在尝试为快速节点应用程序创建单元测试。我希望用于测试的配置与生产中使用的配置不同,因此我实现了以下内容。
在 my 中index.js,我将配置加载到全局变量中,如下所示:
global.env = {};
global.env.config = require('./config/config');
// Create the server ...
server.listen(3000);
module.exports = server;
Run Code Online (Sandbox Code Playgroud)
在其他一些控制器中myController.js,我像这样访问全局变量
var Config = global.env.config
Run Code Online (Sandbox Code Playgroud)
当我使用node index.js它启动它时,它工作得很好。
但是当我使用带有 proxyquire 的 mocha 来覆盖配置时:
describe('myController', function () {
describe("#myMethod", () => {
it("must work", (done) => {
const config = {
INPUT_FILE_DIR: path.resolve('../ressources/input/')
}
const server = proxyquire('../index.js', { './config/config': config })// error in this line
})
})
})
Run Code Online (Sandbox Code Playgroud)
我有一个错误提示myController无法读取属性配置
Cannot read property 'config' of undefined
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
这就是我接近它的方式。首先,我会将配置导出为函数而不是对象。
原因是代码将具有更好的结构并且易于维护。此外,无需全局公开配置,因为这可能会带来一些安全风险。
export const getConfig = () => {
if(process.env.NODE_ENV==="production"){
return require('./production.config');
}
return require('./default.config');
};
Run Code Online (Sandbox Code Playgroud)
在我的测试文件中,我会sinonjs像下面这样模拟函数调用。
const configModule = require("./config");
sinon.stub(configModule, "getConfig").returns(require('./e2e.config'));
Run Code Online (Sandbox Code Playgroud)
这不是经过测试的代码,但我有点确定这种思维模式应该有效。
| 归档时间: |
|
| 查看次数: |
489 次 |
| 最近记录: |