Skip to content
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

rejectWithValue is not invoked when testing the createAsyncThunk action #4302

Open
stasguma opened this issue Mar 25, 2024 · 5 comments
Open

Comments

@stasguma
Copy link

First of all, I understand that it's probably not right place to ask. Anyway, I hope you could help me.

I have a createAsyncThunk with a rejectWithValue that I want to test with jest.

image

My test file looks next. It crashed on the last line because payload is undefined and as you can see in console.log
rejectedWithValue: false.

image
image

How to make it possible to invoke rejectWithValue on a rejected status in jest?

@stasguma
Copy link
Author

stasguma commented Mar 27, 2024

I noticed that If I change mockRejectedValue to mockResolvedValue then rejectWithValue is invoked and I get the action.payload from rejectWithValue, but the problem is that it has requestStatus: fulfilled not rejected

image

@phryneas
Copy link
Member

I honestly don't know if we can help you here, this looks more like you're having problem with jest mocks.

Could I recommend that you use msw instead of mocking axios?

@stasguma
Copy link
Author

I honestly don't know if we can help you here, this looks more like you're having problem with jest mocks.

Could I recommend that you use msw instead of mocking axios?

I'll also move the api to rtk query. Perhaps all together will help.
Thanks for reply.

@stasguma
Copy link
Author

@phryneas Hi, I replaced axios to rtk query, jest to vitest and use MSW. I got a new problem, that not with rejectWithValue at all.
The problem is that this dispatch returns undefined and further code just breaks. MSW intercepts the call properly.

const response = await dispatch(
    sessionApi.endpoints.login.initiate({ username, password })
);

loginThunk.test.ts

image

loginThunk.ts

image

Perhaps you can provide your own vision on how to test code like this. Thank you in advance.

@phryneas
Copy link
Member

Instead of action(dispatch, getState, undefined) maybe calling dispatch(action) might already be enough.

Test it like you would actually use it. With a real state. This mocking will get you nowhere. What guarantees that your mock actually behaves like the store?

Generally, see https://redux.js.org/usage/writing-tests - under "Example App Code" it even shows how to test a slice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants