0

我在 node.js 中有一个 API,我可以在其中发送多个 DeviceId 的有效负载,以更新它们的设置。例如,我要发送的示例有效负载是:

{"DeviceId":["1","2","3"],"Settings":[{"Key":"OnSwitch","Value":"true"}]}

发送后,我会说 DeviceId 1,2,3 都将更新他们的设置。这工作正常,我已经在 Postman 本地对其进行了测试。我现在想编写一个单元测试来检查行为。我的单元测试如下:

context('POST With Multiple IDs', () => {
  describe('1,2,3 IDs POST', () => {
    it.only('It should post a full payload with Value True', (done) =>{
        chai.request('http://localhost:3999')
        .post('/api/v2/settings/')
        .set('Authorization', authToken)
        .set('Content-Type', 'application/json')
        .type('Form')
        .send({"DeviceId": ["1", "2", "3"],
            "Settings": [
              {
                "Key": "OnSwitch",
                "Value": "true"
              }
            ]
          })
        .then(res => {
        console.log(res.body);
        res.should.have.status(200);
        res.body.should.be.a('object');
        res.body.should.have.property('message');
        res.body.should.have.property('message').eql('All of the Ids Settings sent for processing.');
        res.body.should.have.property('payload');
        done();
        });
    });
});

在我发帖的代码中,我检查了 DeviceIds 是否出现在数组中。如果它们不在数组中,则会返回一条消息,说明 DeviceId 必须在数组中。这是代码:

if (!Array.isArray(req.body.DeviceId)) {
                logInfo({message: 'DeviceId must be an array.', data: req.body}, 'API');
                return res.status(400).send({
                    message: 'DeviceId must be an array.',
                });
            }

当我运行上面的单元测试时,我陷入了这个 if 语句,我得到了返回的消息,即req.body.DeviceId不是数组。如果我记录typeof req.body.DeviceId,我会得到未定义的记录。为什么会这样?当我从邮递员本地发帖时,它工作正常。那就是当我在本地发送帖子时,帖子请求通过没有错误。但是chaiHttp现在用于单元测试,我遇到了一些麻烦。可能有人知道为什么在单元测试中会发生这种情况,并使其不会发生,我不会被困在这个数组检查中。任何建议将不胜感激!

4

1 回答 1

0

单元测试中的行.type('Form')取消了将 Content Type 设置为 application/json。该行实际上将内容类型更改为不识别数组的不同内容类型。因此,删除该行并进行以下单元测试是可行的!

context('POST With Multiple IDs', () => {
  describe('1,2,3 IDs POST', () => {
    it.only('It should post a full payload with Value True', (done) =>{
        chai.request('http://localhost:3999')
        .post('/api/v2/settings/')
        .set('Authorization', authToken)
        .set('Content-Type', 'application/json')
        .type('Form')
        .send({"DeviceId": ["1", "2", "3"],
            "Settings": [
              {
                "Key": "OnSwitch",
                "Value": "true"
              }
            ]
          })
        .then(res => {
        console.log(res.body);
        res.should.have.status(200);
        res.body.should.be.a('object');
        res.body.should.have.property('message');
        res.body.should.have.property('message').eql('All of the Ids Settings sent for processing.');
        res.body.should.have.property('payload');
        done();
        });
    });
});
于 2020-12-10T20:37:28.653 回答