开玩笑如何循环类似的测试功能

Jest how to loop through similar test functions

我知道使用 Jest Globals,如果您要使用不同的测试参数测试相同的功能,而不是重复这个:

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);
    });
});

我们可以这样做以避免重复it,这很棒:

describe('test year functions', () => {
    test.each`
        year         | addYear  | expected
        ${testYear}  | [=11=]     | ${1990}
        ${testYear}  |      | ${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}  | 
    `('returns correct dates', ({ function, parameter, expected }) => {
        expect(function(parameter)).toBe(expected);
    });
});

是的,这是可能的。你只需要改变一件事:

  1. function替换为其他词,因为它是一个保留字:

 describe('test date functions', () => {
      test.each`
              func    | parameter         | expected
          ${getYear}  | ${1990}           | ${1990}
          ${getMonth} | ${testMonth + 1}  | 
      `('returns correct dates', ({ func, parameter, expected }) => {
          expect(func(parameter)).toBe(expected);
      });
 });

我试过了,成功了。