test failed with msw, but works with other mock server library #915
-
Environment
Request handlersimport { setupServer } from 'msw/node'
import { rest } from 'msw'
const server = setupServer(
rest.get('/v1/check-rsa', (req, res, ctx) => {return res(ctx.status(200), ctx.json({ rsa_key: '' }))}),
rest.post('/v1/auth', (req, res, ctx) => { return res(ctx.status(400), ctx.json({ error: 'invalid user' }))})
)
beforeAll(() => server.listen({ onUnhandledRequest: 'warn' }))
beforeEach(() => server.resetHandlers())
beforeAll(() => server.close())
describe('[LoginForm]', () => {
it('Login will be failed with invalid user info', () => {
fireEvent.change(screen.getByTestId('id'), {
target: { value: 'test_id' },
})
fireEvent.change(screen.getByTestId('pw'), {
target: { value: 'test_pw' },
})
const button = screen.getByTestId('submit')
fireEvent.click(button)
await waitFor(() => {
expect(screen.getByText(invalidInfo)).toBeInTheDocument()
})
})
}) Actual requestconst { data: { rsa_key } } = await axios.get('/v1/check-rsa')
if (rsa_key) {
// ...
}
return await axios.post('/v1/auth', {
id,
pw,
}) Current behaviorWhen the login button is clicked, send two requests sequentially: GET and POST. And the test ends with Network Error. Below is an example of a code using an import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
const mockServer = new MockAdapter(axios)
mockServer
.onGet('/v1/check-rsa')
.reply(200, { rsa_key: '' })
.onPost('/v1/auth')
.reply(400, { error: 'invalid user' }) Expected behaviorThe test must pass like Screenshots |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Hey, @tofutree23. There are a few issues with your setup that may be causing the behavior you're experiencing.
beforeAll(() => server.listen({ onUnhandledRequest: 'warn' }))
beforeEach(() => server.resetHandlers())
-beforeAll(() => server.close())
+afterAll(() => server.close())
import { BASE_URL } from './my-axios-setup'
const server = setupServer(
rest.get(BASE_URL + '/v1/check-rsa', (req, res, ctx) => {return res(ctx.status(200), ctx.json({ rsa_key: '' }))}),
rest.post(BASE_URL + '/v1/auth', (req, res, ctx) => { return res(ctx.status(400), ctx.json({ error: 'invalid user' }))})
) |
Beta Was this translation helpful? Give feedback.
Hey, @tofutree23.
There are a few issues with your setup that may be causing the behavior you're experiencing.
beforeAll
hooks, where first enables the mocking and the second disables it immediately. I believe you meant to useafterAll
: