-
I don't mean server.use() at the start of a test, I mean, for example, use the default server with it's handlers for a first search and then on a second search use the next handler. Here's an example: Line 55 makes a search with the default handlers, line 65 would theoretically "change" the handlers, if possible. The reason I need to do this is because when I make a new search I can't see if it is a new response, because the responses are identical (same array). I hope this makes sense |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Hey, @jordanss1. The Here's an example of changing the network behavior mid-test: import { rest } from 'msw'
import { setupServer } from 'msw/node'
const server = setupServer(
rest.post('/search', (req, res, ctx) => {
// Let's return no search results by default.
return res(ctx.json([]))
})
)
beforeAll(() => server.listen())
// Make sure to reset the handlers after each test
// so that handlers you prepend via "server.use()"
// do not persist between tests.
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
it('displays new search results', async () => {
// Making the initial search attempt.
// The default request handler for POST /search
// is handling this so we get no search results.
await renderApp()
const results =await search('porcelain')
expect(results).toEqual([])
// Here, let's change the response to POST /search
// to return a list of search results.
server.use(
rest.post('/search', (req, res, ctx) => {
return res(ctx.json([
{ title: 'Porcelain' },
{ title: 'Porcelain: A Memoir'}
]))
})
)
const newResults = await search('porcelain')
expect(newResults).toEqual([
{ title: 'Porcelain' },
{ title: 'Porcelain: A Memoir'}
])
}) |
Beta Was this translation helpful? Give feedback.
-
I figured it out after a week, it was my own implementation issue, nothing to do with MSW. I didn't realize sessionStorage was affecting my test environment which I use in the regular application. I added sessionStorage.clear() to the setupTests file to clean the sessionStorage after each test. This can be closed/answered. |
Beta Was this translation helpful? Give feedback.
I figured it out after a week, it was my own implementation issue, nothing to do with MSW.
I didn't realize sessionStorage was affecting my test environment which I use in the regular application. I added sessionStorage.clear() to the setupTests file to clean the sessionStorage after each test.
This can be closed/answered.