Puppeteer:在下拉选择后等待请求完成 [英] Puppeteer: wait for request to finish after dropdown selection

查看:403
本文介绍了Puppeteer:在下拉选择后等待请求完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的 React 应用程序编写测试.

I am writing a test for my React application.

我有两个下拉菜单.在第一个中做出选择后,将触发提取请求,并且使用该提取请求中的数据填充第二个下拉列表.

I have two dropdowns. Once a selection is made in the first one, a fetch request is trigged and the data from that fetch request is used to populate the second dropdown.

我的测试如下:

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"] 是否被禁用?

Right now that test fails, how do I tell it to wait until the fetch request has finished before checking if [data-testid="fruit"] is disabled?

推荐答案

您有两个选择:

  1. 等待请求/响应完成
  2. 等待第二个下拉框填满

选项 1:等待请求

使用 page.waitForResponse 等待特定响应发生,然后您希望脚本继续.示例:

Use page.waitForResponse to wait for a specific response to happen, before you want your script to continue. Example:

await page.waitForResponse(response => response.url().includes('/part-of-the-url'));

选项 2:等待第二个下拉框被填充

正如您所说的请求填充另一个下拉框(我猜是 select 元素),您可以使用 page.waitForFunction 函数等待直到选择框被填满.示例:

As you are saying that the request populates another dropdown box (I'm guessing a select element), you could use the page.waitForFunction function to wait until the select box is filled. Example:

await page.waitForFunction(() => document.querySelector('#selector-of-second-selectbox').length > 0);

选择框上的 length 属性将检查里面有多少 option 元素.因此,通过检查 length 是否非零,这是等到选择框被填充.这假设选择框在开始时是空的(length0).

The length attribute on a select box will check how many option elements are inside. So by checking if length is non-zero, this is wait until the select box is filled. This assumes, that the select box is empty at the start (length is 0).

这篇关于Puppeteer:在下拉选择后等待请求完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