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).to.have.property("foo").and.be.a("array");
30
expect(req.request.body).to.have.property("hello").and.be.a("string");
31
32
/**
33
* You can run assertions on any fields
34
*/
35
expect(req.request.body.foo).to.have.members(["bar", "baz"]);
36
expect(req.request.body.hello).to.equal("world");
37
});
38
39
/**
40
* This won't be checked until the @submitPOST request has resoilved
41
*/
42
cy.get('[data-testid="foobar"]');
43
});