使用Playwright自动化测试后端接口

764 阅读2分钟

使用 Playwright 自动化测试后端接口可以通过模拟 HTTP 请求和响应来实现。虽然 Playwright 主要是用于前端浏览器自动化测试,但它也提供了强大的 API 支持,允许你直接测试后端接口。

接下来,我们一步步来实现:

1. 安装Playwright

npm install playwright

2. 使用 Playwright 进行接口测试

我们可以使用 Playwright 提供的 APIRequestContext 来发送 HTTP 请求:

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

test('GET API - Verify countries list length', async () => {
  // 创建 API 请求上下文
  const apiContext = await request.newContext();

  // 发送 GET 请求
  const response = await apiContext.get('https://api.example.com/countries');

  // 断言返回的状态码
  expect(response.status()).toBe(200);

  // 获取返回的 JSON 数据
  const body = await response.json();

  // 断言数据结构和长度
  expect(body.data.countries).toHaveLength(200);
});

我们来解释下这段代码:

  • request.newContext():创建一个新的 API 请求上下文,允许你管理请求的设置、头信息等。

  • apiContext.get('https://api.example.com/countries'):模拟发送一个 GET 请求,获取后端接口的数据。

  • response.status():获取接口响应的状态码,并断言它是 200(即成功响应)。

  • response.json():将响应的 JSON 数据解析成 JavaScript 对象。

  • expect(body.data.countries).toHaveLength(200):断言 body.data.countries 的数组长度为 200。

3. 发送其他类型的 HTTP 请求

除了Get请求,Playwright 还支持 POSTPUTDELETE 等请求类型。就像这样:

POST请求:

test('POST API - Create new country', async () => {
  const apiContext = await request.newContext();

  const response = await apiContext.post('https://api.example.com/countries', {
    data: {
      name: 'New Country',
      code: 'NC'
    }
  });

  expect(response.status()).toBe(201);  // 判断是否成功创建
  const body = await response.json();
  expect(body.data.name).toBe('New Country');
});

PUT请求:

test('PUT API - Update country', async () => {
  const apiContext = await request.newContext();

  const response = await apiContext.put('https://api.example.com/countries/NC', {
    data: {
      name: 'Updated Country'
    }
  });

  expect(response.status()).toBe(200);
  const body = await response.json();
  expect(body.data.name).toBe('Updated Country');
});

DELETE 请求示例
test('DELETE API - Delete country', async () => {
  const apiContext = await request.newContext();

  const response = await apiContext.delete('https://api.example.com/countries/NC');

  expect(response.status()).toBe(204);  // 判断删除是否成功
});

4. 进行身份验证

在我们实际开发中,ajax接口请求大多都是要带身份验证信息的,这一点,Playwright也是支持的,我们可以使用Authorization Header来实现:

test('GET API with Auth', async () => {
  const apiContext = await request.newContext({
    headers: {
      'Authorization': 'Bearer YOUR_TOKEN_HERE'
    }
  });

  const response = await apiContext.get('https://api.example.com/protected-resource');
  expect(response.status()).toBe(200);
});

我们也可以使用Cookie注入的方式来实现登录,就像这样:

    const browser = await chromium.launch({});
    const context = await browser.newContext(contextConfig);
    const page = await context.newPage();
    // cookie 就是我们的登录cookie信息
    await page.context().addCookies(cookie);

验证结果:

最后,我们可以运行下面这个命令来验证结果:

npx playwright test

总结

通过 Playwright,我们可以轻松地模拟 HTTP 请求,测试后端接口,断言响应的内容和状态码。尽管 Playwright 的主要用途是浏览器自动化,但其强大的 APIRequestContext 使得后端接口测试也变得非常简便。