在 Jest 中使用 puppeteer 上传文件

sdg*_*uck 6 chromium jestjs google-chrome-headless puppeteer

我正在使用 Jest 并在这个存储库中设置了 puppeteer ,它从Jest 文档链接到。

我正在尝试使用 puppeteer 在 WordPress 网站上编写一些自动烟雾测试。其中一项测试尝试将图像上传到 WordPress 媒体库。

这是测试:

it('Create test media', async () => {
  // go to Media > Add New
  await page.goto(`${env.WP_HOME}/wp/wp-admin/media-new.php`)
  const display = await page.evaluate(() => {
    const el = document.querySelector('#html-upload-ui')
    return window.getComputedStyle(el).display
  })
  if (display !== 'block') {
    // ensure we use "built-in uploader" as it has `input[type=file]`
    await page.click('.upload-flash-bypass > a')
  }
  const input = await page.$('#async-upload')
  await input.uploadFile(testMedia.path)
})
Run Code Online (Sandbox Code Playgroud)

文件输入字段的值按预期填充(我知道这一点,因为如果我在调用uploadFile它后保存屏幕截图会显示输入中文件的路径),并且表单已提交,但是当我去查看媒体时图书馆没有物品。

uploadFile对测试的部分尝试了以下修改,无果:

// 1. attempt to give time for the upload to complete
await input.uploadFile(testMedia.path)
await page.waitFor(5000)
Run Code Online (Sandbox Code Playgroud)

// 2. attempt to wait until there is no network activity
await Promise.all([
  input.uploadFile(testMedia.path),
  page.waitForNavigation({waitUntil: 'networkidle0'})  
])
Run Code Online (Sandbox Code Playgroud)

// 3. attempt to submit form manually (programmatic)
input.uploadFile(testMedia.path)
page.evaluate(() => document.querySelector('#file-form').submit())
await page.waitFor(5000) // or w/ `waitForNavigation()`
Run Code Online (Sandbox Code Playgroud)

// 4. attempt to submit form manually (by interaction)
input.uploadFile(testMedia.path)
page.click('#html-upload')
await page.waitFor(5000) // or w/ `waitForNavigation()`
Run Code Online (Sandbox Code Playgroud)

sdg*_*uck 5

问题是在通过 WebSocket 连接到浏览器实例时,文件上传不起作用,如jest-puppeteer-example. (此处的 GitHub 问题:#2120。)

因此,不要puppeteer.launch()在设置测试套件时直接使用(而不是通过自定义的“Jest Node environment”):

let browser
  , page

beforeAll(async () => {
  // get a page via puppeteer
  browser = await puppeteer.launch({headless: false})
  page = await browser.newPage()
})

afterAll(async () => {
  await browser.close()
})
Run Code Online (Sandbox Code Playgroud)

然后您还必须手动提交页面上的表单,因为根据我的经验uploadFile()不会这样做。因此,在您的情况下,对于 WordPress 媒体库单个文件上传表单,测试将变为:

it('Create test media', async () => {
  // go to Media > Add New
  await page.goto(`${env.WP_HOME}/wp/wp-admin/media-new.php`)
  const display = await page.evaluate(() => {
    const el = document.querySelector('#html-upload-ui')
    return window.getComputedStyle(el).display
  })
  if (display !== 'block') {
    // ensure we use the built-in uploader as it has an `input[type=file]`
    await page.click('.upload-flash-bypass > a')
  }
  const input = await page.$('#async-upload')
  await input.uploadFile(testMedia.path)
  // now manually submit the form and wait for network activity to stop
  await page.click('#html-upload')
  await page.waitForNavigation({waitUntil: 'networkidle0'})
})
Run Code Online (Sandbox Code Playgroud)