首页 文章

赛普拉斯请求:身体中的空数组

提问于
浏览
3

在使用赛普拉斯测试我的API时,我发现自己遇到了一些麻烦 . (我使用的是2.1.0版)

我正在向我的 endpoints 发送请求,并希望在我将空数组作为参数发送时验证它是如何响应的 . 问题是,不知何故,赛普拉斯必须解析我给他的身体,并删除空阵列 .

我的代码如下:

cy.request({
    method: 'PUT',
    url,
    form: true,
    body: {
        name: 'Name',
        subjects: []
    }
})
.then((response) => {
    expect(response.body).to.have.property('subjects');
    const { subjects } = response.body;
    expect(subjects.length).to.eq(0);
});

// API receives only the parameter name, and no subjects

当我发送一个空的主题数组时, endpoints 将删除所有相关主题,并返回具有空主题数组的对象 . 它正在按预期工作,我正在使用的软件正常运行 .

当赛普拉斯发送此请求时, endpoints does not 将接收参数主题 . 对我来说这是一个非常不同的事情:在这种情况下我不应该触及主题 .

有没有办法避免赛普拉斯的这种“改写”并在我写这篇文章时发送身体?

1 回答

  • 3

    设置 form: false 时,测试有效 .

    it.only('PUTs a request', () => {
      const url = 'http://localhost:3000/mythings/2'
      cy.request({
          method: 'PUT',
          url: url,
          form: false,
          body: {
            name: 'Name',
            subjects: []
          }
        })
        .then((response) => {
          expect(response.body).to.have.property('subjects');
          const {
            subjects
          } = response.body;
          expect(subjects.length).to.eq(0);
        });
    })
    

    我用json-server设置了一个本地休息服务器来检查行为 .

    如果我尝试使用 form: true PUT非空数组

    cy.request({
        method: 'PUT',
        url: url,
        form: true,
        body: {
          name: 'Name',
          subjects: ['x']
        }
      })
    

    在测试运行后查看 db.json ,我看到项目索引迁移到密钥,

    "mythings": [
        {
            "name": "Name",
            "subjects[0]": "x",
            "id": 2
        }
    ],
    

    所以也许 form 只意味着简单的属性 .

    更改为 form: false 会给出正确的数组

    {
      "mythings": [
        {
          "name": "Name",
          "subjects": ['x'],
          "id": 2
        }
      ],
    }
    

    然后可以通过发布一个空数组来清空它 .

相关问题