Javascript Promises: testing error scenario - javascript

How do I test a promise that rejects with an error? (that is the expected behaviour)
I can not figure out why this test is failing. I'm catching the error rejected, and the test still fails. From the example provided at https://www.sitepoint.com/promises-in-javascript-unit-tests-the-definitive-guide/ this should work, and can't figure out how it's supposed to really. Both console logs appear.
it('shows that even an error occurs the test passes', (done) => {
const promise = new Promise((resolve, reject) => {
console.log('error promise is called');
setTimeout(() => {
reject(new Error('dummy error thrown'));
}, 100);
})
promise.then(() => {});
promise.catch((e) => {
console.log('error caught');
done();
});
});
1) promise behaviour in tests (async) - base test cases shows that even an error occurs the test passes:
Uncaught Error: dummy error thrown
at Timeout.setTimeout [as _onTimeout] (test\promise-spec.js:24:17)
Tried like this, still fail
promise
.then(() => {})
.catch((e) => {
console.log('error caught');
done();
});

Turns out it was because of a previous test that didn't call done, and it throwing an error killed this one

Related

JavaScript: Catching an error thrown in a promise does not work? [duplicate]

What is the best way to handle this scenario. I am in a controlled environment and I don't want to crash.
var Promise = require('bluebird');
function getPromise(){
return new Promise(function(done, reject){
setTimeout(function(){
throw new Error("AJAJAJA");
}, 500);
});
}
var p = getPromise();
p.then(function(){
console.log("Yay");
}).error(function(e){
console.log("Rejected",e);
}).catch(Error, function(e){
console.log("Error",e);
}).catch(function(e){
console.log("Unknown", e);
});
When throwing from within the setTimeout we will always get:
$ node bluebird.js
c:\blp\rplus\bbcode\scratchboard\bluebird.js:6
throw new Error("AJAJAJA");
^
Error: AJAJAJA
at null._onTimeout (c:\blp\rplus\bbcode\scratchboard\bluebird.js:6:23)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
If the throw occurs before the setTimeout then bluebirds catch will pick it up:
var Promise = require('bluebird');
function getPromise(){
return new Promise(function(done, reject){
throw new Error("Oh no!");
setTimeout(function(){
console.log("hihihihi")
}, 500);
});
}
var p = getPromise();
p.then(function(){
console.log("Yay");
}).error(function(e){
console.log("Rejected",e);
}).catch(Error, function(e){
console.log("Error",e);
}).catch(function(e){
console.log("Unknown", e);
});
Results in:
$ node bluebird.js
Error [Error: Oh no!]
Which is great - but how would one handle a rogue async callback of this nature in node or the browser.
Promises are not domains, they will not catch exceptions from asynchronous callbacks. You just can't do that.
Promises do however catch exceptions that are thrown from within a then / catch / Promise constructor callback. So use
function getPromise(){
return new Promise(function(done, reject){
setTimeout(done, 500);
}).then(function() {
console.log("hihihihi");
throw new Error("Oh no!");
});
}
(or just Promise.delay) to get the desired behaviour. Never throw in custom (non-promise) async callbacks, always reject the surrounding promise. Use try-catch if it really needs to be.
After dealing with the same scenario and needs you are describing, i've discovered zone.js , an amazing javascript library , used in multiple frameworks (Angular is one of them), that allows us to handle those scenarios in a very elegant way.
A Zone is an execution context that persists across async tasks. You can think of it as thread-local storage for JavaScript VMs
Using your example code :
import 'zone.js'
function getPromise(){
return new Promise(function(done, reject){
setTimeout(function(){
throw new Error("AJAJAJA");
}, 500);
});
}
Zone.current
.fork({
name: 'your-zone-name',
onHandleError: function(parent, current, target, error) {
// handle the error
console.log(error.message) // --> 'AJAJAJA'
// and return false to prevent it to be re-thrown
return false
}
})
.runGuarded(async () => {
await getPromise()
})
Thank #Bergi. Now i know promise does not catch error in async callback. Here is my 3 examples i have tested.
Note: After call reject, function will continue running.
Example 1: reject, then throw error in promise constructor callback
Example 2: reject, then throw error in setTimeout async callback
Example 3: reject, then return in setTimeout async callback to avoid crashing
// Caught
// only error 1 is sent
// error 2 is reached but not send reject again
new Promise((resolve, reject) => {
reject("error 1"); // Send reject
console.log("Continue"); // Print
throw new Error("error 2"); // Nothing happen
})
.then(() => {})
.catch(err => {
console.log("Error", err);
});
// Uncaught
// error due to throw new Error() in setTimeout async callback
// solution: return after reject
new Promise((resolve, reject) => {
setTimeout(() => {
reject("error 1"); // Send reject
console.log("Continue"); // Print
throw new Error("error 2"); // Did run and cause Uncaught error
}, 0);
})
.then(data => {})
.catch(err => {
console.log("Error", err);
});
// Caught
// Only error 1 is sent
// error 2 cannot be reached but can cause potential uncaught error if err = null
new Promise((resolve, reject) => {
setTimeout(() => {
const err = "error 1";
if (err) {
reject(err); // Send reject
console.log("Continue"); // Did print
return;
}
throw new Error("error 2"); // Potential Uncaught error if err = null
}, 0);
})
.then(data => {})
.catch(err => {
console.log("Error", err);
});

Expected one assertion to be called but received zero assertion calls

I am trying to test a method using Jest... The method should return Promise.reject() .
Here is the code I wrote:
test('testing Invalid Response Type', () => {
const client = new DataClient();
client.getSomeData().then(response => {
console.log("We got data: "+ response);
}).catch(e => {
console.log("in catch");
expect(e).toBeInstanceOf(IncorrectResponseTypeError);
});
expect.assertions(1);
});
When I run the test, it prints "in catch" but fails with this exception:
Expected one assertion to be called but received zero assertion calls.
console.log src/data/dataclient.test.js:25
in catch
● testing Invalid Response Type
expect.assertions(1)
Expected one assertion to be called but received zero assertion calls.
at extractExpectedAssertionsErrors (node_modules/expect/build/extract_expected_assertions_errors.js:37:19)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
I solved it by adding return statement before the block.
With return statement the function will wait for catch block to finish.. and hence expect will be executed..
test('testing Invalid Response Type', () => {
const client = new DataClient();
return client.getSomeData().then(response => {
console.log("We got data: "+ response);
}).catch(e => {
console.log("in catch");
expect(e).toBeInstanceOf(IncorrectResponseTypeError);
});
expect.assertions(1);
});
You need to wait for the promise to finish to check number of assertions (to reach the .catch block).
see jest's asynchronous tutorial, specially the async/await solution. Actually, their example is almost identical to your problem.
in your example, you would do:
test('testing Invalid Response Type', async () => { // <-- making your test async!
const client = new DataClient();
await client.getSomeData().then(response => { // <-- await for your function to finish
console.log("We got data: "+ response);
}).catch(e => {
console.log("in catch");
expect(e).toBeInstanceOf(IncorrectResponseTypeError);
});
expect.assertions(1);
});
Btw, the accepted solution also works, but not suitable to multiple tests of async code

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

