So based off Cypress request docs: https://docs.cypress.io/api/commands/request.html
It seems like I should be able to send a POST request with a JSON body pretty easily. So this is what I tried:
cy.fixture('test_create').as('create_test')
cy.request({
method: 'POST',
url: 'http://localhost:8080/widgets',
body: '@create_test',
headers: {
'Authorization': this.token,
'Content-Type': 'application/json;charset=UTF-8'
}
})
However when I look at the "commands" Cypress sends, it's sending the body as literally Body: @create_test
Is it not possible to use a fixture within the body of a POST request? I confirmed the fixture is loading correctly. I confirmed also it works when I paste the entire JSON inside of the body
option....but that gets ugly really quick with large JSON bodys.
You get a literal because in the form cy.request(options)
, options is a plain JS object and unfortunately not parsed by Cypress to interpret the alias.
The request form cy.request(method, url, body)
probably does allow an alias for the body param, since cy.route()
allows it ref: Accessing Fixture Data
e.g the following should be valid, but does not allow setting headers
cy.fixture('test_create').as('create_test')
cy.request('POST', 'http://localhost:8080/widgets', '@create_test');
So, you can use then()
cy.fixture('test_create').then(myFixture => {
cy.request({
method: 'POST',
url: 'http://localhost:8080/widgets',
body: myFixture,
headers: {
'Authorization': this.token,
'Content-Type': 'application/json;charset=UTF-8'
}
})
});
or
cy.fixture('test_create').as('create_test');
... // some other code between
cy.get('@create_test').then(myFixture => { // retrieve the fixture from alias
cy.request({
method: 'POST',
url: 'http://localhost:8080/widgets',
body: myFixture,
headers: {
'Authorization': this.token,
'Content-Type': 'application/json;charset=UTF-8'
}
})
})
I ended up having to use
then()
the other thing is thatcy.fixture()
is async. So my thinking was also that usingthis.fixturename
may not have been "read" yet. So by usingthen()
I made sure not to do the request till after the fixture was done loading.I noticed the comment that you already had the answer after I posted, but it's useful for others to see some explicit code.
As for fixture being async, I wonder if that's correct? I understand
cy.fixture()
to be shorthand for 'read this file from the fixtures folder', which does not have to be done async. Note that.then()
looks like a promise then, but it's not really - it just gives you access to the previous command result.Using local variables like
this.fixturename
does work, but is gets tricky becausethis
can change depending on whether you usefunction
styleit()
or arrow functions, so I personally prefer to usethen()
.