Sometimes I need to assert only specific properties of the actual object and I don't care about the other properties.
For example:
const actual = [
{ a: 1, additionalProp: 'not interestig' },
{ a: 2, additionalProp: 'not interestig' }
];
expect(actual).toEqual([
{ a: 1 },
{ a: 2 }
])
This currently fails with:
Expected $[0] not to have properties
additionalProp: 'random value'
How can I write the expectation?
I currently do something like this:
expect(actual.map(i => ({a: 1}))).toEqual([
{ a: 1 },
{ a: 2 }
])
but I don't like it much and it does not work for more complex objects
You could explicitly address specific objects and their relevant attributes?
expect(actual.length).toBe(2);
expect(actual[0]['a']).toBe(1);
expect(actual[1]['a']).toBe(2);
Another approach is using jasmine.obectContaining
. This may be more appropriate in case the expected objects contain several properties.
const expected = [
{ a: 1 },
{ a: 2 }
];
expect(actual.length).toBe(expected.length);
for (let i = 0; i < expected.length; i++) {
expect(actual[i]).toEqual(jasmine.objectContaining(expected[i]));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.