如何在 Mocha 中的单个断言中检查响应的正文是否具有某些属性

Gia*_*nMS 4 javascript testing mocha.js

我正在使用 Mocha 在 Node.js 中测试 Web 应用程序的路由器,我想知道是否有一种方法可以检查对象是否具有某些属性。

现在,这就是我正在做的事情:

describe('GET /categories', function () {
        it('should respond with 200 and return a list of categories', function (done) {
            request.get('/categories')
                .set('Authorization', 'Basic ' + new Buffer(tokenLogin).toString('base64'))
                .expect('Content-Type', /json/)
                .expect(200)
                .end(function (err, res) {
                    if (err) return done(err);
                    expect(res.body).to.be.an.instanceof(Array);
                    expect(res.body).to.have.lengthOf.above(0);
                    expect(res.body[0]).to.have.property('id');
                    expect(res.body[0]).to.have.property('category');
                    expect(res.body[0]).to.have.property('tenant');
                    done();
                });
        });
});
Run Code Online (Sandbox Code Playgroud)

我在 Mocha 的文档中进行了搜索,但一直找不到我想要的内容。

rob*_*lep 5

我假设您正在使用chai

expect(res.body)
  .to.be.an.instanceof(Array)
  .and.to.have.property(0)
  .that.includes.all.keys([ 'id', 'category', 'tenant' ])
Run Code Online (Sandbox Code Playgroud)

或者:

expect(res)
  .to.have.nested.property('body[0]')
  .that.includes.all.keys([ 'id', 'category', 'tenant' ])
Run Code Online (Sandbox Code Playgroud)

(虽然后者并没有真正检查是否res.body实际上是一个数组)