【问题标题】:Test several functions callbacks with mocha/chai使用 mocha/chai 测试几个函数回调
【发布时间】:2018-09-04 19:20:50
【问题描述】:

我有一个全局对象,它能够为事件分配函数,例如:

obj.on('event', () => {});

在调用确切的公共 API 后,这些事件也会被触发。

现在我需要用 mocha.js/chai.js 编写异步测试并在 node.js 环境中运行。

我陷入了一个应该同时测试两个事件订阅的情况。

所有代码都是用 TypeScript 编写的,然后转译成 JavaScript。

全局对象中的代码:

public someEvent(val1: string, val2: Object) {
 // some stuff here...
 this.emit('event_one', val1);
 this.emit('event_two', val1, val2);
}

测试文件中的代码(我的最新实现):

// prerequisites are here...
describe('test some public API', () => {
 it('should receive a string and an object', (done) => {
  // counting number of succesfull calls
  let steps = 0;

  // function which will finish the test
  const finish = () => {
   if ((++steps) === 2) {
    done();
   }
  };

  // mock values
  const testObj = {
   val: 'test value'
  };

  const testStr = 'test string';

  // add test handlers
  obj.on('event_one', (key) => {
   assert.equal(typeof key, 'string');
   finish();
  });

  obj.on('event_two', (key, event) => {
   assert.equal(typeof key, 'string');
   expect(event).to.be.an.instanceOf(Object);
   finish();
  });

  // fire the event
  obj.someEvent(testStr, testObj);
 });
});

所以,我的问题是 - 是否有任何内置功能可以让这个测试看起来更优雅?

另一个问题是如何提供一些有意义的错误信息而不是默认的错误字符串?

错误:超过 2000 毫秒的超时。对于异步测试和钩子,确保调用了“done()”;如果返回 Promise,请确保它已解决。

【问题讨论】:

  • 如果 event_oneevent_two 没有逻辑连接,你可能应该做 2 个单独的测试
  • 但是这些事件是一个接一个地触发的。而且我需要检查值是否在途中以某种方式发生突变,并确保两个事件都被触发。
  • 如果你知道执行顺序,你可以嵌套它们并在第二个事件触发后调用done(),但如果它们是两个独立的事件,它们之间没有关联,你应该编写两个独立的测试,你可以确保两个测试都通过
  • 你能举个例子吗?另外,您对如何处理超时错误有任何想法吗?谢谢!
  • 你应该在你的实现中添加间谍。这个链接有点帮助stackoverflow.com/questions/27209016/…

标签: javascript node.js testing mocha.js chai


【解决方案1】:

感谢LostJon的cmets!

我的解决方案是将sinon.js 库添加到项目中并使用sinon.spy

解决方案是这样的:

import * as sinon from 'sinon';

...

// prerequisites are here...
describe('test some public API', () => {
 it('should receive a string and an object', (done) => {
  const spyOne = sinon.spy();
  const spyTwo = sinon.spy();

  // mock values
  const testObj = {
   val: 'test value'
  };

  const testStr = 'test string';

  // add test handlers
  obj.on('event_one', spyOne);
  obj.on('event_two', spyTwo);

  // fire the event
  obj.someEvent(testStr, testObj);

  // assert cases
  assert(spyOne.calledOnce, `'event_one' should be called once`);
  assert.equal(typeof spyOne.args[0][0], 'string');

  assert(spyTwo.calledOnce, `'event_two' should be called once`);
  assert.equal(typeof spyTwo.args[0][0], 'string');
  assert.equal(typeof spyTwo.args[0][1], 'object');
 });
});

【讨论】:

    猜你喜欢
    • 2015-11-18
    • 2015-07-25
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多