-
Notifications
You must be signed in to change notification settings - Fork 232
How to test useReducer dispatch that errors? #43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
If it's catching in the test("throws an error when dispatched with an unknown action type", () => {
expect.assertions(1);
const { result } = renderHook(() => useReducer(reducer, initialState));
const [, dispatch] = result.current;
act(() => {
dispatch({ type: "whaaat" });
});
expect(result.error).toEqual(Error("Unknown action type"));
}); |
Ah.. that makes sense, thank you for the help! |
@mpeyper , is there a way to suppress the console.error message that's coming from ErrorBoundary? This test is passing: it('should throw if the initialVariant does not exist', () => {
const { result } = renderHook(() =>
useProductVariant(dummyProduct, { initialVariant: '2' })
);
expect(result.error.message).toBe(
'There is no variant with the id "2" on the product Dummy Product'
);
}); But I still see this in the console:
I know one option is to create a global |
You may want to take a look at #50 as there was a better way but the switch to |
@good-idea @mpeyper dont know if you still interested in it, but I have different approach to it, by just avoiding the console error to show up in the unit test window.addEventListener('error', (e) => e.preventDefault()); |
You can update the expectation to check for the error message without throwing it : expect(() => act(() => dispatch({ type: 'whaaat' })).toThrow('Unknown action type'); |
What is your question:
How can I test that a reducer dispatch results in an error?
The
renderHook
api returns a result object with anerror
key. The docs state that this is an error that is thrown if the callback function threw an error during rendering. I'm trying to test for an error from a subsequent dispatch, not from the initialrenderHook
call.Dan Abrmaov suggests that with
useReducer
, the default switch case should throw an error: https://twitter.com/dan_abramov/status/1093969005675773954?lang=enWould the best approach be to render the test by wrapping it in an
ErrorBoundary
type component and testing for the resulting render?As it stands, I get the following reported, just not sure how to catch/handle it in my test.
The text was updated successfully, but these errors were encountered: