簡體   English   中英

使用mocha / chai測試幾個函數回調

[英]Test several functions callbacks with mocha/chai

我有一個全局對象,可以為事件分配功能,例如:

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()”; 如果返回承諾,請確保其解決。

感謝LostJon的評論!

我的解決方案是將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');
 });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM