Skip to content

Instantly share code, notes, and snippets.

@agamm
Last active October 22, 2022 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agamm/f1c322608b5237e528cd7eada400840b to your computer and use it in GitHub Desktop.
Save agamm/f1c322608b5237e528cd7eada400840b to your computer and use it in GitHub Desktop.
Table tests with Jest (including exceptions)
// If you ever so fancy, you might want to check: unzip.dev
export const tableTest = (
test: jest.It,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
cases: any[][],
testFn: CallableFunction
) => {
test.each(cases)(`${testFn.name}(%s) should be %s`, async (input, output) => {
const asyncFn = testFn.constructor.name == 'AsyncFunction';
const inputIsArr = Array.isArray(input) && input.length > 0;
if (output instanceof Error) {
if (asyncFn) {
await expect(() =>
inputIsArr ? testFn(...input) : testFn(input)
).rejects.toThrow((output as Error).message);
} else {
expect(() => {
inputIsArr ? testFn(...input) : testFn(input);
}).toThrow((output as Error).message);
}
} else if (output instanceof Function) {
const result = inputIsArr ? testFn(...input) : testFn(input);
expect(output(result)).toBeTruthy();
} else {
if (asyncFn) {
const result = inputIsArr
? await testFn(...input)
: await testFn(input);
expect(result).toEqual(output);
} else {
const result = inputIsArr ? testFn(...input) : testFn(input);
expect(result).toEqual(output);
}
}
});
};
// Example
// You can use a value, an Error or a function as the output (2nd item in the cases array).
describe('domainToBaseURL', () => {
const cases = [
['example.com', 'https://example.com/'],
['asd.example.com', 'https://asd.example.com/'],
['asd.example.com', 'https://asd.example.com/'],
['', Error('domain is empty')],
['https://test.com?ref', (result) => result.includes('ref')],
[['param1', 'param2', 'param3'], 'result']
];
tableTest(test, cases, domainToBaseURL);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment