Node.js Mocha/Chai:如何测试对象的Mongoose模式数组

Node.js Mocha/Chai:如何测试对象的Mongoose模式数组,node.js,mocha.js,chai,Node.js,Mocha.js,Chai,当前使用Mongoose保存数组类型,我没有通过测试 let resourcePublic = { name: 'RS123', description: 'RS123Description', owner: newUser.id, permissions: [{ level: 'group', level_id: newGroup.id, canWrite: true }], private: false }; it('should create a new public

当前使用Mongoose保存数组类型,我没有通过测试

let resourcePublic = {
  name: 'RS123',
  description: 'RS123Description',
  owner: newUser.id,
  permissions: [{ level: 'group', level_id: newGroup.id, canWrite: true }],
  private: false
};

it('should create a new public resource', (done) => {
  request(app)
    .post('/api/v1/resources')
    .send(resourcePublic)
    .expect(httpStatus.OK)
    .then((res) => {
      ...
      expect(res.body.permissions).to.have.same.members(resourcePublic.permissions);
      ...
      resourcePublic = res.body;
      done();
    })
    .catch(done);
});
实际数组在保存文档后插入了object_id字段。。这是预期中没有的

  ACTUAL
  res.body.permissions:  [ 
      { level: 'group',
      level_id: '58f4b9c7110e5e7abd4f0425',
      _id: '58f4b9cb110e5e7abd4f042d',
      canWrite: true } 
  ]
  EXPECTED
  resourcePublic.permissions:  [
  { level: 'group',
      level_id: '58f4b9c7110e5e7abd4f0425',
      canWrite: true }
  ]
有办法通过考试吗?
感谢您的反馈。首先,您需要包含一个
.deep
,因为您正在比较对象数组(如果您不包含
.deep
,Chai将只使用
==
比较这两个对象,这永远不会是真的)

但即便如此,我认为你也不能让柴忽略额外的
\u id
。相反,我可能会将测试分为两部分:首先检查
res.body.permissions
中的项目是否具有
\u id
属性,然后将其删除,最后与
resourcePublic
进行深入比较

因此:

另外,由于您使用的是基于承诺的代码,我建议您利用摩卡的。您的测试将需要(稍微)更少的代码,它可以帮助您在混合回调和承诺时防止某些问题:

it('should create a new public resource', () => {
  return request(app)
    .post('/api/v1/resources')
    .send(resourcePublic)
    .expect(httpStatus.OK)
    .then((res) => {
      ...
      // assertions here
      ...
    });
});
it('should create a new public resource', () => {
  return request(app)
    .post('/api/v1/resources')
    .send(resourcePublic)
    .expect(httpStatus.OK)
    .then((res) => {
      ...
      // assertions here
      ...
    });
});