在Jest中使用puppeteer上传文件

时间:2018-02-28 15:02:15

标签: chromium jestjs puppeteer google-chrome-headless

我正在使用Jest,并在this repository中设置了puppeteer,该Jest documentationjest-puppeteer-example相关联。

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

1 个答案:

答案 0 :(得分:3)

问题是,在#2120中通过WebSocket连接到浏览器实例时,文件上传不起作用。 (GitHub问题在这里:custom "Jest Node environment"。)

因此,在设置测试套件时(而不是通过{{3}})直接使用puppeteer.launch(),而不是这样做:

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'})
})