Hey, @tofutree23.
There are a few issues with your setup that may be causing the behavior you're experiencing.
- Two
beforeAllhooks, where first enables the mocking and the second disables it immediately. I believe you meant to useafterAll:
beforeAll(() => server.listen({ onUnhandledRequest: 'warn' }))
beforeEach(() => server.resetHandlers())
-beforeAll(() => server.close())
+afterAll(() => server.close())
- If you configure Axios with any options that affect request URL (i.e. base URL), make sure you account for those options when declaring handlers. For instance, in the case of base URL, export that URL and prepend it to each handler:
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' }))}) )
When I'm writing tests for my frontend I've generally used axios mock adapter and then manually constructed the mocks that I need for the particular test. However, this can be quite tedious, especially as the test scenarios get complex with more API calls.
Then yesterday I discovered miragejs. I started playing around with it, I like it well enough. It's got some rough edges though, mainly with TS types and some parts of how it's internal DB works. I could probably make use of it though.
All that being said, I've gotten genuinely curious about the more solutions to this problem. I like the mirage approach overall, creating a centralized source of test data that can handle responses to more complex queries and requests. But anyway, I would love to hear suggestions from the community.
Thanks in advance.
test failed with msw, but works with other mock server library
reactjs - How to mock data response using msw and axios.create() instance - Stack Overflow
mock Axios.Create() in unit testing - javascript
Axios never receives mocked response object msw@0.38.1
» npm install axios-mock-adapter
I have a React component called Login. It sends a http post request to a server via the Axios library sending username and password credentials. This allows me to authenticate users on my site. What is the best way to unit test this component using Jest? Should I have the unit test send a network request to the same url with mock data or should I render the Login component and simulate entering data and submitting the form?