如何部分测试 json 对象的形状和部分测试值
How to partially test shape and partially test values of a json object
我想测试一下我的 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-pattern 插件来做到这一点。
Chai JSON pattern allows you to create blueprints for JavaScript objects to ensure validation of key information. It enables you to use JSON syntax extends with easy to use validators. It came up mostly for testing API with cucumber-js but can be used in any application. Additionally, you can extend base functionality with custom validators
例如
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)
我想测试一下我的 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-pattern 插件来做到这一点。
Chai JSON pattern allows you to create blueprints for JavaScript objects to ensure validation of key information. It enables you to use JSON syntax extends with easy to use validators. It came up mostly for testing API with cucumber-js but can be used in any application. Additionally, you can extend base functionality with custom validators
例如
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)