找不到 Chai 函数

Chai function not found

我刚刚开始使用 TDD,我 运行 遇到了一个奇怪的问题。我已经为(也很简单)user 模块编写了一个非常简单的测试。由于某种原因,测试抱怨 hasOwnProperty 函数不存在。

测试代码:

var expect = require('chai').expect;
var user = require('./user');

describe('Name', function() {
  it('Should have a name', function() {
    expect(user).to.have.ownProperty('name');
  });
  it('The name property should be a string', function () {
    expect(user.name).to.be.a('string');
  });
  it('Should have non empty string as name', function () {
    expect(user.name).to.have.length.above(0);
  });
});

模块:

var user = Object.create(null);

user.name = 'Name';

// exports
module.exports = user;

运行$ mocha test.js后,第一个测试失败。 Chai ownProperty reference

有什么建议吗?谢谢!

控制台输出:

Name
  1) Should have a name
  ✓ The name property should be a string
  ✓ Should have non empty string as name


2 passing (12ms)
1 failing

1) Name Should have a name:
   TypeError: obj.hasOwnProperty is not a function
    at Assertion.assertOwnProperty (node_modules/chai/lib/chai/core/assertions.js:937:13)
    at Assertion.ctx.(anonymous function) [as ownProperty] (node_modules/chai/lib/chai/utils/addMethod.js:41:25)
    at Context.<anonymous> (test.js:6:26)

Object.create(null)表示创建对象user的原型为null,因此不继承'Object'类型的属性。

试试这个。

var user = Object.create({});

user.name = 'Name';

 // exports
module.exports = user;

您需要使用 Object.create({}),才能使用 hasOwnProperty 方法。