如何使用Chai和Mocha测试嵌套对象?

时间:2019-07-23 09:26:13

标签: mocha chai chai-http

我正在使用mocha,chai和chai-http对我的Node.js和Express应用程序进行集成测试。我正在尝试测试我的登录路由是否具有令牌。我尝试了其他断言来检查令牌是否存在于数据对象中,但是它们都不起作用。

Postman的数据如下:

{
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NiwiaWF0IjoxNTYzODczMzE3LCJleHAiOjE1NjM5NTk3MTd9.bM1RFem2pnlEqjTWGhg-s4Am1PjGNRUS_8x5Dq8J6lI",
    "user": {
      "id": 6,
      "firstName": "John",
      "lastName": "Doe",
      "email": "test@test.com",
      "createdAt": "2019-07-23T06:38:11.358Z",
      "updatedAt": "2019-07-23T06:38:11.358Z"
    }
  },
  "hasErrors": false,
  "errors": []
}

这是我尝试检查res.body是否在数据对象内部嵌套了令牌的实际测试。

/* Login Test */
let credentials = {
  'email': 'adnan@test.com',
  'password': 'test'
};

describe("POST /user-sessions", function() {
  it("should login user", function(done) {
    chai.request('http://localhost:3000')
      .post("/user-sessions")
      .send(credentials) 
      .end((err, res) => {
        res.should.have.status(200);

        res.body.should.have.nested.property('data.token');
        done();
      })
  });
})

我收到了Uncaught AssertionError:预期{对象(数据,hasErrors,...)}具有属性'data.token'

1 个答案:

答案 0 :(得分:0)

您可以使用deep.property来检查对象中的嵌套属性。

res.body.should.have.deep.property('data.token')