Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `expect.any(Object)` or `expect.anything()` does not work to match `undefined` in Jest

I have the following module which I want to test.

import * as apiUtils from './apiUtils';

export function awardPoints(pointsAwarding) {
  return apiUtils.callApiService("POST", "points", pointsAwarding);
}

And this is my test.

it("should call apiUtils with correct path", () => {
  //given
  jest.spyOn(apiUtils, 'callApiService');

  //when
  pointsAwardingApi.awardPoints();

  //then
  expect(apiUtils.callApiService).toBeCalledWith(expect.any(String), 'points', expect.any(Object));
});

When I try to run this test I get the following error.

Any<Object> as argument 3, but it was called with undefined.

I was expecting that expect.any(Object) would also match undefined but it seems that's not the case.

I also tried with expect.anything() but I get a similar error.

I could simply specify undefined as the third parameter but my test is only intended to verify the second parameter.

Is there a way I can use a matcher that matches any object including undefined?

like image 738
alayor Avatar asked Oct 31 '17 02:10

alayor


People also ask

How do you match objects in Jest?

With Jest's Object partial matching we can do: test('id should match', () => { const obj = { id: '111', productName: 'Jest Handbook', url: 'https://jesthandbook.com' }; expect(obj). toEqual( expect. objectContaining({ id: '111' }) ); });

What is expect assertions in Jest?

expect. assertions(number) verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.

How do you match an array in Jest?

Array partial matching with Jest's arrayContainingtest('should contain important value in array', () => { const array = [ 'ignore', 'important' ]; expect(array). toEqual(expect. arrayContaining(['important'])) }); This test will pass as long as the array contains the string 'important' .

Which of the following matcher function is used to test greater than condition?

The toBeGreaterThan and toBeLessThan matchers check if something is greater than or less than something else.


1 Answers

It looks like expect.anything doesn't match unset values by design. If you need a "really anything" matcher, here's one:

export const expectAnythingOrNothing = expect.toBeOneOf([expect.anything(), undefined, null]);

You'll need jest-extended for the toBeOneOf matcher -- but it's a useful package anyway :)

like image 54
quezak Avatar answered Sep 21 '22 21:09

quezak