Warm tip: This article is reproduced from stackoverflow.com, please click
cypress

Cypress using JSON fixture in body?

发布于 2020-04-16 11:55:12

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.

Questioner
msmith1114
Viewed
70
Marion Morrison 2020-02-04 16:29

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