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
?
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' }) ); });
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.
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' .
The toBeGreaterThan and toBeLessThan matchers check if something is greater than or less than something else.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With