Reactjs Jest如何循环使用类似的测试函数
我知道,对于Jest Globals,如果要使用不同的测试参数测试相同的函数,而不是重复以下步骤:Reactjs Jest如何循环使用类似的测试函数,reactjs,unit-testing,jestjs,enzyme,Reactjs,Unit Testing,Jestjs,Enzyme,我知道,对于Jest Globals,如果要使用不同的测试参数测试相同的函数,而不是重复以下步骤: describe('test year functions', () => { it('should return correct year', () => { expect(getYear(testYear)).toBe(1990); }); it('should return correct year + 1', () => {
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);
});
});
我们可以这样做以避免重复它,这很好:
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);
});
});
现在我有不同的功能需要测试,但测试非常相似:
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);
});
});
我可以避免重复it
并这样做吗
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);
});
});
是的,这是可能的。你只需要改变一件事:
功能
,因为它是保留字:
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);
});
});