gpt4 book ai didi

javascript - 如何用 Jest 动态匹配对象值

转载 作者:行者123 更新时间:2023-11-28 21:16:25 24 4
gpt4 key购买 nike

我正在测试一个将返回客户数据对象(id、姓名、年龄等)的 API。

这些对象将有一些共享数据,具体取决于我的查询参数,如位置等,其余的是动态的。我怎样才能最好地测试返回的数据是我想要的?

示例数据 - 假设我搜索了特定城镇的所有客户:

{
"location": "some town",
"data": [
{ "id": "123", "name": "Bob" },
{ "id": "234", "name": "Jane" }
]
}

当然,对于我输入的每个不同的查询参数 town,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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com