Skip to content

Testing a POST with MSW #933

Answered by kettanaito
nareshbhatia asked this question in Q&A
Discussion options

You must be logged in to vote

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…

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by nareshbhatia
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@kettanaito
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants