Skip to content

Commit

Permalink
fix: avoid unhandled promise rejection in latest nodejs
Browse files Browse the repository at this point in the history
  • Loading branch information
3cp committed May 8, 2021
1 parent 23878f1 commit ed48502
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
9 changes: 5 additions & 4 deletions lib/bypass.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ exports = module.exports = function bypass(fn) {
let result;
try {
result = fn();
} finally {
if (result && typeof result.then === 'function') {
result.then(
return result.then(
r => {
enable();
return r;
Expand All @@ -32,10 +31,12 @@ exports = module.exports = function bypass(fn) {
);
} else {
enable();
return result;
}
} catch (err) {
enable();
throw err;
}

return result;
};

/**
Expand Down
18 changes: 7 additions & 11 deletions test/lib/bypass.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,8 @@ describe('mock.bypass()', () => {
assert.equal(fs.readFileSync('/path/to/file', 'utf8'), 'content');
assert.isFalse(fs.existsSync(__filename));

const promise = mock.bypass(() => fs.promises.stat(__filename));
assert.instanceOf(promise, Promise);

promise
mock
.bypass(() => fs.promises.stat(__filename))
.then(stat => {
assert.isTrue(stat.isFile());
assert.isFalse(fs.existsSync(__filename));
Expand All @@ -84,13 +82,11 @@ describe('mock.bypass()', () => {

const error = new Error('oops');

const promise = mock.bypass(() => {
assert.isTrue(fs.existsSync(__filename));
return Promise.reject(error);
});
assert.instanceOf(promise, Promise);

promise
mock
.bypass(() => {
assert.isTrue(fs.existsSync(__filename));
return Promise.reject(error);
})
.then(() => {
done(new Error('should not succeed'));
})
Expand Down

0 comments on commit ed48502

Please # to comment.