5

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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I also found this article that, in combination with what you wrote, was very helpful medium.com/@andrei.pfeiffer/…
Yes, I think a custom matcher would be a great solution if you were finding yourself testing this case more often. Still, I wonder if you're writing one test case where you should be writing two

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.