【问题标题】:Check browser console messages and response status codes in Playwright and Jest检查 Playwright 和 Jest 中的浏览器控制台消息和响应状态代码
【发布时间】:2021-04-15 07:29:33
【问题描述】:

我最近开始使用 Playwright 和 Jest 包编写端到端测试。

在测试中,我想检查一下,在加载页面后,浏览器控制台不包含任何错误消息,并且在后台执行的所有请求的状态码都等于 200(或者至少与 5XX 不同)。 问题是:最干净的方法是什么?

以下是有效的解决方案吗?

page.on('response', response => {
  expect(response.status()).toBe(200);
});
page.on('console', message => {
  expect(message.type()).not.toBe('error');
});
const response = await page.goto('https://url');

我不知道确切原因,但我觉得我错过了一些东西。

【问题讨论】:

  • 这是一个好方法。问题是测试将在goto 完成后立即结束。所以你可能会错过一些错误。

标签: jestjs playwright


【解决方案1】:

是的,这是一个有效的解决方案。

现在,为了丰富我的答案,下面还有一些内容......

我刚刚编写了一个类来收集我的 API 响应作为测试实用程序:

import { Page } from 'playwright';

interface ApiStat {
  status: number,
  pathname: string
}

export class AssertApiCalls {
  private _apiStats: ApiStat[] = [];
  private readonly MY_FANCY_API_ADDRESS = 'http://localhost:4321';
  private readonly API_PATH = '/api/';

  constructor(page: Page) {
    this.initEventListener(page);
  }

  private initEventListener(page: Page) {
    page.on('response', response => {
      const url = new URL(response.url());
      const origin = url.origin;
      const pathname = url.pathname;
      const isApiPath = pathname.slice(0,5) === this.API_PATH;

      if (origin === this.MY_FANCY_API_ADDRESS && isApiPath) {
        this.pushStat({
          pathname: url.pathname,
          status: response.status()
        });
      }
    });
  }

  private pushStat(apiStat: ApiStat): void {
    this._apiStats.push(apiStat)
  }

  public routeWasCalledAtPositionWithStatus(
    pathname: string,
    position: number,
    status: number
  ): boolean {
    const apiCall = this._apiStats[position];
    return apiCall.pathname == pathname && apiCall.status === status;
  }

  get apiStats() {
    return this._apiStats;
  }
}

jest 我现在做的事情像

...
expect(assertApiCalls.routeWasCalledAtPositionWithStatus('/api/user', 0, 401)).toBe(true);
expect(assertApiCalls.routeWasCalledAtPositionWithStatus('/api/user/refresh-jwt', 1, 200)).toBe(true);
expect(assertApiCalls.routeWasCalledAtPositionWithStatus('/api/user', 2, 200)).toBe(true);
...

当然,控制台事件监听器也可能发生类似情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2019-01-12
    • 2017-02-15
    • 2013-11-14
    • 2014-01-29
    • 2018-10-19
    • 2011-06-02
    相关资源
    最近更新 更多