Reputation: 2743
I know that with Jest Globals, if you have same function to be tested with different test parameters, instead of repeating this:
describe('test year functions', () => {
it('should return correct year', () => {
expect(getYear(testYear)).toBe(1990);
});
it('should return correct year + 1', () => {
expect(getYear(testYear + 1)).toBe(1991);
});
});
We can do this to avoid repeating it
, which is great:
describe('test year functions', () => {
test.each`
year | addYear | expected
${testYear} | ${0} | ${1990}
${testYear} | ${1} | ${1991}
`('returns correct years', ({ year, addYear, expected }) => {
expect(getYear(testYear + addYear)).toBe(expected);
});
});
Now I have different functions to be tested, but the tests are quite similar:
describe('test date functions', () => {
it('getYear(date) should return correct year', () => {
expect(getYear(1990)).toBe(1990);
});
it('getMonth(date) should return correct month', () => {
expect(getMonth(testMonth + 1)).toBe(10);
});
});
Can I avoid the repeat of it
and do something like this?
describe('test date functions', () => {
test.each`
function | parameter | expected
${getYear} | ${1990} | ${1990}
${getMonth} | ${testMonth + 1} | ${10}
`('returns correct dates', ({ function, parameter, expected }) => {
expect(function(parameter)).toBe(expected);
});
});
Upvotes: 2
Views: 235
Reputation: 13078
Yes it is possible. You just need to change one thing:
function
for other word because it is a reserved word:
describe('test date functions', () => {
test.each`
func | parameter | expected
${getYear} | ${1990} | ${1990}
${getMonth} | ${testMonth + 1} | ${10}
`('returns correct dates', ({ func, parameter, expected }) => {
expect(func(parameter)).toBe(expected);
});
});
I tried it and it worked.
Upvotes: 1