gpt4 book ai didi

unit-testing - 测试 Node.js,模拟并测试所需的模块?

转载 作者:搜寻专家 更新时间:2023-10-31 22:26:50 25 4
gpt4 key购买 nike

我正在努力围绕我的 Node 模块编写高质量的测试。问题是需要模块系统。我希望能够检查某个必需的模块是否具有方法或其状态是否已更改。似乎有 2 个相对较小的库可以在这里使用:node-gentlymockery .然而,由于他们的“低调”,这让我觉得要么人们不测试这个,要么有另一种我不知道的方法。

模拟和测试所需模块的最佳方法是什么?

最佳答案


------------ 更新 ----------------

node-sandbox工作原理与下面所述相同,但包含在一个不错的模块中。我发现与它一起工作非常愉快。


---------------- 详细的awnser ----------------

经过多次试验,我发现在模拟事物时隔离测试 Node 模块的最佳方法是使用 Vojta Jina 的方法在具有新上下文的虚拟机中运行每个模块,如解释的那样 here .

使用这个测试虚拟机模块:

var vm = require('vm');
var fs = require('fs');
var path = require('path');

/**
* Helper for unit testing:
* - load module with mocked dependencies
* - allow accessing private state of the module
*
* @param {string} filePath Absolute path to module (file to load)
* @param {Object=} mocks Hash of mocked dependencies
*/
exports.loadModule = function(filePath, mocks) {
mocks = mocks || {};

// this is necessary to allow relative path modules within loaded file
// i.e. requiring ./some inside file /a/b.js needs to be resolved to /a/some
var resolveModule = function(module) {
if (module.charAt(0) !== '.') return module;
return path.resolve(path.dirname(filePath), module);
};

var exports = {};
var context = {
require: function(name) {
return mocks[name] || require(resolveModule(name));
},
console: console,
exports: exports,
module: {
exports: exports
}
};

vm.runInNewContext(fs.readFileSync(filePath), context);
return context;
};

可以使用自己的上下文测试每个模块,并轻松排除所有外部依赖项。

fsMock = mocks.createFs();
mockRequest = mocks.createRequest();
mockResponse = mocks.createResponse();

// load the module with mock fs instead of real fs
// publish all the private state as an object
module = loadModule('./web-server.js', {fs: fsMock});

我强烈推荐这种方式来单独编写有效的测试。只有验收测试应该影响整个堆栈。单元和集成测试应该测试系统的隔离部分。

关于unit-testing - 测试 Node.js,模拟并测试所需的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9563983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com