Cypress 在 body 中使用 JSON 夹具?

msm*_*114 4 cypress

因此基于 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'
  }
})
Run Code Online (Sandbox Code Playgroud)

然而,当我查看 Cypress 发送的“命令”时,它按照字面意思发送正文Body: @create_test

是否无法在 POST 请求正文中使用固定装置?我确认夹具加载正确。我确认当我将整个 JSON 粘贴到选项中时它也可以工作body......但是对于大型 JSON 主体来说,这很快就会变得丑陋。

小智 7

你得到一个文字,因为在表单中cy.request(options), options 是一个普通的 JS 对象,不幸的是 Cypress 没有解析它来解释别名。

请求表单cy.request(method, url, body)可能确实允许主体参数的别名,因为cy.route()允许它参考:访问夹具数据

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

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

所以,你可以使用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'
    }
  })
});
Run Code Online (Sandbox Code Playgroud)

或者

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'
    }
  })
})
Run Code Online (Sandbox Code Playgroud)