Currently, I am utilizing Jest#test.each
to execute some unit tests.
Below is the code snippet:
const invalidTestCases = [
[null, TypeError],
[undefined, TypeError],
[false, TypeError],
[true, TypeError],
];
describe('normalizeNames', () => {
describe('invalid', () => {
test.each(invalidTestCases)('some description for (%p, %p)', (actual, expected) => {
expect(() => normalizeNames(actual as any)).toThrowError(expected);
});
});
describe('valid', () => {
// ...
});
});
The issue arises when attempting to run this code due to TypeScript errors:
Argument of type '(actual: boolean | TypeErrorConstructor | null | undefined, expected: boolean | TypeErrorConstructor | null | undefined) => void' is not assignable to parameter of type '(...args: (TypeErrorConstructor | null)[] | (TypeErrorConstructor | undefined)[] | (boolean | TypeErrorConstructor)[]) => any'.
Types of parameters 'actual' and 'args' are incompatible.
Type '(TypeErrorConstructor | null)[] | (TypeErrorConstructor | undefined)[] | (boolean | TypeErrorConstructor)[]' is not assignable to type '[boolean | TypeErrorConstructor | null | undefined, boolean | TypeErrorConstructor | null | undefined]'.
Type '(TypeErrorConstructor | null)[]' is missing the following properties from type '[boolean | TypeErrorConstructor | null | undefined, boolean | TypeErrorConstructor | null | undefined]': 0, 1
test.each(invalidTestCases)('some description for (%p, %p)', (actual, expected) => {
~~~~~~~~~~~~~~~~~~~~~~~
I also experimented with using an array
of objects
instead of a 2D array
, like so:
const invalidTestCases = [
{ actual: null, expected: TypeError },
{ actual: undefined, expected: TypeError },
{ actual: false, expected: TypeError },
{ actual: true, expected: TypeError },
];
describe('normalizeNames', () => {
describe('invalid', () => {
test.each(invalidTestCases)('some description for (%p, %p)', ({ actual, expected }) => {
expect(() => normalizeNames(actual as any)).toThrowError(expected);
});
});
describe('valid', () => {
// ...
});
});
...however, by doing it this way, getting the correct test description for object
values becomes challenging.