Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Jest如何循环使用类似的测试函数_Reactjs_Unit Testing_Jestjs_Enzyme - Fatal编程技术网

Reactjs Jest如何循环使用类似的测试函数

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', () => {

我知道,对于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);
    });
});
我们可以这样做以避免重复它,这很好:

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