温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Cypress using JSON fixture in body?
cypress

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

发布于 2020-04-16 13:18:29

因此,基于赛普拉斯请求文档: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正文时,这确实非常难看。

查看更多

提问者
msmith1114
被浏览
60
Marion Morrison 2020-02-04 16:29

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

该请求表单cy.request(method, url, body)可能确实为body参数提供了别名,因为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'
    }
  })
})