Reputation: 784
How do I test if a async function is throwing an error in a specific condition when I don't have access to a reference for the instance of that promise?
const fakeRequest = Promise.reject();
function Component() {
const click = async () => {
await fakeRequest()
.then(doStuff)
.catch(error => {
if (error.foo === true) {
throw new Error('Error') // how do I test this?
}
return 'fallback';
});
};
return (
<button onClick={click}>hi</button>
);
}
test('test', () => {
render(<Component>)
userEvent.click(screen.getByRole('button'))
// ??
await flushPromises()
expect().throwError()
})
Upvotes: 1
Views: 1839
Reputation: 3714
React-testing-library promotes to "test like a real user would", leaving the internal implementation. Following this principle, you should always trigger user interaction, and assert on visual things (or things that a real human would experience).
https://testing-library.com/docs/guiding-principles
Your component "visual output" is not affected by the result of the request you make, so there is nothing to test if you want to stick with RTL mindset. In fact, you are trying to test internal implementation here, and this is precisely what RTL tries to avoid.
If you modifiy your component and make it display some kind of success/error message, then you can test that a promise rejection triggers the error message.
Upvotes: 1