尝试对返回具有给定参数的对象实例的静态方法进行单元测试。我只想测试传递给此方法的属性,因为该对象具有我想排除的自动填充字段,例如 createdAt
。
在这种情况下,我是否必须使用诸如 expect().to.have.property()
之类的方法针对单个属性进行测试,或者是否有单行解决方案?
最佳答案
我已经为这样的任务创建了一个 node.js 模块:只验证预期对象中提供的那些字段。
在下面的示例中,我想比较两个对象:actual
(它由测试返回)和 expected
(预期结果)。 actual
中的某些字段是自动生成的 (_id
),因此我只需要检查它们是否存在并具有特殊格式。一些我不想比较的字段(类型为 work
的电话、account.number
)。所以 expected
对象只包含测试所需的字段:
// Some test method returns this object
let actual = {
_id: '5945bf36ccb3fa0011e8533c',
name: 'John',
email: 'john@mail.com',
phones: [
{ type: 'mobile', number: '1234567' }
{ type: 'work', number: '567382' }
],
account: {
number: '11111',
registered: '2010-04-21'
},
createdAt: '2017-02-03'
};
// Ned to do the following assertions:
// _id is exists
// name and email match
// mobile phone is exists and it's a number
// account registered match
let expected = {
_id: '_mock_',
name: 'John',
email: 'john@mail.com',
phones: [
{ type: 'mobile', number: /^d{1,10}$/ }
],
account: {
registered: '2010-04-21'
}
}
nassert.assert(actual, expected); // should pass
链接:n-assert
关于javascript - Mocha : comparing two objects, 排除像 createdAt 这样的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823856/