首页 > 解决方案 > Mocha/Chai 检查对象原型上是否存在键

问题描述

我正在使用 Mocha/Chai 编写测试,并且assert.hasAllKeys适用于不在对象原型上的键。有没有办法检查对象原型上是否存在键?

我试过阅读文档无济于事。

谢谢

标签: javascriptmocha.jschai

解决方案


我们可以使用这种方式

assert.hasAllKeys(YourObject.prototype, ['prop1', 'prop2']);

这是代码示例:

src.js

function MyObject () {

}

MyObject.prototype.prop1 = function() {
  console.log('ok');
}

MyObject.prototype.prop2 = 10;

module.exports = {
  MyObject
};

测试.js

const chai = require('chai');
const src = require('./src');
const assert = chai.assert;

describe('unit test', function() {
  it('runs test', function() {    
    assert.hasAllKeys(src.MyObject.prototype, ['prop1', 'prop2']); // check object prototype       
  })
});

希望能帮助到你


推荐阅读