@@ -87,6 +87,60 @@ context('Network Requests', () => {
8787 } )
8888 } )
8989
90+ it ( 'cy.request() - pass result to the second request' , ( ) => {
91+ // first, let's find out the userId of the first user we have
92+ cy . request ( 'https://jsonplaceholder.cypress.io/users?_limit=1' )
93+ . its ( 'body.0' ) // yields the first element of the returned list
94+ . then ( ( user ) => {
95+ expect ( user ) . property ( 'id' ) . to . be . a ( 'number' )
96+ // make a new post on behalf of the user
97+ cy . request ( 'POST' , 'https://jsonplaceholder.cypress.io/posts' , {
98+ userId : user . id ,
99+ title : 'Cypress Test Runner' ,
100+ body : 'Fast, easy and reliable testing for anything that runs in a browser.' ,
101+ } )
102+ } )
103+ // note that the value here is the returned value of the 2nd request
104+ // which is the new post object
105+ . then ( ( response ) => {
106+ expect ( response ) . property ( 'status' ) . to . equal ( 201 ) // new entity created
107+ expect ( response ) . property ( 'body' ) . to . contain ( {
108+ id : 101 , // there are already 100 posts, so new entity gets id 101
109+ title : 'Cypress Test Runner' ,
110+ } )
111+ // we don't know the user id here - since it was in above closure
112+ // so in this test just confirm that the property is there
113+ expect ( response . body ) . property ( 'userId' ) . to . be . a ( 'number' )
114+ } )
115+ } )
116+
117+ it ( 'cy.request() - save response in the shared test context' , ( ) => {
118+ // https://on.cypress.io/variables-and-aliases
119+ cy . request ( 'https://jsonplaceholder.cypress.io/users?_limit=1' )
120+ . its ( 'body.0' ) // yields the first element of the returned list
121+ . as ( 'user' ) // saves the object in the test context
122+ . then ( function ( ) {
123+ // NOTE 👀
124+ // By the time this callback runs the "as('user')" command
125+ // has saved the user object in the test context.
126+ // To access the test context we need to use
127+ // the "function () { ... }" callback form,
128+ // otherwise "this" points at a wrong or undefined object!
129+ cy . request ( 'POST' , 'https://jsonplaceholder.cypress.io/posts' , {
130+ userId : this . user . id ,
131+ title : 'Cypress Test Runner' ,
132+ body : 'Fast, easy and reliable testing for anything that runs in a browser.' ,
133+ } )
134+ . its ( 'body' ) . as ( 'post' ) // save the new post from the response
135+ } )
136+ . then ( function ( ) {
137+ // When this callback runs, both "cy.request" API commands have finished
138+ // and the test context has "user" and "post" objects set.
139+ // Let's verify them.
140+ expect ( this . post , 'post has the right user id' ) . property ( 'userId' ) . to . equal ( this . user . id )
141+ } )
142+ } )
143+
90144 it ( 'cy.route() - route responses to matching requests' , ( ) => {
91145 // https://on.cypress.io/route
92146
0 commit comments