Ask Your Question
1

What is the method to test multiple values that are returned using Jest?

asked 2021-09-19 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-09-07 16:00:00 +0000

bukephalos gravatar image

To test multiple values that are returned using Jest, you can use the expect.arrayContaining matcher. This matcher allows you to check that an expected array contains all the elements that are returned in the actual array.

For example, if you have a function that returns an array of numbers [1,2,3], you could test it like this:

test('returns an array of numbers', () => {
  expect(myFunction()).toEqual(expect.arrayContaining([1,2,3]));
});

This will ensure that the array returned by myFunction contains all the expected numbers, but it may contain additional values as well. If you want to ensure that the array only contains the expected values, you can add the expect.arrayContaining matcher to an expect.not.arrayContaining matcher:

test('returns only expected numbers', () => {
  expect(myFunction()).toEqual(expect.not.arrayContaining([expect.anything()]));
  expect(myFunction()).toEqual(expect.arrayContaining([1,2,3]));
});

This will ensure that the array returned by myFunction does not contain any other values besides those specified in the expected array.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-19 11:00:00 +0000

Seen: 9 times

Last updated: Sep 07 '21