In my development code, I am utilizing Promise.prototype.finally() (or try-catch-finally in an async function) to run additional code without altering the resolution or rejection status of the current promise.
However, when it comes to testing with Jest, I want to specifically check if the Promise within the finally block was not rejected.
edit: The catch section of my "production" code is where I handle errors, so I'm only concerned about re-thrown errors from there and not from finally.
Is there a way to test this? Or perhaps mock the Promise.prototype to reject the current promise upon exceptions from finally?
For example, when testing redux action creators like in the following code snippet, the tests pass even though there may be an unhandled Promise rejection warning:
https://codesandbox.io/s/reverent-dijkstra-nbcno?file=/src/index.test.js
test("finally", async () => {
const actions = await dispatchMock(add("forgottenParent", { a: 1 }));
const newState = actions.reduce(reducer, undefined);
expect(newState).toEqual({});
});
const dispatchMock = async thunk => {...};
// ----- simplified "production" code -----
const reducer = (state = {}, action) => state;
const add = parentId => async dispatch => {
dispatch("add start");
try {
await someFetch("someData");
dispatch("add success");
} catch (e) {
dispatch("add failed");
throw e;
} finally {
dispatch(get(parentId)); // tests pass if the promise here is rejected
}
};
const get = id => async dispatch => {
dispatch("get start");
try {
await someFetch(id);
dispatch("get success");
} catch (e) {
dispatch("get failed");
throw e;
}
};
const someFetch = async id => {
if (id === "forgottenParent") {
throw new Error("imagine I forgot to mock this request");
}
Promise.resolve(id);
};