So, I'm testing a component that relies on an event-emitter. To do so I came up with a solution using Promises with Mocha+Chai:
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();
});
});
On the console I'm getting an 'UnhandledPromiseRejectionWarning' even though the reject function is getting called since it instantly shows the message 'AssertionError: Promise error'
(node:25754) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 2): AssertionError: Promise error: expected
{ Object (message, showDiff, ...) } to be falsy
should transition with the correct event
And then, after 2 sec I get
Error: timeout of 2000ms exceeded. Ensure the done() callback is
being called in this test.
Which is even weirder since the catch callback was executed(I think that for some reason the assert failure prevented the rest of the execution)
Now the funny thing, if I comment out the assert.isNotOk(error...) the test runs fine without any warning in the console. It stills 'fails' in the sense that it executes the catch.
But still, I can't understand these errors with promise. Can someone enlighten me?
The issue is caused by this:
.catch((error) => {
assert.isNotOk(error,'Promise error');
done();
});
If the assertion fails, it will throw an error. This error will cause done() never to get called, because the code errored out before it. That's what causes the timeout.
The "Unhandled promise rejection" is also caused by the failed assertion, because if an error is thrown in a catch() handler, and there isn't a subsequent catch() handler, the error will get swallowed (as explained in this article). The UnhandledPromiseRejectionWarning warning is alerting you to this fact.
In general, if you want to test promise-based code in Mocha, you should rely on the fact that Mocha itself can handle promises already. You shouldn't use done(), but instead, return a promise from your test. Mocha will then catch any errors itself.
Like this:
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');
});
});
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 */ });
I got this error when stubbing with sinon.
The fix is to use npm package sinon-as-promised when resolving or rejecting promises with stubs.
Instead of ...
sinon.stub(Database, 'connect').returns(Promise.reject( Error('oops') ))
Use ...
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.
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
}
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 had a similar experience with Chai-Webdriver for Selenium.
I added await to the assertion and it fixed the issue:
Example using Cucumberjs:
Then(/I see heading with the text of Tasks/, async function() {
await chai.expect('h1').dom.to.contain.text('Tasks');
});
Just a heads-up that you can get a UnhandledPromiseRejectionWarning if you accidentally put your test code outside of the it-function. 😬
describe('My Test', () => {
context('My Context', () => {
it('should test something', () => {})
const result = testSomething()
assert.isOk(result)
})
})

Making assertions with catch in promises exceeds timeout

I want to make an assertion in a catch block of a promise chain, but it reaches the timeout. Assertions work in then blocks, but it seems in the catch block, done() is never reached. Is it being suppressed? Is there a better way to test promise rejections?
import assert from 'assert';
import { apicall } from '../lib/remoteapi';
describe('API calls', function () {
it('should test remote api calls', function (done) {
apicall([])
.then((data) => {
assert.equal(data.items.length, 2); // this works fine
done();
})
.catch((e) => {
console.log('e', e);
assert.equal(e, 'empty array'); // ?
done(); // not reached?
});
});
});
The promise rejection
apicall(channelIds) {
if(channelIds.length === 0) return Promise.reject('empty array');
...
}
I get this error:
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
If this is mocha and you're using Promises, don't use the callback functionality; it makes things very awkward as you're discovering. Instead, mocha lets you return the promise in your test. A rejected Promise means a failed test, and a successful Promise means a succeeding test. A failed assertion causes the code to throw an exception, which will automatically fail the Promise, which is usually what you'll want. In short:
describe('API calls', function () {
it('should test remote api calls', function () {
return apicall([])
.then((data) => {
assert.equal(data.items.length, 2);
});
});
});

Promise reject error - Unhandled rejection Error: closed

I use the following code to check some app port currenlty its working but I got error in the third else statement
Unhandled rejection Error: Port is not open
How can I handle that ?
I use bluebird
checkPortStatus: function(port, host){
return new Promise((resolve, reject) => {
portscanner.checkPortStatus(port, host, function(error, status) {
if(error)
reject(error);
else if(status === 'open')
resolve(status);
else
reject(new Error('Port is not open'));
});
});
},
Eventually, you need to handle rejected promises, for instance using a .catch():
obj.checkPortStatus(port, host).then((status) => {
...
}).catch((err) => {
// handle the error here...
});
Attributes of the code calling checkPortStatus cause the unhandled exception.
That code might look like
somePromiseFunction()
.then(checkPortStatus(port, host))
.then(someOtherPromiseFunction())
It would (minimally) "handle" the exception if it looked more like
somePromiseFunction()
.then(checkPortStatus(port, host))
.catch(function(error) {
console.log(error.message);
})
.then(someOtherPromiseFunction()
There's trouble in your code in this aspect: When using resolve and reject, it's also necessary to use return. So instead of resolve(), use return resolve(); same with reject.
A side note, in case it helps: Once you add the returns I mention, each of the else statements in your code is immediately preceded by a return. You can delete the else statements.
Good luck!

Categories