javascript - 使用 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()”;如果返回 Promise,请确保它已解决。
解决方案
感谢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');
});
});
推荐阅读
- scala - 在函数参数级别实现 Ad hoc 多态性(混合不同类型的参数)
- python - 对特定索引 PyTorch 求和(类似于 scatter_add)
- python-3.x - 如何使用 python 查找和更新 XML 文件内容
- docker - docker-compose 中的字符串插值环境变量
- python - 递归调用字典以查找最后一个值
- stored-procedures - 在雪花中,如何从动态查询中删除单引号。在这种情况下,反斜杠没有多大用处
- javascript - 将图标传递给 JS 对象
- python - 我的 django web app 评论表单显示不正确
- python - 为 conv1D Keras NN 找到正确的输入和输出形状
- odoo - Odoo 覆盖删除记录确认对话框