繁体   English   中英

基于节点单元测试事件的异步代码

[英]Nodeunit testing event based async code

过去几天,我已经发布了一些问题,这些问题太长了(我猜是因为我没有收到任何非神秘的反馈)。 我已经试过简短了。

以下代码使用“ 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函数以使用带有noPreserveCache标志集的proxyquire来解决此问题:

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

当我单步执行代码时,我注意到有两个事件侦听器设置,即使我在测试中只设置了一个。

希望这可以帮助其他人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM