javascript - Nodeunit 测试基于事件的异步代码

标签 javascript node.js unit-testing events nodeunit

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

以下代码使用“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/

相关文章:

javascript - 如何使用 AWS S3 中的预签名 cookie 在 ReactPlayer 上实现电影播放器

node.js - gruntjs 0.4 registerHelper 已弃用,语法修复?

c# - 响应式扩展测试调度程序模拟时间流逝

java - Junit:如何让每个@Test方法完全隔离?

javascript - 如何在给定值和 <select> 名称的情况下选择 <option> 的标签

javascript - AngularJS 删除范围内数组的最后一个元素

javascript - 在不刷新的情况下加载新页面时 CSS 加载缓慢

javascript - 异步/等待 promise 未决错误

javascript - 使用 TypeScript 扩展 Element 原型(prototype)

java - 从另一个类方法内部调用时无法正确模拟方法调用