赛普拉斯在体内使用JSON夹具?

时间:2020-02-04 04:49:32

标签: cypress

因此基于赛普拉斯请求文档:https://docs.cypress.io/api/commands/request.html

似乎我应该能够轻松发送带有JSON正文的POST请求。这就是我尝试过的:

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

但是,当我查看赛普拉斯发送的“命令”时,它实际上是按照Body: @create_test

的形式发送正文。

是否无法在POST请求的正文中使用固定装置?我确认固定装置已正确加载。我确认,当我将整个JSON粘贴到body选项中时,它也可以工作....但是使用大型JSON正文时,这确实非常难看。

1 个答案:

答案 0 :(得分:2)

之所以得到文字,是因为cy.request(options)形式的options是一个普通的JS对象,不幸的是,赛普拉斯没有对其进行解析以解释该别名。

由于cy.request(method, url, body)允许ref: Accessing Fixture Data

,因此请求表格cy.route()可能确实允许为主体参数使用别名。

例如以下内容应有效,但不允许设置标题

cy.fixture('test_create').as('create_test')
cy.request('POST', 'http://localhost:8080/widgets', '@create_test');

因此,您可以使用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'
    }
  })
});

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