I resolved this problem this way. To add functionality to the Jest we should use expect.extend({...})
. So, to add toBeType
method to the Jest we should write this code to some setupTests.js
file:
// setupTests.js
expect.extend({
/**
* @param {*} received
* @param {string|string[]} arg
* @return {{pass:boolean,message:(function():string)}}
*/
toBeType(received, arg) {
const isCorrectType = arg => {
const receivedType = typeof received;
const checkForSingle = arg => {
const type = receivedType === 'object'
? Array.isArray(received)
? 'array'
: receivedType
: receivedType;
return type === arg;
};
const checkForArr = arg => {
const reducer = (prev, curr) => prev
|| isCorrectType(curr).isCorrect;
return arg.reduce(reducer, false);
};
return {
receivedType,
isCorrect: Array.isArray(arg)
? checkForArr(arg)
: checkForSingle(arg)
};
};
const {isCorrect, receivedType} = isCorrectType(arg);
return {
pass: isCorrect,
message: () => {
const toBe = Array.isArray(arg)
? arg.join(`' or '`)
: arg;
return `Expected '${received}' of '${receivedType}' type to be of '${toBe}' type(s)`;
}
};
}
});
Don't forget to add setupTests.js
to the jest.config.js
file as follows:
// jest.config.js
module.exports = {
...your_configurations...
setupFilesAfterEnv: ['<rootDir>/setupTests.js'],
};
Also we have to extend global.d.ts
file to say interpreter we have toBeType
method at the extend
namespace (it is required if only you are using TypeScript). Here is code we have to add to global.d.ts
:
// global.d.ts
declare namespace jest {
interface Matchers<R> {
toBeType(type:string|string[]);
}
}
This code says: get jest
namespace and extend Matchers<R>
interface with the toBeType
method. (You can look at Matchers<R>
interface implementation at the @types/jest
node module.)