'javascript async/await catch block trapping error instead of mocha
There is a mocha test as follows:
it('(t4) should assert that issues a GET request by john should fetch his own records via svc1', done => {
let filter = { where: { key: 'john' }};
let testHelperUrl = `${svc1}/api/TestHelper?filter=${encodeURIComponent(JSON.stringify(filter))}`;
let fetchToken = cb => {
req('GET', testHelperUrl, (err, resp) => {
if(err) {
return cb(err);
}
cb(null, resp.data[0]);
});
};
let getWithToken = ({ value: token }, cb) => {
let consumerUrl = `${svc1}/api/Consumers?access_token=${token}`;
req('GET', consumerUrl, (err, resp) => {
if(err) {
return cb(err);
}
cb(null, resp.data);
})
};
async.seq(fetchToken, getWithToken)((err, data) => {
if(err) {
return done(err);
}
expect(data.length).to.equal(2);
done();
});
});
It calls some APIs via the req(), and, it is defined as follows:
const req = (method, url, data, cb) => {
if (method.toLowerCase() === 'get') {
if (typeof cb === 'undefined') {
cb = data;
data = null;
}
(async () => {
try {
let response = await got(url, { responseType: 'json', https: { rejectUnauthorized: false } });
cb(null, { code: response.statusCode, data: response.body });
} catch (err) {
cb(err);
}
})();
}
else {
(async () => {
try {
let response = await got.post(url, { json: data, responseType: 'json', https: { rejectUnauthorized: false } });
cb(null, { code: response.statusCode, data: response.body });
} catch (err) {
cb(err);
}
})();
}
};
The above code uses got for doing http requests. Its design is promised-based, and hence, the reason to why async/await pattern is used here.
I am also using the async library here. The following line: expect(data.length).to.equal(2) should fail, and, the expectation is that mocha should report that error correctly.
However, the error is actually trapped by the async library. It should report an error saying callback already was called. But instead the program just dies. However, through debugging I am able to confirm that it was an error trapped in the async module. No idea why it dies abruptly though.
Am I doing something wrong? Or should I modify mocha code to properly handle the assertion error like wrapping that in a try/catch block or something?
Update:
Solution is to invoke the callback function to req() inside of a process.nextTick(). E.g.
try {
let response = await got(url, { responseType: 'json', https: { rejectUnauthorized: false } });
process.nextTick(() => cb(null, { code: response.statusCode, data: response.body }));
} catch (err) {
process.nextTick(() => cb(err));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
