我已经使用nodeunit编写了一堆测试来测试我的代码.在这样做时,我想模拟被测代码所需的模块.而不是更改代码使其更容易测试与模拟,控制反转,当不需要时,我改为使用nodeunits沙箱功能.
例
var nodeunit = require("nodeunit");
export.MyTest = {
test1(test) {
var fakeGlobals = {
require: function(filename) {
if (filename == "CoolUtil.js") {
return { doit: function wasCool() { return true; } };
} else {
return require(filename);
}
}
};
var testSubject = nodeunit.utils.sandbox("ModuleUnderTest.js", fakeGlobals);
test.equals(42, testSubject.doSomethingCoolUsingCoolUtil(), "Worked");
test.done();
}
}
Run Code Online (Sandbox Code Playgroud)
伊斯坦布尔给了我错误的报道编号.我尝试使用标志--post-require-hook,据说它与RequireJS一起使用,我很好切换到但尚未学习.
test/node_modules/.bin/istanbul cover --v --hook-run-in-context --root test/node_modules/.bin/nodeunit - --reporter junit --output target/results/unit_tests test
有没有人成功使用nodeunit,istanbul并在nodeunit中使用沙箱功能?
我有用 JavaScript编写的测试,我使用TravisCI进行测试.
我package.json是这样的:
"scripts": {
"test": "node testsRunner.js"
}
Run Code Online (Sandbox Code Playgroud)
而我的.travis.yml是:
language: node_js
node_js:
- '0.12.7'
Run Code Online (Sandbox Code Playgroud)
'testsRunner.js'是:
var nodeunit = require('nodeunit');
var path = require('path');
nodeunit.reporters.default.run([
path.join(__dirname, 'suite1/test.js')
]);
Run Code Online (Sandbox Code Playgroud)
而suite1/test.js最后是:
module.exports = {
setUp: function(callback) {
// Initialization code...
callback();
},
tearDown: function(callback) {
// Cleanup...
callback();
},
test1: function(test) {
test.expect(10); // This test expects 10 assertions to be run
// Doing stuff...
test.done();
},
test2: function(test) {
test.expect(10); // …Run Code Online (Sandbox Code Playgroud) 我在我的node.js应用程序中有一个JS方法,我想进行单元测试.它对服务方法进行多次调用,每次都将该服务传递回调; 回调累积结果.
我如何使用Jasmine来删除服务方法,以便每次调用存根时,它都会使用由参数确定的响应来调用回调?
这是(就像)我正在测试的方法:
function methodUnderTest() {
var result = [];
var f = function(response) {result.push(response)};
service_method(arg1, arg2, f);
service_method(other1, other2, f);
// Do something with the results...
}
Run Code Online (Sandbox Code Playgroud)
我想指定当使用arg1和arg2调用service_method时,存根将使用特定响应调用f回调,并且当使用other1和other2调用它时,它将使用不同的特定响应调用相同的回调.
我也考虑一个不同的框架.(我尝试过Nodeunit,但没有按照我的意愿去做.)
因此,在本教程的帮助下,我决定在我的node.js应用程序中添加一些单元测试.我的gruntfile似乎没问题,当我输入grunt nodeunit我的唯一测试运行就好了,但在那之后,它崩溃了错误Fatal error: Cannot find module 'tap':
$> grunt nodeunit
Running "nodeunit:all" (nodeunit) task
Testing db.test.js
.OK
Fatal error: Cannot find module 'tap'
Run Code Online (Sandbox Code Playgroud)
我对这个模块一无所知,但是在搞砸之后,似乎这是nodeunit需要的东西.事实上,它$MY_NODE_APP/node_modules/nodeunit/node_modules/tap存在:存在,当我启动节点$MY_NODE_APP/node_modules/nodeunit并输入require('tap')交互式控制台时,我得到一些带有很多东西的对象,这给我的印象是它应该正常工作.
所以,显而易见的问题是:为什么我会收到此错误,我该如何解决?
Gruntfile:
module.exports = function(grunt) {
grunt.initConfig({
nodeunit: {
all: ['./**/*.test.js']
}
});
grunt.loadNpmTasks('grunt-contrib-nodeunit');
};
Run Code Online (Sandbox Code Playgroud)
更新:安装tap到我的项目,但它也没有帮助.