-
-
Notifications
You must be signed in to change notification settings - Fork 469
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
server.use()
or server.resetHandlers
do not appear to be working within/between tests
#251
Comments
By @mwarger thanks for opening this issue :) Have you tried to understand if you have something not clean before each test? I think that a reproduction case could help a lot Thanks for using MSW 🎊 |
I've been running into the same issue as well. Let me try and make a reproduction. |
Hey! Thanks for reaching out with this. Let me share some insights on what may help in triaging this issue. Ensure single server instanceThe list of request handlers ( // src/handlers.js
import { rest } from 'msw'
export const handlers = [
rest.get('myUrl', (req, res, ctx) => res(ctx.json({ a: 1 }))
] // src/mocks/server.js
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
export const setupServer(...handlers) // src/setupTests.js
import { server } from './mocks/server'
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close()) // test/MyComponent.test.js
// Reference the same instance created in `mocks/server.js`
import { server } from '../src/mocks/server'
test('regular', () => {})
test('override', () => {
server.use(...)
}) IsolateIsolating a single test to fix an issue is usually a sign of shared state between tests. Apart from the list of request handlers, there may be other state at place, which we can find out. What I'd usually to is Please, try to set up a minimal reproduction scenario/repository, so we could take a look. Thank you. |
Reproduction project here: https://github.com/roy-dendro/msw You can run You can see in https://github.com/roy-dendro/msw/blob/master/index.spec.js#L23 that i add a console.log in the overwrite graphql call, but its never called. In the second test, where it supposed to return an error from the msw, it renders as normally with the handler defined in |
Please see the reproduction above. Like you mentioned, when skipping the first Any idea what could cause that? |
Thanks for getting back at such a short notice. We'll checkout your reproduction repository and let you know on any technical insights we find. Stay tunned. |
Hi @roy-dendro I think that
|
Unfortunately i don't think that that's the issue. Setting a |
I have tried as above and it works. Let me know if I'm wrong
|
That indeed seems to be working, sorry for disregarding your solution so soon in my previous reply. Setting the fetchPolicy to network-only didn't resolve it, which confuses me at the moment. Also when trying to reproduce in the browers with multiple ApolloProviders i'm not getting shared cache. I will look into it some more next week, I don't have time at the moment to look into it :) thanks for your help. |
it's not a problem :) the important thing is that the problem is solved. We are here trying to help other and make others help us 😄 |
This ended up being a cache issue. I was using SWR for the tests in question and I needed to add cache clearing and deduping to fix it. Thank you for walking through the issues to consider, and thanks for @roy-dendro for the reproduction and jogging my mind that I needed to think about the cache! Here's what I ended up doing that solved it: vercel/swr#231 (comment) I appreciate your help and quick response. |
This bit me as well. Thank you for the solution. I imagine using Apollo Client is pretty common with |
For anyone coming to this who is using react-query. You will need to add
|
We should really create an FAQ point mentioning cache invalidation for such request clients. |
References this suggestion in this FAQ section. |
@kettanaito @philals @dgurns @marcosvega91 @roy-dendro I'm unable to use two server.use() get API success call instances
Here I'm conditionally unordered rendering list item or a select field depending on the items being returned in the GET API endpoint, but I'm unable to use the response in two different describe blocks, mock server just renders the whichever block is written first instead of running both the API Step1.test.js
server.js
handlers.js
|
Hey, @vaibhav-systango. Id' advise calling Otherwise, I'd kindly ask you to prepare a reproduction repository for your issue so I'd be able to help you. |
I'm seeing a similar issue recently. I have 2 tests in a file ( A and B ), the first test uses the standard handlers (no server.use) , the second uses a
We have this configuration for our project as well: beforeAll(() => {
// Enable the mocking in tests.
server.listen();
});
afterEach(() => {
// Reset any runtime handlers tests may use.
server.resetHandlers();
});
afterAll(() => {
// Clean up once the tests are done.
server.close();
}); |
I went about creating a repro repository...and of course...it works. There is something about our setup that is wrong. Disregard above. |
Hi, I'd like to add to this, because just like @nicholascm, I've encountered the error and created a repo... where it didn't happen. However I did go through with more testing, and I was able to reproduce a case which I cannot explain right now. https://github.com/MrGuiMan/msw-handler-override here you can see that the test that overrides mygraphql query doesn't work. @kettanaito any insight would be very appreciated. Thanks |
Alright, brand new day, and I found a solution that I'm okay with. This -> vercel/swr#781 is what actually helped me. It turns out waiting on the cache reset seems to be necessary
I think it's worth a mention in the FAQ section regarding caching ? |
I cant tell you folks how long it took me to get through this bug. Your soultion(s) did it. Thanks much! |
It's in the type definitions public abstract reset(options?: Cache.ResetOptions): Promise<void>; |
The api from react query requires you to define a "new" cache in entry point. How do you reset it in every test iteration? |
Just export the beforeEach(() => {
queryClient.clear();
}); Worked for me. Or, make sure to use it('should do something', async () => {
queryClient.clear();
server.use(
rest.get('/some/endpoint', (_req, res, ctx) => {
return res.once(ctx.json({ data: 'updated data' }));
}),
);
render(<Component />);
// Your tests that use the updated data
}); Hope this helps others, struggled with this for too long :') |
I was strugglin with this in relation to RTK query. Indeed, the cached requests were my problem, too. This thread helped me ro realize that. The solution for RTK query is to do
between my tests |
If you are using const queryClient = new QueryClient({
defaultOptions: { queries: { cacheTime: 0 } },
}) |
Describe the bug
server.use()
orserver.resetHandlers
do not appear to be working within tests.I have a
setupTests
file that is appropriately callingresetHandlers
(confirmed with logging) after each test.When using a
server.use
statement to override a route payload like so:I would expect the result to return as an empty array. My main handlers file is setup similarly:
When running all my tests, I see my mock data, and can log it to the console in the actual component implementation.
When running as part of a test suite, I do not get the overridden empty array that I want, I see the original list from the handlers.
The bug I think I've found is that if I run the test as
it.only
then I see the correct empty array and my test passes. My component logs out the empty array as the fetched data I was expecting. Running the tests completely by itself seems to fix the issue.I'm hoping this is just a silly mistake on my part.
Environment
msw: 0.19.5
nodejs: 12.16.1
npm: 6.13.4
To Reproduce
Steps to reproduce the behavior:
I attempted to reproduce this behavior using the react example project, but haven't been able to yet.
Expected behavior
I have a
setupTests
file that is appropriately callingresetHandlers
(confirmed with logging) after each test. When usingserver.use
to setup a route override, I should get the payload assigned (as one would expect from the docs as well as the example project.The text was updated successfully, but these errors were encountered: