如何在玩笑中使每个块描述动态化?

mut*_*thu 3 javascript node.js jasmine jestjs

我正在使用 jest it.each 块来减少同一场景的测试用例的重复性,但我无法动态更新 it 块描述。怎么做?

测试用例示例

const testData = [
    {
      module: 'test_module',
      entityName: 'test_entity'
    },
    {
      module: 'test_module1',
      entityName: 'test_entity1'
    },
  ];

 it.each(testData)(`should perform get respose - ${entityName}`, async (entityDetails: any) => {
       
         const url = `${entityDetails.module}/${entityDetails.entityName}/all/`;
        // Executing
        const response = await request(server).get(url);
        // Verifying
        expect(response.status).toBe(200);

});

Run Code Online (Sandbox Code Playgroud)

在这个提供的示例中,我需要动态地将实体名称包含在块描述中。类似的事情
应该执行 get respose - test_entity
应该执行 get respose - test_entity1
如何实现这一点?

zor*_*ord 9

我意识到这是一个老问题,但它可能对未来的谷歌用户有所帮助。

it.eachname以多种方式支持动态“描述”(在文档中称为):

使用数组的数组。这为我们提供了描述中的位置参数。

it.each([
  [1, 1, 2],
  [1, 2, 3],
])('%i plus %i returns %i', (a, b, expected) => {
  expect(a + b).toBe(expected);
});
Run Code Online (Sandbox Code Playgroud)

您还可以使用对象数组。这给了我们命名参数。这对于 TypeScript 来说也更好,因为参数可以有不同的类型。

it.each([
  {a: 1, b: 1, expected: 2},
  {a: 1, b: 2, expected: 3},
])('returns $expected for $a plus $b', ({ a, b, expected }) => {
  expect(a + b).toBe(expected);
});
Run Code Online (Sandbox Code Playgroud)

最后是模板字符串方法:

it.each`
  a    | b    | expected
  ${1} | ${1} | ${2}
  ${1} | ${2} | ${3}
`('returns $expected for $a plus $b', ({ a, b, expected }) => {
  expect(a + b).toBe(expected);
});
Run Code Online (Sandbox Code Playgroud)

该描述还支持 printf 样式的格式化选项。请参阅文档以获取更多信息。

  • 感谢您提供这些清晰详细的答案 (2认同)