最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论