我怎样才能让剧作家收听消息事件

how can I get playwright to listen to message events

我有一个通过 postMessage 命令进行通信的网站

 window.parent.postMessage(communication, this.origin);

当使用 playwright 时,我试图做一个“on message”处理程序

function eventListener(returnEvent: any): any {
  window.addEventListener('message', function(event: MessageEvent) {
    console.log('Im here');
    if (event.data.messageId === 'payment-method') {
      console.log('setting return event', event);
      returnEvent = event;
      return returnEvent;
    }
  });
}

...

  let returnEvent: any = {};
  await page.evaluate(eventListener, returnEvent);
  await creditCardDetailsPage.fillFormValid();
  await page.waitForTimeout(5000); //give time for message event to fire
  console.log('event was', returnEvent);
  await expect(returnEvent).toEqual(<MY DATA OBJECT HERE>)

控制台输出

Im here
setting return event MessageEvent
event was {}

我不能将我的期望放在 page.evaluate() 代码中,因为它是在它注入的 javascript 标记的上下文中执行的,而不是在规范的上下文中执行的。

async def print_args(msg):
    values = []
    for arg in msg.args:
        values.append(await arg.json_value())
    print(values)

page.on("console", print_args)
await page.evaluate("console.log('hello', 5, {foo: 'bar'})")

我想最终达到 expect,而不是 evaluatewaitForEvent

遗憾的是,我找不到任何用于收听消息事件的内容。相反,我们只是选择 console.info.

此解决方案将 page.on('console', ...) 包装到一个异步函数中,我们可以简单地将其用作 'resolve if success, hang if failure' 开关

// Return true if the page emits 'Hello, World!' to the console info level
async function waitForMessageAsync(): Promise<boolean> {
  return new Promise(function (resolve) {
    page.on('console', (msg) => {
      if (msg.type() === 'log' && msg.text() === 'Hello, World!') {
        resolve(true);
      }
    });
  });
}

await expect(await waitForMessageAsync).toBeTruthy();

这样,如果 expect 等待我们的 'Hello, World!' 消息超时,测试将失败!