Puppeteer:在下拉选择后等待请求完成
Puppeteer: wait for request to finish after dropdown selection
我正在为我的 React 应用程序编写测试。
我有两个下拉菜单。在第一个中做出选择后,将触发获取请求,并且来自该获取请求的数据将用于填充第二个下拉列表。
我的测试是这样的:
test("fruit dropdown becomes enabled when food type fruit is selected", async () => {
await page.select('[data-testid="food"]', "fruit"); // this makes a selection in the drop down and fires a request
// I should wait for request to finish before doing this
const isFruitDropdownDisabled = await page.$eval(
'[data-testid="fruit"]',
element => element.disabled
);
expect(isFruitDropdownDisabled).toBe(false);
}, 16000);
现在测试失败了,我如何告诉它等到提取请求完成后再检查 [data-testid="fruit"]
是否被禁用?
如果您需要等待,请使用手册中描述的 waitFor
函数之一,例如 waitForFunction。
您有两个选择:
- 等待 request/response 完成
- 等到第二个下拉框被填满
选项 1:等待请求
使用 page.waitForResponse
等待特定响应发生,然后您希望您的脚本继续运行。示例:
await page.waitForResponse(response => response.url().includes('/part-of-the-url'));
方案二:等待第二个下拉框被填充
正如您所说,请求会填充另一个下拉框(我猜是 select
元素),您可以使用 page.waitForFunction
函数等到 select 框充满。示例:
await page.waitForFunction(() => document.querySelector('#selector-of-second-selectbox').length > 0);
select 框上的 length
属性将检查里面有多少 option
个元素。因此,通过检查 length
是否为 non-zero,这是等待 select 框被填满。这假设 select 框在开始时是空的(length
是 0
)。
我正在为我的 React 应用程序编写测试。
我有两个下拉菜单。在第一个中做出选择后,将触发获取请求,并且来自该获取请求的数据将用于填充第二个下拉列表。
我的测试是这样的:
test("fruit dropdown becomes enabled when food type fruit is selected", async () => {
await page.select('[data-testid="food"]', "fruit"); // this makes a selection in the drop down and fires a request
// I should wait for request to finish before doing this
const isFruitDropdownDisabled = await page.$eval(
'[data-testid="fruit"]',
element => element.disabled
);
expect(isFruitDropdownDisabled).toBe(false);
}, 16000);
现在测试失败了,我如何告诉它等到提取请求完成后再检查 [data-testid="fruit"]
是否被禁用?
如果您需要等待,请使用手册中描述的 waitFor
函数之一,例如 waitForFunction。
您有两个选择:
- 等待 request/response 完成
- 等到第二个下拉框被填满
选项 1:等待请求
使用 page.waitForResponse
等待特定响应发生,然后您希望您的脚本继续运行。示例:
await page.waitForResponse(response => response.url().includes('/part-of-the-url'));
方案二:等待第二个下拉框被填充
正如您所说,请求会填充另一个下拉框(我猜是 select
元素),您可以使用 page.waitForFunction
函数等到 select 框充满。示例:
await page.waitForFunction(() => document.querySelector('#selector-of-second-selectbox').length > 0);
select 框上的 length
属性将检查里面有多少 option
个元素。因此,通过检查 length
是否为 non-zero,这是等待 select 框被填满。这假设 select 框在开始时是空的(length
是 0
)。