Last active
May 31, 2019 17:44
-
-
Save cvle/e4496b733889c137e9f19dddf861fdd4 to your computer and use it in GitHub Desktop.
Workaround for Jest Assertions not failing tests in a try/catch block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Jest assertions will not fail if they live inside a try-catch block due to | |
// https://github.com/facebook/jest/issues/3917. | |
// This file returns a version of `expect` that fails | |
// the test immediately when an exception is thrown. | |
/** | |
* isPromise detects whether given object is a promise or not. | |
*/ | |
const isPromise = obj => | |
!!obj && | |
(typeof obj === "object" || typeof obj === "function") && | |
typeof obj.then === "function"; | |
/** | |
* Wrap a jest matcher so if the expectation fails, it also fails the test. | |
* @param func the jest matcher that will be wrapped. | |
*/ | |
const wrapMatcher = func => { | |
const wrappedMatcher = {}; | |
const keys = Object.keys(func); | |
keys.forEach(k => { | |
if (typeof func[k] === "function") { | |
wrappedMatcher[k] = (...args) => { | |
try { | |
const result = func[k](...args); | |
if (isPromise(result)) { | |
return result.then(undefined, e => { | |
// Remove this function from stacktrace. | |
Error.captureStackTrace(e, wrappedMatcher[k]); | |
fail(e); | |
throw e; | |
}); | |
} | |
return result; | |
} catch (e) { | |
// Remove this function from stacktrace. | |
Error.captureStackTrace(e, wrappedMatcher[k]); | |
fail(e); | |
throw e; | |
} | |
}; | |
} else { | |
// This should be `not`, `resolves`, and `rejects`. | |
wrappedMatcher[k] = wrapMatcher(func[k]); | |
} | |
}); | |
return wrappedMatcher; | |
}; | |
const originalExpect = global.expect; | |
const expectAndFail = (...args) => { | |
const matcher = originalExpect(...args); | |
return wrapMatcher(matcher); | |
}; | |
export default expectAndFail; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment