Cypress: How do I assert against the contents of a window.fetch POST request body?

1.5k Views Asked by At

So say I've got a cypress test with a spy on window.fetch like so:

describe('My test', () => {
beforeEach(() => {
    cy.visit('http://localhost:3000', {
        onBeforeLoad(win) {
            cy.spy(win, 'fetch')
        },
    })

I can assert that POST request has a certain URL like so:

cy.window().its('fetch').should('be.calledWith', 'http://whatever.com/stuff')

but I can't figure out how to assert against the body of that request. How would I assert, for instance, that it contains my_param=10?

Thanks!

2

There are 2 best solutions below

0
On

To extend the answer of @BaronVonKaneHoffen:

There is no need for extra import, you can use the Cypress.sinon.match.

Here is a snippet, for window.open stubbing if somebody would looking for it:

cy.window().then(win => {
    cy.stub(win, 'open').as('open')
})

...

...

cy.get('@open').should('have.been.calledWithMatch', Cypress.sinon.match('expected_value'))

I think for fetch you can steal some ideas from it, too :).

0
On

Nobody eh? Well, if anyone else stumbles across this, I figured it out and here's how you do it:

cy.window().its('fetch').should(
  'be.calledWithMatch', 
  'http://your-url.com/here', 
  sinon.match.has('body', sinon.match('your_param=expected_value')))
  
        

Remember to import sinon as a separate dependency.

You can use this line multiple times to assert against multiple variables.