gpt4 book ai didi

javascript - 检查一个对象数组是否包含 Jest 中另一个对象数组的元素

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

我见过针对此问题的不同解决方案的实现,但是,似乎没有一个对我有用。

假设我有一个对象数组(长度为 6),其中包含具有结构的唯一数据:

{
first_name,
last_name,
age,
dob,
address_1,
postal_code
}

如果此数组包含另一个对象数组的部分元素,而该数组的对象结构稍短,我将如何进行比较:

{
first_name,
last_name,
age
}

我明白,如果我要比较单个项目,我可以使用类似的东西:

expect(response[i]).toMatchObject(expected[i]);

但是我不确定如何比较完整数组...

我见过这样的:

expect(state).toEqual(          
expect.arrayContaining([
expect.objectContaining({
type: 'END'
})
])
)

但我无法让它工作。

最佳答案

您可以使用 .toMatchObject(object)方法,如文档所述:

You can also pass an array of objects, in which case the method will return true only if each object in the received array matches (in the toMatchObject sense described above) the corresponding object in the expected array.

您也可以使用 expect.arrayContaining(array) ,如文档所述:

That is, the expected array is a subset of the received array. Therefore, it matches a received array which contains elements that are not in the expected array.

import faker from 'faker';

describe('test suites', () => {
it('should contains', () => {
const state = new Array(6).fill(null).map(() => ({
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
age: faker.random.number({ min: 0, max: 100 }),
dob: 'c',
address_1: faker.address.city(),
postal_code: faker.address.zipCode()
}));

const matchObj = new Array(state.length).fill(null).map((_, idx) => {
const item = state[idx];
const stateSlice = {
first_name: item.first_name,
last_name: item.last_name,
age: item.age
};
return stateSlice;
});
expect(matchObj).toEqual(
expect.arrayContaining([
expect.objectContaining({
first_name: expect.any(String),
last_name: expect.any(String),
age: expect.any(Number)
})
])
);
expect(state).toMatchObject(matchObj);
expect(state).toEqual(
expect.arrayContaining([
expect.objectContaining({
first_name: expect.any(String),
last_name: expect.any(String),
age: expect.any(Number)
})
])
);
});
});

单元测试结果:

PASS  src/stackoverflow/58238433/index.spec.ts (9.564s)
test suites
✓ should contains (8ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.779s

关于javascript - 检查一个对象数组是否包含 Jest 中另一个对象数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238433/

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