在 Jest 中使用 puppeteer 上传文件

Upload a file with puppeteer in Jest

我正在使用 Jest 并按照 this repository, which is linked to from the Jest documentation.

中的方式设置了 puppeteer

我正在尝试使用 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)
})

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

我已经尝试对测试的uploadFile部分进行了以下修改,但无济于事:

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

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

// 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()`

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

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

因此,与其这样做,不如在设置测试套件时直接使用 puppeteer.launch()(而不是通过 custom "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()
})

您还必须在页面上手动提交表单,根据我的经验 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'})
})