NodeJS UnhandledPromiseRejectionWarning
그래서 이벤트 이미 터를 사용하는 구성 요소를 테스트하고 있습니다. 그렇게하기 위해 Mocha + Chai와 함께 Promises를 사용하는 솔루션을 생각해 냈습니다.
it('should transition with the correct event', (done) => {
const cFSM = new CharacterFSM({}, emitter, transitions);
let timeout = null;
let resolved = false;
new Promise((resolve, reject) => {
emitter.once('action', resolve);
emitter.emit('done', {});
timeout = setTimeout(() => {
if (!resolved) {
reject('Timedout!');
}
clearTimeout(timeout);
}, 100);
}).then((state) => {
resolved = true;
assert(state.action === 'DONE', 'should change state');
done();
}).catch((error) => {
assert.isNotOk(error,'Promise error');
done();
});
});
콘솔에 'AssertionError : Promise error'메시지가 즉시 표시되므로 거부 함수가 호출되었지만 'UnhandledPromiseRejectionWarning'이 나타납니다.
(node : 25754) UnhandledPromiseRejectionWarning : 처리되지 않은 약속 거부 (거부 ID : 2) : AssertionError : 약속 오류 : 예상 {개체 (메시지, showDiff, ...)}가 거짓 1 임) 올바른 이벤트로 전환해야 함
그리고 2 초 후
오류 : 시간 초과 2000ms를 초과했습니다. 이 테스트에서 done () 콜백이 호출되고 있는지 확인하십시오.
catch 콜백이 실행 된 이후로 더 이상합니다 (어떤 이유로 든 어설 션 실패로 인해 나머지 실행이 차단되었다고 생각합니다)
이제 재미있는 것은 assert.isNotOk(error...)
콘솔에서 경고없이 테스트가 제대로 실행되었다는 것입니다. 캐치를 실행한다는 의미에서 여전히 '실패'합니다.
그러나 여전히, 나는 이러한 오류를 약속으로 이해할 수 없습니다. 누군가 나를 밝게 할 수 있습니까?
이 문제는 다음으로 인해 발생합니다.
.catch((error) => {
assert.isNotOk(error,'Promise error');
done();
});
어설 션이 실패하면 오류가 발생합니다. 이 오류는 done()
코드가 오류를 일으켰 기 때문에 호출되지 않습니다. 이것이 시간 초과를 일으키는 원인입니다.
"처리되지 않은 약속 거부"가 아니라 오류가 던져 경우 때문에 실패 주장에 의해 발생 catch()
핸들러 및 후속가없는 catch()
핸들러 (에 설명 된대로 오류가 삼킨 얻을 것이다 이 문서 ). UnhandledPromiseRejectionWarning
이 사실을 경고 하는 경고입니다.
일반적으로 Mocha에서 약속 기반 코드를 테스트하려면 Mocha 자체가 이미 약속을 처리 할 수 있다는 사실에 의존해야합니다. 을 사용하지 done()
말고 대신 테스트에서 약속을 반환하십시오. 그런 다음 Mocha는 오류 자체를 포착합니다.
이처럼 :
it('should transition with the correct event', () => {
...
return new Promise((resolve, reject) => {
...
}).then((state) => {
assert(state.action === 'DONE', 'should change state');
})
.catch((error) => {
assert.isNotOk(error,'Promise error');
});
});
sinon으로 스터 빙 할 때이 오류가 발생했습니다.
해결책은 스텁으로 약속을 해결하거나 거부 할 때 약속대로 npm 패키지를 사용 하는 것입니다.
대신에 ...
sinon.stub(Database, 'connect').returns(Promise.reject( Error('oops') ))
사용하다 ...
require('sinon-as-promised');
sinon.stub(Database, 'connect').rejects(Error('oops'));
There is also a resolves method (note the s on the end).
See http://clarkdave.net/2016/09/node-v6-6-and-asynchronously-handled-promise-rejections
The assertion libraries in Mocha work by throwing an error if the assertion was not correct. Throwing an error results in a rejected promise, even when thrown in the executor function provided to the catch
method.
.catch((error) => {
assert.isNotOk(error,'Promise error');
done();
});
In the above code the error
objected evaluates to true
so the assertion library throws an error... which is never caught. As a result of the error the done
method is never called. Mocha's done
callback accepts these errors, so you can simply end all promise chains in Mocha with .then(done,done)
. This ensures that the done method is always called and the error would be reported the same way as when Mocha catches the assertion's error in synchronous code.
it('should transition with the correct event', (done) => {
const cFSM = new CharacterFSM({}, emitter, transitions);
let timeout = null;
let resolved = false;
new Promise((resolve, reject) => {
emitter.once('action', resolve);
emitter.emit('done', {});
timeout = setTimeout(() => {
if (!resolved) {
reject('Timedout!');
}
clearTimeout(timeout);
}, 100);
}).then(((state) => {
resolved = true;
assert(state.action === 'DONE', 'should change state');
})).then(done,done);
});
I give credit to this article for the idea of using .then(done,done) when testing promises in Mocha.
For those who are looking for the error/warning UnhandledPromiseRejectionWarning
outside of a testing environment, It could be probably because nobody in the code is taking care of the eventual error in a promise:
For instance, this code will show the warning reported in this question:
new Promise((resolve, reject) => {
return reject('Error reason!');
});
(node:XXXX) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Error reason!
and adding the .catch()
or handling the error should solve the warning/error
new Promise((resolve, reject) => {
return reject('Error reason!');
}).catch(() => { /* do whatever you want here */ });
Or using the second parameter in the then
function
new Promise((resolve, reject) => {
return reject('Error reason!');
}).then(null, () => { /* do whatever you want here */ });
Here's my take experience with E7 async/await:
In case you have an async helperFunction()
called from your test... (one explicilty with the ES7 async
keyword, I mean)
→ make sure, you call that as await helperFunction(whateverParams)
(well, yeah, naturally, once you know...)
And for that to work (to avoid ‘await is a reserved word’), your test-function must have an outer async marker:
it('my test', async () => { ...
I solved this problem after uninstalling webpack (react js problem ).
sudo uninstall webpack
I faced this issue:
(node:1131004) UnhandledPromiseRejectionWarning: Unhandled promise rejection (re jection id: 1): TypeError: res.json is not a function (node:1131004) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.j s process with a non-zero exit code.
It was my mistake, I was replacing res
object in then(function(res)
, so changed res
to result and now it is working.
Wrong
module.exports.update = function(req, res){
return Services.User.update(req.body)
.then(function(res){//issue was here, res overwrite
return res.json(res);
}, function(error){
return res.json({error:error.message});
}).catch(function () {
console.log("Promise Rejected");
});
Correction
module.exports.update = function(req, res){
return Services.User.update(req.body)
.then(function(result){//res replaced with result
return res.json(result);
}, function(error){
return res.json({error:error.message});
}).catch(function () {
console.log("Promise Rejected");
});
Service code:
function update(data){
var id = new require('mongodb').ObjectID(data._id);
userData = {
name:data.name,
email:data.email,
phone: data.phone
};
return collection.findAndModify(
{_id:id}, // query
[['_id','asc']], // sort order
{$set: userData}, // replacement
{ "new": true }
).then(function(doc) {
if(!doc)
throw new Error('Record not updated.');
return doc.value;
});
}
module.exports = {
update:update
}
참고URL : https://stackoverflow.com/questions/39716569/nodejs-unhandledpromiserejectionwarning
'programing tip' 카테고리의 다른 글
알 수없는 확장명을 포함하는 IPv6 확장 헤더 구문 분석 (0) | 2020.07.29 |
---|---|
C # 6“정적 사용”기능을 어떻게 사용합니까? (0) | 2020.07.29 |
sys.path / PYTHONPATH에 디렉토리 추가 (0) | 2020.07.29 |
클래스 속성을 만드는 방법? (0) | 2020.07.29 |
HTTP 엔터티 란 정확히 무엇입니까? (0) | 2020.07.29 |