我正在测试一个 API,它将返回客户数据对象(ID、姓名、年龄等)。
这些对象将具有一些共享数据,具体取决于我的查询参数(例如位置等),其余数据是动态的。如何才能最好地测试返回的数据是否是我想要的?
示例数据 - 假设我搜索了特定城镇的所有客户:
{
"location": "some town",
"data": [
{ "id": "123", "name": "Bob" },
{ "id": "234", "name": "Jane" }
]
}
当然,对于我输入的每个不同的查询参数城镇,data
数组中会有不同的数据且长度不同。
我正在使用 Jest,想知道最好的测试方法是什么?
到目前为止,我有以下内容:
test('customer data location', async () => {
const expect = require('./customer-obj.json');
const response = await getcustomersin('some town');
expect(response.body).toMatchObject(expected);
expect(response.body.data).toHaveLength(2);
});
其中 customer-obj.json
是 JSON 文件:
{
"location": "some town",
}
我使用了 toMatchObject
来实现这一点,但我觉得我错过了不包含 data
值的要点...
我确实在官方文档中看到了 expect.arrayContaining(array)
,但我不知道要包含在其中的数据,因为它似乎只有在您提供的子集时才有效整体数据数组。
最佳答案
您可以忘记期待确切的值,而只需检查基础对象是否包含一组属性,如下所示:
test('Contains object with location and data properties', async () => {
const expect = require('./customer-obj.json');
const response = await getcustomersin('some town');
expect(typeof response.body).toBe('object');
expect(response.body.hasOwnProperty('location')).toBe(true);
expect(response.body.hasOwnProperty('data')).toBe(true);
});
关于javascript - 如何使用 jest 动态匹配对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57389051/