如何将运行时测试数据传递到global.teardown.ts?

问题描述 投票:0回答:1

在fixtures.ts中,我执行一些API调用,在数据库中创建对象并返回它们的id。

所有测试完成后,我需要清理数据库中创建的对象。

如何将 id 传递给 global.teardown.ts?


我有什么

我在 global.teardown.ts 中导入带有 GUID 单例数组的固定装置模块,但该模块已重新初始化且数组为空。

global.teardown.ts

import { entityGuidsToDelete, api } from './fixtures'

async function globalTeardown() {
    //not working yet, because the array is always empty
    for(const entityGuid of entityGuidsToDelete) { 
        await api.deleteEntity(entityGuid);
    }
}

export default globalTeardown;

playwright.config.ts

export default defineConfig({
  ...
  /* Configure projects for major browsers */
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
  ],

  globalTeardown: require.resolve('./global-teardown')
});
type Fixtures = {
  userApi: Api;
  newEntity: LegalEntityModel;
};

export const entityGuidsToDelete = new Array<string>();

export const test = base.extend<Fixtures>({
 ...
 newEntity: async ({ userApi }, use) => {
    const newEntity = await createNewEntity()
    entityGuidsToDelete.push(newEntity.id); //this is being called
    await use(newEntity);
  }  
}

export { expect } from '@playwright/test';
javascript playwright playwright-test playwright-typescript
1个回答
0
投票

我会使用范围

worker
固定装置:

import { test as base } from '@playwright/test';

export const test = base.extend({
  entities: [async ({}, use) => {
    const array = [];
    await use(array);
  }, { scope: 'worker' }],
  forEachWorker: [async ({entities}, use) => {
    // This code runs before all the tests in the worker process.
    await use();
    // Do something with entities
  }, { scope: 'worker', auto: true }], 
});

export { expect } from '@playwright/test';

在此示例中,将为每个工作人员创建一个

entities
数组。然后,您可以在
forEachWork
中使用该夹具,并在
use
之后对它们执行一些操作。

这是您在测试中使用它的方法:

import { test, expect } from './fixtures';

test.describe('Example test suite', () => {
  test('first dummy test', async ({ page, entities }) => {
    // Empty test
    entities.push('entity1');
  });

  test('second dummy test', async ({ page, entities }) => {
    // Empty test
    entities.push('entity2');
  });

  test('third dummy test', async ({ page, entities }) => {
    // Empty test
    entities.push('entity3');
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.