Reputation: 6326
I have seen different implementations of solutions to this problem, however, none seem to work for me.
Say I have an array of objects (length of 6) containing unique data with structure:
{
first_name,
last_name,
age,
dob,
address_1,
postal_code
}
How would I compare if this array contains partial elements of another object array whose objects have a slightly shorter structure:
{
first_name,
last_name,
age
}
I understand that if I were comparing singular items I could use something like:
expect(response[i]).toMatchObject(expected[i]);
however I am unsure on how I would compare full arrays...
I have seen something like this:
expect(state).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: 'END'
})
])
)
But I cannot get it to work.
Upvotes: 5
Views: 17853
Reputation: 102307
You can use .toMatchObject(object) method, as the doc describe:
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.
You also can use expect.arrayContaining(array), as the doc describe:
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)
})
])
);
});
});
Unit test result:
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
Upvotes: 11