gpt4 book ai didi

chromium - 在 Jest 中使用 puppeteer 上传文件

转载 作者:行者123 更新时间:2023-12-01 00:20:33 25 4
gpt4 key购买 nike

我正在使用 Jest 并设置了 puppeteer,如 this repository ,从 Jest documentation 链接到.

我正在尝试使用 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 问题:#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'})
})

关于chromium - 在 Jest 中使用 puppeteer 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49032568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com