Web Services 如何使用Mocha和Chai测试REST Web服务

moiiocjp  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(149)

我是编写单元测试的新手,我正在努力学习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 Web服务是活动的,我可以看到Mocha确实调用了它,因为我的Web服务记录了传入的请求。该Web服务使用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服务返回数据,然后再将测试解析为通过?

zbwhf8kr

zbwhf8kr1#

经过几次试验结束错误,我发现
1.当Mocha单元测试需要等待某个东西时,它们必须返回一个Promise

  1. EventSource npm包(它与本地EventSource Javascript对象不是100%兼容),由于某些原因,可能总是,可能只有在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);
        });
    });
});

相关问题