5.5 expect.any: Function or constructor
We’ve seen how expect.anything()
can be used to assert only on specific parts of the code.
expect.anything
lets us match anything that’s not null or undefined.
Jest also has an expect.any(Constructor)
construct. Which is similar to expect.anything()
except we can be prescriptive with the type of the variable being asserted upon.
expect.any(Function)
For example, we can check that the output of a function is a function. In this case we’re using a thunkify
function which takes a function and returns a function that calls the original function.
const thunkify = fn => () => fn();
test('curry should return a function', () => {
expect(thunkify(() => {})).toEqual(expect.any(Function));
});
This passes as expected.
npx jest src/05.05-thunkify.test.js
PASS src/05.05-thunkify.test.js
✓ curry should return a function (3ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
expect.any() for constructors
expect.any
works with any constructor.
We can check that a createUser
function in our application is called with a string and a Date.
const appWork = createUser => {
return async (request, response) => {
const {name} = request.body;
const user = await createUser(name, new Date());
return response.status(201).json(user);
};
};
We can write a test as follows, to check that createUser
parameters are of the right type.
test('should call createUser with right types', async () => {
const request = {
body: {
name: 'User Name'
}
};
const response = {
status: jest.fn(() => response),
json: jest.fn(() => response)
};
const mockCreateUser = jest.fn();
await appWork(mockCreateUser)(request, response);
expect(mockCreateUser).toHaveBeenCalledWith(
expect.any(String),
expect.any(Date)
);
});
This outputs tests passing.
npx jest src/05.05-constructors.test.js
PASS src/05.05-constructors.test.js
✓ should call createUser with right types (4ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
We’ve seen how expect.any()
is a more prescriptive expect.anything()
.
The next part of The Jest Handbook deals with testing Express applications.