如何使用Mocha和Chai测试rest式web服务



我是编写单元测试的新手,我正在尝试学习摩卡和Chai。在我的Node+express项目中,我创建了一个这样的单元测试:

import { expect } from 'chai';
var EventSource = require('eventsource');
describe('Connection tests', () => { // the tests container
it('checks for connection', () => { // the single test
var source = new EventSource('http://localhost:3000/api/v1/prenotazione?subscribe=300');
source.onmessage = function(e: any) {
expect(false).to.equal(true);
};
});
});

当测试执行时,http://localhost:3000/api/v1/prenotazione?subscribe=300webservice是活动的,我可以看到Mocha调用它,因为我的webservice记录传入的请求。该web服务使用SSE协议,它从不关闭连接,但它不时地在同一连接上发送数据。EventSource是实现SSE协议的客户端类,当您在其中设置onmessage回调时,它将连接到服务器。然而,Mocha不等待webservice返回,并且测试通过了我写入expect函数调用的任何内容。例如,为了调试测试代码本身,我甚至编写了显然永远不可能为真的expect(false).to.equal(true);。然而,这是我运行测试时得到的结果:

$ npm run test
> crud@1.0.0 test
> mocha -r ts-node/register test/**/*.ts --exit

Connection tests
✔ checks for connection

1 passing (23ms)

如何让Mocha等待webservice返回数据,然后再解析测试是否通过?

经过几次尝试结束错误后,我发现

  1. 当Mocha单元测试需要等待某事时,它们必须返回一个Promise
  2. EventSource npm包(它不是100%兼容原生EventSource Javascript对象),出于某种原因,也许总是,也许只有在Mocha或其他地方使用时,不调用onmessage处理程序,所以你必须使用替代的addEventListener函数添加事件监听器

下面是我的工作代码:

describe('SSE Protocol tests', () => {
it('checks for notifications on data changes', function () { 
this.timeout(0);
return new Promise<boolean>((resolve, _reject) => {
var eventSourceInitDict = {https: {rejectUnauthorized: false}};
var source = new EventSource('http://localhost:3000/api/v1/prenotazione?subscribe=3600', eventSourceInitDict);
var count = 2;
source.addEventListener("results", function(event: any) {
const data = JSON.parse(event.data);
count--;
if(count == 0)  {
resolve(true);
}       
});
}).then(value => {
assert.equal(typeof(value), 'boolean');
assert.equal(value, true);
}, error => {
assert(false, error);
});
});
});

最新更新