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 plex objects
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 plex objects
Share Improve this question edited Oct 30, 2019 at 13:06 adiga 35.3k9 gold badges65 silver badges87 bronze badges asked Oct 30, 2019 at 12:58 LieroLiero 27.5k41 gold badges179 silver badges337 bronze badges 01 Answer
Reset to default 5You 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]));
}