
使用 playwright 等端到端测试框架时,模拟 graphql 请求可以显着提高测试可靠性和速度。受到 jay freestone 优秀博客文章 stubbing graphql requests in playwright 的启发,我决定构建一个可重用的实用函数,允许灵活的 graphql 请求拦截和响应存根。
在这篇文章中,我将引导您完成拦截gql实用程序的实现,并演示如何将其与 playwright 一起使用来模拟 graphql 查询和突变的服务器响应。
interceptgql 实用程序:它是如何工作的
interceptgql 实用程序为后端的所有 graphql 请求注册一个路由处理程序,根据操作名称拦截特定操作。您可以定义每个操作应如何响应并验证请求中传递的变量。
这是实现:
婚纱影楼小程序提供了一个连接用户与影楼的平台,相当于影楼在微信的官网。它能帮助影楼展示拍摄实力,记录访客数据,宣传优惠活动。使用频率高,方便传播,是影楼在微信端宣传营销的得力助手。功能特点:样片页是影楼展示优秀摄影样片提供给用户欣赏并且吸引客户的。套系页是影楼根据市场需求推出的不同套餐,用户可以按照自己的喜好预定套系。个人中心可以查看用户预约的拍摄计划,也可以获取到影楼的联系方式。
import { test as basetest, page, route } from '@playwright/test';
import { namedoperations } from '../../src/graphql/autogenerate/operations';
type calledwith = record;
type operations = keyof (typeof namedoperations)['query'] | keyof (typeof namedoperations)['mutation'];
type interceptconfig = {
operationname: operations | string;
res: record;
};
type interceptedpayloads = {
[operationname: string]: calledwith[];
};
export async function interceptgql(
page: page,
interceptconfigs: interceptconfig[]
): promise<{ reqs: interceptedpayloads }> {
const reqs: interceptedpayloads = {};
interceptconfigs.foreach(config => {
reqs[config.operationname] = [];
});
await page.route('**/graphql', (route: route) => {
const req = route.request().postdatajson();
const operationconfig = interceptconfigs.find(config => config.operationname === req.operationname);
if (!operationconfig) {
return route.continue();
}
reqs[req.operationname].push(req.variables);
return route.fulfill({
status: 200,
contenttype: 'application/json',
body: json.stringify({ data: operationconfig.res }),
});
});
return { reqs };
}
export const test = basetest.extend<{ interceptgql: typeof interceptgql }>({
interceptgql: async ({ browser }, use) => {
await use(interceptgql);
},
});
示例:测试任务管理仪表板
为了演示该实用程序的实际效果,让我们用它来测试任务管理仪表板。我们将拦截 graphql 查询 (gettasks) 并模拟其响应。
import { expect } from '@playwright/test';
import { namedOperations } from '../../../src/graphql/autogenerate/operations';
import { test } from '../../fixtures';
import { GetTasksMock } from './mocks/GetTasks.mock';
test.describe('Task Management Dashboard', () => {
test.beforeEach(async ({ page, interceptGQL }) => {
await page.goto('/tasks');
await interceptGQL(page, [
{
operationName: namedOperations.Query['GetTasks'],
res: GetTasksMock,
},
]);
});
test('Should render a list of tasks', async ({ page }) => {
const taskDashboardTitle = page.getByTestId('task-dashboard-title');
await expect(taskDashboardTitle).toHaveText('Task Dashboard');
const firstTaskTitle = page.getByTestId('0-task-title');
await expect(firstTaskTitle).toHaveText('Implement authentication flow');
const firstTaskStatus = page.getByTestId('0-task-status');
await expect(firstTaskStatus).toHaveText('In Progress');
});
test('Should navigate to task details page when a task is clicked', async ({ page }) => {
await page.getByTestId('0-task-title').click();
await expect(page.getByTestId('task-details-header')).toHaveText('Task Details');
await expect(page.getByTestId('task-details-title')).toHaveText('Implement authentication flow');
});
});
这里发生了什么?
- 拦截请求:拦截gql实用程序拦截gettasks查询并返回gettasksmock中定义的模拟数据。
- 模拟响应: 提供模拟响应,而不是到达实际后端。
- 验证变量:该实用程序还存储随请求发送的 graphql 变量,这对于单独测试 api 调用非常有用。
为什么使用这种方法?
- 提高速度:通过避免实际的网络请求,测试运行得更快、更可靠。
- 简化的测试数据:您可以控制响应,从而更轻松地测试边缘情况和各种应用程序状态。
- api调用验证:通过捕获随请求发送的变量,您可以确保前端使用正确的参数调用后端。
此实现和方法的灵感来自 jay freestone 的优秀博客文章 stubbing graphql requests in playwright。他的帖子为构建拦截gql实用程序提供了坚实的基础。
通过将此实用程序合并到您的 playwright 测试套件中,您可以轻松模拟 graphql 查询和突变,提高测试速度和可靠性,同时简化复杂的场景。









