Testing a POST with MSW #933
-
I have mostly seen examples of testing a GET with MSW. Seems very natural because the component I am testing renders itself based on the response and I can check for expected elements. However, how do I test a component that is doing a POST and does not change itself. Here's an example of an eCommerce app that shows a product catalog on the left and the shopping cart on the right. I am trying to unit test the product catalog on the left. Clicking on a product send a POST call to the server, which adds the product to the cart. The shopping cart component on the right shows the newly added product, but the product catalog on the left has no change whatsoever. So how do I unit test the product catalog all by itself? Is there a way to "mock" the POST call at the MSW level and make sure that it is called? The only other way I can think of is to test both components together, but that starts to look like a large integration test. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Hey, @nareshbhatia. You can mock POST, or any other REST API requests with MSW the same way you do GET requests. rest.post('/cart', (req, res, ctx) => {
// return your mocked response
}) Then, I suggest reading about request assertions, and if you absolutely can't assert the UI in any other way, use life-cycle events API to check that a certain request was made. On the unit test level it may be enough to just ensure the response resolver was called, ignoring the mocked response it returns (unless your UI has some special response handling, such as 4xx/5xx responses). const resolver = jest.fn()
// ...
rest.post('/cart', resolver)
// ...
it('some test', () => {
// render UI
// click on a product
expect(resolver).toHaveBeenCalledTimes(1)
})
|
Beta Was this translation helpful? Give feedback.
-
This is perfect for my use case. Thank you so much, @kettanaito for your help. |
Beta Was this translation helpful? Give feedback.
-
@kettanaito i wonder what you think about solving this issue through payload validation on the handler side, in a similar way it would happen on the server. so if the payload is meant to be a JSON then use something like Zod to create the expected schema and validate against it. Then we only need to check that the response is not 400+ or 500+ ? does this miss with any motives or principles for using msw? |
Beta Was this translation helpful? Give feedback.
Hey, @nareshbhatia.
You can mock POST, or any other REST API requests with MSW the same way you do GET requests.
Then, I suggest reading about request assertions, and if you absolutely can't assert the UI in any other way, use life-cycle events API to check that a certain request was made.
On the unit test level it may be enough to just ensure the response resolver was called, ignoring the mocked response it returns (unless your UI has some special response handling, such as 4xx/5xx responses).