您也可以使用chai-json-pattern 插件来做到这一点。
Chai JSON 模式允许您为 JavaScript 对象创建蓝图,以确保验证关键信息。它使您能够使用带有易于使用的验证器的 JSON 语法扩展。
另外,由于chai-json-pattern插件目前不支持TypeScript,我们需要扩展chai.Assertion的方法类型。
我使用faker包生成符合myType的随机测试数据。
例如
import faker from 'faker';
import chai, { expect } from 'chai';
import chaiJsonPattern from 'chai-json-pattern';
chai.use(chaiJsonPattern);
declare global {
export namespace Chai {
interface Assertion {
matchPattern(pattern: string): void;
}
}
}
type myType = {
title: string;
description: string;
level: number;
categorie: string;
name: string;
};
describe('49047322', () => {
it('should pass if the data has correct types', () => {
const ach: myType[] = [
{
title: faker.name.title(),
description: faker.lorem.sentence(),
level: faker.random.number(),
categorie: faker.lorem.word(),
name: faker.name.findName(),
},
{
title: faker.name.title(),
description: faker.lorem.sentence(),
level: faker.random.number(),
categorie: faker.lorem.word(),
name: faker.name.findName(),
},
];
expect(ach).to.matchPattern(`
[
{
"title": String,
"description":String,
"level": Number,
"categorie": String,
"name": String
}
]
`);
});
it('should fail if the data has incorrect types', () => {
const ach: myType[] = [
{
title: 1 as any, // Simulate wrong type of data
description: faker.lorem.sentence(),
level: faker.random.number(),
categorie: faker.lorem.word(),
name: faker.name.findName(),
},
];
expect(ach).to.matchPattern(`
[
{
"title": String,
"description":String,
"level": Number,
"categorie": String,
"name": String
}
]
`);
});
});
测试结果:
49047322
✓ should pass if the data has correct types
1) should fail if the data has incorrect types
1 passing (27ms)
1 failing
1) 49047322
should fail if the data has incorrect types:
AssertionError: expected [ Array(1) ] to be like [ Array(1) ]
+ expected - actual
"categorie": "nisi"
"description": "Quae aut sint et earum quae."
"level": 69341
"name": "Mozell Green MD"
- "title": 1
+ "title": "String"
}
]
at Context.it (src/stackoverflow/49047322/main.test.ts:63:20)