Assert request properties with cypress

Created Jun 11 2020

JS
1
it('Calls the correct endpoint with the expected payload when clicking on submit', () => {
2
cy.server();
3
cy.route({
4
url: 'https://my-awesome-app.com/submit',
5
method: 'POST',
6
}).as('submitPOST');
7
8
/**
9
* Use a data-testid attribute toi target the element we want to click on
10
* Here we want to click the submit button with the data-testid
11
* "submit-button"
12
*/
13
cy.get('[data-testid="submit-button"]').click();
14
15
/**
16
* Wait for the submitPOST request to resolve before moving to the next command
17
*
18
* This will yield an object containing the HTTP request and response properties.
19
*
20
*/
21
cy.wait('@submitPOST').should(req => {
22
/**
23
* You can run any kind of assertions against the request object
24
*/
25
expect(req.method).to.equal('POST');
26
/**
27
* You can check the type of any property
28
*/
29
expect(req.request.body)
30
.to.have.property('foo')
31
.and.be.a('array');
32
expect(req.request.body)
33
.to.have.property('hello')
34
.and.be.a('string');
35
36
/**
37
* You can run assertions on any fields
38
*/
39
expect(req.request.body.foo).to.have.members(['bar', 'baz']);
40
expect(req.request.body.hello).to.equal('world');
41
});
42
43
/**
44
* This won't be checked until the @submitPOST request has resoilved
45
*/
46
cy.get('[data-testid="foobar"]');
47
});