Jest.js “ puppet 师不接电话”对话框

siv3szwd  于 2022-12-31  发布在  Jest
关注(0)|答案(1)|浏览(132)

我正在测试 puppet 戏中的警告框:

msg = '';
    await page.goto('http://localhost:8080/', {
      waitUntil: 'networkidle2'
    });
    await page.$eval('#value', el => el.value = '<script>alert("BLEH")</script>');
    page.on('dialog', async dialog => {
      msg = dialog.message();
      await dialog.dismiss()
    })
    // submit comment
    await page.$eval('#message', form => form.submit());
    expect(msg).toEqual('BLEH');

然而,它似乎没有在警告框中返回消息(即使我已经确认它可以手动操作)。你知道为什么page.on('dialog', async dialog => {没有被输入吗?

anhgbhbe

anhgbhbe1#

我不确定您的页面发生了什么--看起来您是在测试XSS,但无论如何,您可以承诺对话框处理程序解析为dialog.message()值,如本例所示。
注意,我是用Enter键提交表单的--调用form.submit()似乎覆盖了默认的阻止机制,杀死了页面,但是如果它在您的站点上工作,那么这种修改不会改变下面代码的基本点。
请记住await dialogDismissed;永远不会超时,因为它不是Puppeteer函数。如果您希望这样,请在promise中调用setTimeout(reject, someDelay)

const puppeteer = require("puppeteer");

let browser;
(async () => {
  const html = `
    <form id="message"><input id="value"></form>
    <script>
      document
        .getElementById("message")
        .addEventListener("submit", e => {
          e.preventDefault();
          alert(document.getElementById("value").value);
        })
      ;
    </script>
  `;
  browser = await puppeteer.launch();
  const [page] = await browser.pages();
  const dialogDismissed = new Promise((resolve, reject) => {
    const handler = async dialog => {
      await dialog.dismiss();
      resolve(dialog.message());
    };
    page.once("dialog", handler);
  });
  await page.setContent(html);
  const inputEl = await page.$("#value");
  await inputEl.type("hello world");
  await inputEl.press("Enter");
  const msg = await dialogDismissed;
  console.log(msg); // => hello world
  await page.close();
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close())
;

相关问题