비동기 함수를 호출하는 동안 mocha 테스트에서 시간 초과 오류를 피하는 방법 : 시간 초과 2000ms 초과
내 노드 응용 프로그램에서 mocha를 사용하여 코드를 테스트하고 있습니다. mocha를 사용하여 많은 비동기 함수를 호출하는 동안 시간 초과 오류 ( Error: timeout of 2000ms exceeded.
) 가 발생 합니다. 이 문제를 어떻게 해결할 수 있습니까?
var module = require('../lib/myModule');
var should = require('chai').should();
describe('Testing Module', function() {
it('Save Data', function(done) {
this.timeout(15000);
var data = {
a: 'aa',
b: 'bb'
};
module.save(data, function(err, res) {
should.not.exist(err);
done();
});
});
it('Get Data By Id', function(done) {
var id = "28ca9";
module.get(id, function(err, res) {
console.log(res);
should.not.exist(err);
done();
});
});
});
테스트를 실행할 때 시간 초과를 설정할 수 있습니다.
mocha --timeout 15000
또는 프로그래밍 방식으로 각 제품군 또는 각 테스트에 대한 시간 초과를 설정할 수 있습니다.
describe('...', function(){
this.timeout(15000);
it('...', function(done){
this.timeout(15000);
setTimeout(done, 15000);
});
});
자세한 내용은 문서를 참조하십시오 .
타임 아웃을 늘리는 "솔루션"이 실제로 진행되고있는 것을 모호하게합니다.
- 코드 및 / 또는 네트워크 호출 속도가 너무 느립니다 (사용자 경험을 좋게하려면 100ms 미만이어야 함)
- 단언 (테스트)이 실패하고 Mocha가 조치를 취하기 전에 오류가 발생했습니다.
You usually encounter #2 when Mocha doesn't receive assertion errors from a callback. This is caused by some other code swallowing the exception further up the stack. The right way of dealing with this is to fix the code and not swallow the error.
When external code swallows your errors
In case it's a library function that you are unable to modify, you need to catch the assertion error and pass it onto Mocha yourself. You do this by wrapping your assertion callback in a try/catch block and pass any exceptions to the done handler.
it('should not fail', function (done) { // Pass reference here!
i_swallow_errors(function (err, result) {
try { // boilerplate to be able to get the assert failures
assert.ok(true);
assert.equal(result, 'bar');
done();
} catch (error) {
done(error);
}
});
});
This boilerplate can of course be extracted into some utility function to make the test a little more pleasing to the eye:
it('should not fail', function (done) { // Pass reference here!
i_swallow_errors(handleError(done, function (err, result) {
assert.equal(result, 'bar');
}));
});
// reusable boilerplate to be able to get the assert failures
function handleError(done, fn) {
try {
fn();
done();
} catch (error) {
done(error);
}
}
Speeding up network tests
Other than that I suggest you pick up the advice on starting to use test stubs for network calls to make tests pass without having to rely on a functioning network. Using Mocha, Chai and Sinon the tests might look something like this
describe('api tests normally involving network calls', function() {
beforeEach: function () {
this.xhr = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
this.xhr.onCreate = function (xhr) {
requests.push(xhr);
};
},
afterEach: function () {
this.xhr.restore();
}
it("should fetch comments from server", function () {
var callback = sinon.spy();
myLib.getCommentsFor("/some/article", callback);
assertEquals(1, this.requests.length);
this.requests[0].respond(200, { "Content-Type": "application/json" },
'[{ "id": 12, "comment": "Hey there" }]');
expect(callback.calledWith([{ id: 12, comment: "Hey there" }])).to.be.true;
});
});
See Sinon's nise
docs for more info.
A little late but someone can use this in future...You can increase your test timeout by updating scripts in your package.json with the following:
"scripts": { "test": "test --timeout 10000" //Adjust to a value you need }
Run your tests using the command test
For me the problem was actually the describe function, which when provided an arrow function, causes mocha to miss the timeout, and behave not consistently. (Using ES6)
since no promise was rejected I was getting this error all the time for different tests that were failing inside the describe block
so this how it looks when not working properly:
describe('test', () => {
assert(...)
})
and this works using the anonymous function
describe('test', function() {
assert(...)
})
Hope it helps someone, my configuration for the above: (nodejs: 8.4.0, npm: 5.3.0, mocha: 3.3.0)
My issue was not sending the response back, so it was hanging. If you are using express make sure that res.send(data), res.json(data) or whatever the api method you wanna use is executed for the route you are testing.
'Programing' 카테고리의 다른 글
자동 레이아웃이있는 UICollectionView 자체 크기 조정 셀 (0) | 2020.05.16 |
---|---|
Visual Studio에서 설치된 TypeScript 버전을 어디에서 찾을 수 있습니까? (0) | 2020.05.16 |
MYSQL 업데이트 명령문 내부 조인 테이블 (0) | 2020.05.16 |
JavaScript / JQuery를 사용하여 간단한지도를 만드는 방법 (0) | 2020.05.16 |
캔버스 요소에서 요소를 그린 후 불투명도 (알파, 투명도)를 변경하는 방법은 무엇입니까? (0) | 2020.05.16 |