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

javascript - Test if an array is empty or contains a certain object with - Stack Overflow

programmeradmin5浏览0评论

I want to test if an array is empty or contains objects of a certain structure. In pseudo code it could be something like this:

expect([])
  .toHaveLength(0)
  .or
  .arrayContaining(
    expect.toMatchObject(
     { foo: expect.any(String) }
    )
  ) => true

expect([{foo: 'bar'}])
  .toHaveLength(0)
  .or
  .arrayContaining(
    expect.toMatchObject(
     { foo: expect.any(String) }
    )
  ) => true

expect([1])
  .toHaveLength(0)
  .or
  .arrayContaining(
    expect.toMatchObject(
      { foo: expect.any(String) }
    )
  ) => false

Maybe I'm getting it wrong on the how things work in Jest, but to me my problem looks like an or-question.

I want to test if an array is empty or contains objects of a certain structure. In pseudo code it could be something like this:

expect([])
  .toHaveLength(0)
  .or
  .arrayContaining(
    expect.toMatchObject(
     { foo: expect.any(String) }
    )
  ) => true

expect([{foo: 'bar'}])
  .toHaveLength(0)
  .or
  .arrayContaining(
    expect.toMatchObject(
     { foo: expect.any(String) }
    )
  ) => true

expect([1])
  .toHaveLength(0)
  .or
  .arrayContaining(
    expect.toMatchObject(
      { foo: expect.any(String) }
    )
  ) => false

Maybe I'm getting it wrong on the how things work in Jest, but to me my problem looks like an or-question.

Share Improve this question edited Aug 29, 2018 at 18:36 Canta 1,4802 gold badges13 silver badges26 bronze badges asked Aug 29, 2018 at 15:05 Maximilian LindseyMaximilian Lindsey 8494 gold badges19 silver badges36 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

The best way to encapsulate a logical or in your test suite would be to just exclude the particular case inside of the test itself. For example:

it('has an array of objects', () => {
  if (arr.length > 0) {
    expect(arr).toBe(expect.arrayContaining(expect.toMatchObject({ foo: expect.any(String) })));
  }
});

However, I think a more unit test-friendly approach would be to separate your concerns. One test for when there is an empty array, and one test for when the foo property is set to 'bar', etc.

发布评论

评论列表(0)

  1. 暂无评论