如何使用超级测试断言猫鼬的验证错误?

How to assert validation errors of mongoose using supertest?

我正在尝试使用 supertest 验证 REST 端点返回的响应包含 moongose 验证的验证错误,如下所示

errors: Object {
  firstName: Object {
    kind: 'required',
    message: 'Path `firstName` is required.',
    name: 'ValidatorError',
    path: 'firstName',
    properties: Object {
      message: 'Path `{PATH}` is required.',
      path: 'firstName',
      type: 'required'
    },
  }

我正在写以下测试

it('should return well formatted error response when first name is missing', function(done){
    var user = {lastName:"Ranger", email:"dan.ranger@gmail.com"};
    request(app)
    .post('/api/user')
    .send(user)
    .end(function(err, res){
        res.body.should.have.property("path", "firstName");
        done();
    });
});

但我收到以下错误

AssertionError: expected Object {
errors: Object {
  firstName: Object {
    kind: 'required',
    message: 'Path `firstName` is required.',
    name: 'ValidatorError',
    path: 'firstName',
    properties: Object {
      message: 'Path `{PATH}` is required.',
      path: 'firstName',
      type: 'required'
    },
  }
},
message: 'User validation failed',
name: 'ValidationError',
} to have property path
  at Test.<anonymous> (test/userTests.js:23:25)
  at net.js:1276:10

如何编写这样的断言?

您断言 res.body 具有 属性 'path',但是 res.body 是仅包含属性 errors、[=14] 的父对象=], 和 name.

您可以测试这些属性,或者您可以按如下方式访问嵌套错误对象:

.end(function(err, res){
  res.body.errors.firstName.should.have.property("path")
  done();
});

只测试父对象的属性可能更方便,因为这应该足够了。