typescript - 剧作家API测试: intercept API request

我正在用 Playwright's API testing 测试服务器.

我有一个简单的 GET 路由,它总是返回 405 not allowed。它还记录调用了 API 路由。为了这个 StackOverflow 示例,我将日志替换为 fetch 到占位符 API。

export const loader = async () => {
  await fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(json => console.log(json));
  return notAllowed();
};

在我的 API 测试中,我想拦截对占位符 API 的 fetch 请求,并只是验证它是否被调用,而不是实际调用它。

当你用 Playwright 编写一个普通的浏览器测试时,你可以使用 page.route:

page.route('*', route => {
  console.log('url', route.request().url());
  route.continue();
});

但是,因为这是一个 API 测试并且不在页面中运行,所以这将不起作用。

如何拦截 API 请求以对其进行断言?

我尝试创建一个新的上下文:

test('my test', async ({ playwright }) => {
  const context = await playwright.request.context();
});

但是那个context对象,实际上是一个request对象,所以你不能运行request.on。我还尝试使用默认夹具中的 context 参数,但它也不起作用。

最佳答案

编写 API 测试:

Playwright Test 带有内置的请求夹具,它遵循配置选项,可以像下面这样使用来发送和断言一些请求。

const { test, expect} = require('@playwright/test');


test('should get and assert an request', async ({ request }) => {
  const issues = await request.get(`https://jsonplaceholder.typicode.com/todos/1`);
  expect(issues.ok()).toBeTruthy();
  expect(await issues.json()).toEqual(expect.objectContaining({
   "userId": 1,
   "id": 1,
   "title": "delectus aut autem",
   "completed": false
  }));
});

https://stackoverflow.com/questions/74473541/

相关文章:

python - ModuleNotFoundError 即使模块被识别

ruby-on-rails - 无法使用带 Rails 的 PostgreSql 创建数据库

typescript - 无法在 Apollo GraphQL 中定义自定义标量,TypeScrip

javascript - 升级到 React 18 后检测到额外的点击。为什么?

python - 通用迭代器注释 Python

blockchain - 在 remix Ide 中,这个通知是什么意思? "You have no

macos - 在 Mac m2 Monterey 上安装 home-brew 时出现问题

python - Pandas dataframe,连续查找所选列中的最大值,并根据该值查找另一列的

swift - 如何为等待函数调用添加超时

typescript - 如何在保持默认行为的同时扩展 tsconfig 中的类型