【问题标题】:How to make it.each block description dynamic in jest?如何使 it.each 块描述动态地开玩笑?
【发布时间】:2021-01-13 16:29:21
【问题描述】:

我正在使用 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);

});

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

【问题讨论】:

标签: javascript node.js jestjs jasmine


【解决方案1】:

it.each 需要一个数组数组,并按照指定的顺序在描述和函数参数中提供它们。它提供的唯一便利是描述字符串被格式化并且不需要字符串文字:

const testData = [
  ['test_entity', 'test_module'],
  ...
];

it.each(testData)('should perform get respose - %s', (_entityName, entityDetails) => ...)

为了更灵活地使用没有这些限制,可以使用 JavaScript 循环:

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

testData.forEach(({ module, entityName }) => {
  it(`should perform get respose - ${entityName}`, () => ...)
});

【讨论】:

  • 感谢您的努力。但我不能改变我的逻辑。它应该是对象数组,并且应该使用it.each 来实现它,是否有任何替代解决方案。还是不可能?
  • 如果你能以某种方式修改it.each 行,这意味着你可以用更适合你的情况的forEach 替换它。检查each 文档,它可以做的一切都在那里,github.com/facebook/jest/tree/master/packages/jest-each。如果不是数组数组,需要转换成它,it.each(testData.map(o => [...Object.values(o)].reverse())(...)reverse 是必需的,因为 entityName 应该首先用作测试标题中的 %s
  • @muthu 如果您需要测试用例中的对象this is how you can create it
  • @Teneff,我已经更新了测试用例中的流程,你的建议对我有用吗?请提出建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
  • 2019-11-09
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
相关资源
最近更新 更多