我正在使用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)我尝试过在全局助手中的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();
});但是由于某些原因,当遇到一些测试时,这些方法没有被删除,所以我到达了ECONNREFUSED错误。我已经三次检查过了,我在哪里恢复沙箱或任何存根。
有没有一种方法来解决我遇到的问题,或者为这个问题找到一个更干净的解决方案?
发布于 2016-01-06 12:02:10
这个问题可能是由于您的测试中没有正确地执行异步操作而造成的。想象一下下面的例子:
it('is BAD asynchronous test', () => {
do_something()
do_something_else()
return do_something_async(/* callback */ () => {
problematic_call()
})
})当Mocha找到这样的测试时,它会(同步)执行do_something、do_something_else和do_something_async。在那一刻,从Mochas的角度看,测试结束了,Mocha为它执行afterEach() (糟糕的是,problematic_call还没有被调用!)而且(更糟的是),它开始运行下一个测试!
现在,很明显,以并行方式运行测试(以及beforeEach和afterEach)可能会导致非常奇怪和不可预测的结果,因此不奇怪会有什么事情出错(可能是在一些测试过程中调用了afterEach,这导致了环境的崩溃)
该如何处理:
测试结束时,总是给摩卡发信号。这可以通过返回承诺对象,或者通过调用done回调来实现:
it('is BAD asynchronous test', (done) => {
do_something()
do_something_else()
return do_something_async(/* callback */ () => {
problematic_call()
done()
})
})这样,Mocha‘知道’什么时候测试结束,然后它才会运行下一个测试。
发布于 2016-01-06 12:25:46
应用程序已经需要request,所以在测试中是否使用存根并不重要。
您需要使用类似于rewire的内容,并将应用程序所需的request替换为短尾版本。
像这样的东西会有帮助的
var request = require('superagent'),
rewire = require('rewire'),
sinon = require('sinon'),
application = rewire('your-app'),
rewiredRequest;
function httpStub() {
return {
withCredentials: () => {
return { end: () => {} };
}
};
};
beforeEach(function() {
var requestStub = {
get: httpStub,
put: httpStub,
patch: httpStub,
post: httpStub,
del: httpStub
};
// rewiredRequest is a function that will revert the rewiring
rewiredRequest = application.__set__({
request: requestStub
});
});
afterEach(function() {
rewiredRequest();
});https://stackoverflow.com/questions/34572881
复制相似问题