我有一个普通对象,我在其中使用伪造者生成随机值:
const product = {
id: faker.random.numeric(6),
note: faker.random.word(),
};
我有两个测试,其中一个步骤将该对象作为参数
test('Populate form', async ({
dashboardPage,
page,
}) => {
await dashboardPage.createNewProduct(product);
await expect(page).toHaveScreenshot();
});
问题是,在这些测试运行期间此对象中生成的数据仅对于一个测试是随机的,而对于第二个测试,它将与第一个测试相同。 问题是什么以及如何解决?
我尝试使用同步函数生成这个对象,但这也没有帮助
function generateNewData() {
return {
id: faker.random.numeric(6),
note: faker.random.word(),
}
};
test('Populate form', async ({
dashboardPage,
page,
}) => {
const product = generateNewData();
await dashboardPage.createNewProduct(product);
await expect(page).toHaveScreenshot();
});
使用异步函数似乎可行,为每个测试生成唯一的数据:
async function generateProduct() {
return {
id: faker.random.numeric(6),
note: faker.random.word(),
}
}
// Running test parameterized and calling function twice in each run:
for(const scenario of ['1', '2']) {
test(`Populate form ${scenario}`, async ({ page }) => {
console.log(await generateProduct())
console.log(await generateProduct())
});
}
结果:
✓ 1 [chrome web] › product.spec.ts:17:9 › Populate form 1 (148ms)
{ id: '964561', note: 'West' }
{ id: '836858', note: 'person' }
✓ 2 [chrome web] › product.spec.ts:17:9 › Populate form 2 (46ms)
{ id: '294908', note: 'Gasoline' }
{ id: '890586', note: 'Smykker' }
也许像下面这样的东西可以工作。如果它不起作用,也许你的 faker 初始化工作不正常。
var newRandomProductOne = createNewRandomProduct(faker.random.numeric(6), faker.random.word());
var newRandomProductTwo = createNewRandomProduct(faker.random.numeric(6), faker.random.word());
function createNewRandomProduct(id, note) {
return {
id: id,
note: note
};
}