[英]Upload a file with puppeteer in Jest
我正在使用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)
})
文件輸入字段的值按預期填充(我知道這是因為如果我在調用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 。)
因此,在設置測試套件時(而不是通過自定義的“Jest Node環境” ),不要直接使用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'})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.