msmith1114
msmith1114

Reputation: 3229

Cypress using JSON fixture in body?

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.

Upvotes: 5

Views: 7067

Answers (1)

user12697177
user12697177

Reputation:

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'
    }
  })
})

Upvotes: 8

Related Questions