尝试连接API时,Mocha测试套件出错

Jak*_*rsh 10 javascript unit-testing mocha.js gulp

我正在使用mocha,通过gulp-jsx-coverage和运行我的测试套件gulp-mocha.我的所有测试都按预期运行并通过/失败.但是,我测试的一些模块通过superagent库向我的API发出HTTP请求.

在开发中,我还在localhost:3000我的客户端应用程序旁边运行我的API ,因此这是我的客户端测试试图访问的URL.但是,在测试时,API通常不会运行.每当请求通过时,都会导致以下错误:

Error in plugin 'gulp-mocha'
Message:
    connect ECONNREFUSED
Details:
    code: ECONNREFUSED
    errno: ECONNREFUSED
    syscall: connect
    domainEmitter: [object Object]
    domain: [object Object]
    domainThrown: false
Stack:
Error: connect ECONNREFUSED
    at exports._errnoException (util.js:746:11)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
Run Code Online (Sandbox Code Playgroud)

我已经尝试在全局帮助器中对superagent(别名为request)库中的所有方法进行存根,如下所示:

function httpStub() {
  return {
    withCredentials: () => {
      return { end: () => {} };
    }
  };
};

beforeEach(function() {
  global.sandbox = sinon.sandbox.create();

  global.getStub = global.sandbox.stub(request, 'get', httpStub);
  global.putStub = global.sandbox.stub(request, 'put', httpStub);
  global.patchStub = global.sandbox.stub(request, 'patch', httpStub);
  global.postStub = global.sandbox.stub(request, 'post', httpStub);
  global.delStub = global.sandbox.stub(request, 'del', httpStub);
});

afterEach(function() {
  global.sandbox.restore();
});
Run Code Online (Sandbox Code Playgroud)

但由于某些原因,当遇到某些测试时,这些方法没有存根,因此我得出ECONNREFUSED错误.我已经三次检查了,我没有在哪里恢复沙箱或任何存根.

有没有办法解决我遇到的问题,或者整体上更清洁的解决方案?

Tom*_*ich 4

该问题可能是由于在测试中未正确执行异步操作而引起的。想象一下下面的例子:

it('is BAD asynchronous test', () => {
  do_something()
  do_something_else()
  return do_something_async(/* callback */ () => {
    problematic_call()
  })
})
Run Code Online (Sandbox Code Playgroud)

当 Mocha 找到这样的测试时,它会(同步)执行do_something,do_something_elsedo_something_async。在那一刻,从 Mochas 的角度来看,测试结束了,Mocha 为其执行 afterEach() (糟糕的是,problematic_call没有被调用!)并且(更糟糕的是),它开始运行下一个测试!

现在,显然,以并行方式运行测试(以及 beforeEach 和 afterEach)可能会导致非常奇怪且不可预测的结果,因此出现错误也就不足为奇了(可能在某些测试过程中调用了 afterEach ,这导致了环境的取消)

该怎么办:

当你的测试结束时,一定要向 Mocha 发出信号。这可以通过返回 Promise 对象或调用done回调来完成:

it('is BAD asynchronous test', (done) => {
  do_something()
  do_something_else()
  return do_something_async(/* callback */ () => {
    problematic_call()
    done()
  })
})
Run Code Online (Sandbox Code Playgroud)

https://mochajs.org/

这样,Mocha 就“知道”您的测试何时结束,然后才运行下一个测试。