首页 > 解决方案 > 如何在测试中使用在 beforeAll() 钩子中分配了值的变量

问题描述

我想在 hook 处分配一堆具有值的变量,beforeAll()然后在 中使用它们test.each([]),但我得到的只是未定义而不是实际值。

但是当我尝试在 normal 中访问相同的变量时test(),事实证明,我的变量具有实际值并且不是未定义的。

有没有办法给变量赋值,然后在中使用它们test.each([])

let movieId: string;
let serialId: string;

describe('Video page tests', () => {

  beforeAll(async () => {
    movieId = await videos.CreateMovie();
    serialId = await videos.CreateSerial();
  });

test.each([
    ['Deletes movie', movieId],
    ['Deletes serial', serialId],
  ])('%s', async(caseTitle, entityId) => {
    reporter.description(`${caseTitle}`);

    await videos.DeleteContent(entityId); //entityId is undefined
  })

test('Deletes movie', async() => {
    reporter.description(`Deletes movie`);

    await videos.DeleteContent(movieId); //movieId is correct
  })

标签: typescriptjestjsautomated-testseachplaywright

解决方案


事实证明,我不能使用test.each在钩子上分配的变量beforeAll,所以我想出了一个解决我的问题的方法

let content: string[] = [];
describe('Video page tests', () => {

  beforeAll(async () => {
    content.push(await videos.CreateMovie());
    content.push(await videos.CreateSerial());
  });

test.each([
    ['Deletes movie', 0],
    ['Deletes serial', 1],
  ])('%s', async(caseTitle, entityId) => {
    reporter.description(`${caseTitle}`);

    await videos.DeleteContent(content[entityId]);
  })

推荐阅读