I'd like to be able to write a passing test that verifies that when I fireEvent, an error is thrown. This test fails before it reaches the expect:
test('error is thrown', async () => {
const { getByText } = render(<TodoApp />)
await waitForDomChange();
fireEvent.click(getByText('Add todo'));
// test fails during this line
await waitForDomChange();
expect(1).toBeTruthy();
})
I'd like something to the effect of:
test('error is thrown', async () => {
const { getByText } = render(<TodoApp />)
await waitForDomChange();
fireEvent.click(getByText('Add todo'));
expect(await waitForDomChange()).toThrow();
})
Adding an <ErrorBoundary> and testing both components together.
@lorensr,
First, I'll mention that waitForDomChange is deprecated and can be replaced by waitFor(() => {}) (keep in mind that an empty callback like that is also not recommended).
Secondly, I don't think that this is possible. To be able to catch an error, we have to have our own try/catch around it which we do not.
Your alternative is solid and that's what I'd recommend you do. Wrap it in an error boundary.
Thanks!
we have to have our own try/catch around it which we do not.
Is adding a try/catch inside RTL a possibility? I think it would be easier for me than wrapping in error boundary, and being able to test without the boundary component allows for better isolation. I've also found a few issues & SO questions that seem to be searching for the same thing I am.
Is adding a try/catch inside RTL a possibility?
I'm not sure where we would put it for it to be effective 馃
I think it would be easier for me than wrapping in error boundary
I'm not sure why.
import {ErrorBoundary} from 'react-error-boundary'
test('error is thrown', async () => {
const fallbackRender = jest.fn(() => null)
render(
<ErrorBoundary fallbackRender={fallbackRender}>
<TodoApp />
</ErrorBoundary>
)
fireEvent.click(await screen.findByText('Add todo'));
await waitFor(() => expect(fallbackRender).toHaveBeenCalled())
expect(fallbackRender.mock.calls[0].error).toMatchInlineSnapshot(/* jest will update this */)
})
Pretty sure that will work. That's how I would test it if it were me.
One other thing to consider is that it's unlikely this is desireable behavior. I'm not sure I understand the use case of expecting an error to occur in application code. I can understand it in library code though, and in this situation, this is how I'd go about it.
Most helpful comment
I'm not sure where we would put it for it to be effective 馃
I'm not sure why.
Pretty sure that will work. That's how I would test it if it were me.