【发布时间】:2022-06-20 17:46:42
【问题描述】:
我是编写单元测试的新手,我正在尝试学习 Mocha 和 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=300 网络服务在测试执行时处于活动状态,我可以看到 Mocha 确实调用了它,因为我的网络服务记录了传入的请求。该网络服务正在使用the SSE protocol,它从不关闭连接,但它会不时地通过同一个连接发送数据。 EventSource 是实现 SSE 协议的客户端类,当您在其中设置 onmessage 回调时,它会连接到服务器。但是,Mocha 不会等待 web 服务返回,并且测试通过了我写入 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 等待 web 服务返回数据,然后再将测试解析为通过?
【问题讨论】:
标签: node.js web-services mocha.js chai server-sent-events