【问题标题】:How to test restful webservices with Mocha and Chai如何使用 Mocha 和 Chai 测试 RESTful Web 服务
【发布时间】: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


    【解决方案1】:

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

    1. 当 Mocha 单元测试需要等待某些东西时,它们必须返回一个 Promise
    2. 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);
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 2014-10-01
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多