How to reach api response in unit test? #1208
Replies: 1 comment 1 reply
-
Hey, @furkanestikDT. When you're mocking a response you're guaranteed to receive the mocked response you specified. API mocking itself takes network calls and turns them into a given—something that's always stable and true. That's why asserting that the response you receive is indeed what you mock is redundant. What you may want to assert is your code (your React component) and how it reacted to the mocked response. In your case, you seem to be filling in a "Forgot password" form. What happens when the user clicks "Submit" on your website? Are they redirected to another page? Is there a callback prop that your Here's an example of such assertion: describe('DefinePassword', () => {
+ const handleSubmit = jest.fn()
beforeEach(() => {
render(
<Provider store={store}>
<BrowserRouter>
+ <DefinePassword onSubmit={handleSubmit} />
</BrowserRouter>
</Provider>
)
})
afterEach(() => {
+ handleSubmit.mockClear()
})
it('is-request-successful', async () => {
const password = screen.getAllByText(/password/i)[0]
const confirmPassword = screen.getAllByText(/confirm password/i)[0]
await user.type(password, 'test', {delay: 1})
await user.type(confirmPassword, 'test', {delay: 1})
await waitFor(() => {
user.click(getFieldByRole('button', /send/i))
})
+ // Await a UI element that represents a 200 OK response.
+ await screen.findByText(/password successfully changed/i)
+ // Check that your component propagates successful password change
+ // via the "onSubmit" prop.
+ expect(onSubmit).toHaveBeenCalledWith({ password: 'test' })
+ expect(onSubmit).toHaveBeenCalledTimes(1)
+ expect(screen.)
})
}) This should give you an idea on how to approach the assertion in your test.
|
Beta Was this translation helpful? Give feedback.
-
Hi, I need to test whether the api response is 200 or not in my react unit test (with testing library). How can I reach the api response status in the test? Below is the example code that might helps.
Beta Was this translation helpful? Give feedback.
All reactions