You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright中测试用例复用同一随机数据导致测试失败的问题

解决Playwright Fixture中随机注册数据重复的问题

问题现象

同时运行两个注册测试用例(test1和test2)时,test1通过但test2失败,触发“账号已存在”错误——两个用例使用了完全相同的随机注册数据。

现有代码

fixtures.ts

import { test as baseTest } from '@playwright/test';
import constants from './constants.json';

const randomFigures = Math.random().toString();
const randomSuffix = randomFigures.substr(10);

constants.randomEmail = randomFigures.substr(2) + '@email.com';
constants.randomPhone = randomFigures.substr(2, 6);

type pageData = {
  constants: typeof constants;
};
const fixture = baseTest.extend<pageData>({ constants });
export const test = fixture;

constants.json

{
  "password": "password",
  "randomEmail": "",
  "randomPhone": ""
}

测试代码

import { expect } from '@playwright/test';
import { test } from './fixtures';

test.beforeEach(async ({ page }) => {
  await page.goto(`https://xyx.com`);
});

test('test1', async ({ page, constants }) => {
  await page.locator('[data-e2e="register"]').click();
  await page.locator('[data-e2e="email"]').fill(constants.randomEmail);
  await page.locator('[data-e2e="phone"]').fill(constants.randomPhone);
  await page.locator('[data-e2e="password"]').fill(constants.password);
  await page.locator('[data-e2e="button-register"]').click();
});

test('test2', async ({ page, constants }) => {
  await page.locator('[data-e2e="register"]').click();
  await page.locator('[data-e2e="email"]').fill(constants.randomEmail);
  await page.locator('[data-e2e="phone"]').fill(constants.randomPhone);
  await page.locator('[data-e2e="password"]').fill(constants.password);
  await page.locator('[data-e2e="button-register"]').click();
});

问题根源

当前代码在模块加载阶段就生成了随机数据并修改了constants对象,而Node.js模块是单例模式——所有测试用例共享这一份提前生成好的constants,不会为每个测试重新生成随机值。

修复方案

将随机数据生成逻辑放到Fixture的工厂函数中,Playwright会为每个测试用例执行一次该函数,生成独立的随机数据:

修改后的fixtures.ts

import { test as baseTest } from '@playwright/test';
import baseConstants from './constants.json';

type pageData = {
  constants: typeof baseConstants;
};

const fixture = baseTest.extend<pageData>({
  constants: async ({}, use) => {
    // 每次测试都生成新的随机数据
    const randomFigures = Math.random().toString();
    // 创建新对象,避免修改原始的baseConstants
    const constants = {
      ...baseConstants,
      randomEmail: randomFigures.substr(2) + '@email.com',
      randomPhone: randomFigures.substr(2, 6)
    };
    // 将生成的constants传递给测试用例
    await use(constants);
  }
});

export const test = fixture;

说明

  1. 使用工厂函数async ({}, use) => {...}来提供constants,Playwright会为每个测试实例调用此函数
  2. 通过对象扩展运算符...baseConstants创建新对象,避免污染原始的JSON配置
  3. 随机数据在每次测试执行时重新生成,确保每个用例的注册数据唯一

修改后,test1和test2会各自使用独立的随机邮箱和手机号,不会再出现账号重复的问题。

内容的提问来源于stack exchange,提问作者Weronika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:15:41