过去几天我已经发布了一些问题,这些问题太长了(我猜是因为我没有收到任何非神秘的反馈)。我已尝试将其简短化。
以下代码使用“setup-complete”事件来通知nodeunit setUp命令运行测试。测试 1 通过,测试 2 失败
失败:未完成的测试(或其设置/拆卸): - 基于事件的异步代码 - test2
我的代码有错误吗?对于测试基于事件的代码来说,nodeunit 是一个糟糕的选择吗?我的做法是吗? 任何建议表示赞赏。谢谢
async_setup.js:
var
events = require( 'events' ),
setup = new events.EventEmitter;
module.exports = function ( app, cb ) {
setup.on( 'setup-complete', function () {
cb();
});
setTimeout( function () {
if ( app.result ) throw new Error( "AlreadyConfiguredAppError" );
app.result = "app is configured";
setup.emit( 'setup-complete', app.result );
}, 5000 );
return app;
};
测试/test.js:
var
nodeunit = require( 'nodeunit' ),
async_setup = require( '../async_setup' );
exports[ 'event based async code' ] = nodeunit.testCase({
setUp: function ( callback ) {
this.app = {};
async_setup( this.app, callback );
},
tearDown: function ( callback ) {
delete this.app;
callback();
},
'test1': function ( t ) {
t.expect( 1 );
t.ok( this.app.result !== undefined, 'app is configured' );
t.done();
},
'test2': function ( t ) {
t.expect( 1 );
t.ok( this.app.result !== undefined, 'app is configured' );
t.done();
}
});
最佳答案
问题最终是事件监听器设置在测试之间没有被破坏。我通过修改 setUp 函数以使用 proxyquire 并设置 noPreserveCache 标志来修复该问题:
var proxyquire = require( 'proxyquire' );
...
setUp: function ( callback ) {
this.app = {};
proxyquire.noPreserveCache();
var async_setup = proxyquire( '../async_setup', {} );
async_setup( this.app, callback );
}
Webstorm 中的错误消息包含更多信息,其中包含对 NodeUnit 异步模块错误的堆栈跟踪:
iterator(x.value, function (err, v) {
Cannot read property 'value' of undefined
当我单步执行代码时,我注意到设置了两个事件监听器,尽管我在测试中只设置了一个。
希望这对其他人有帮助。
关于javascript - Nodeunit 测试基于事件的异步代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23328902/