我正在使用Jest并且在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()`
问题是,在jest-puppeteer-example
中通过WebSocket连接到浏览器实例时文件上传不起作用。 (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'})
})