如何部分测试json对象的形状和部分测试值



我想在我的mocha期望中测试json的形状。我知道的一些东西像"name",但其他的(_id(来自数据库。对于它们,我只关心它们是否设置了正确的类型。

这里我有我的期望:

expect(object).to.eql({
recipe:
{
_id: '5fa5503a1fa816347f3c93fe',
name: 'thing',
usedIngredients: []
}
})

如果可能的话,我宁愿做这样的事情:

expect(object).to.eql({
recipe:
{
_id: is.a('string'),
name: 'thing',
usedIngredients: []
}
})

有人知道实现这一点的方法吗?还是最好将其分解为多个测试?

您可以使用chai-json模式插件来实现这一点。

Chai JSON模式允许您为JavaScript对象创建蓝图,以确保关键信息的验证。它使您能够使用JSON语法扩展和易于使用的验证器。它主要用于使用cucumber-j测试API,但可用于任何应用。此外,您可以使用自定义验证器扩展基本功能

例如

const chai = require('chai');
const chaiJsonPattern = require('chai-json-pattern').default;
chai.use(chaiJsonPattern);
const { expect } = chai;
describe('64715893', () => {
it('should pass', () => {
const object = {
recipe: {
_id: Math.random().toString(),
name: 'thing',
usedIngredients: [Math.random() + 'whatever'],
},
};
expect(object).to.matchPattern(`{
"recipe": {
"_id": String,
"name": "thing",
"usedIngredients": Array,
},
}`);
});
});

测试结果:

64715893
✓ should pass

1 passing (50ms)

最新更新