javascript - Jasmine expect toEqual but ignore additional properties on the actual object to prevent 'Expected ... not t

Sometimes I need to assert only specific properties of the actual object and I don't care about th

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 0
Add a ment  | 

1 Answer 1

Reset to default 5

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]));
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745360970a4624356.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信