返回

Cypress 基于 React 应用端对端测试

前端

搭建 Cypress:

  1. 安装 Cypress:打开命令行窗口并输入 "npm install cypress --save-dev"。
  2. 在项目中初始化 Cypress:运行 "npx cypress open",这将在项目目录中创建一个 "cypress" 文件夹。
  3. 创建第一个测试:在 cypress/integration 文件夹中创建一个名为 "first-test.js" 的文件,并输入以下代码:
describe('My First Test', () => {
  it('should visit the home page', () => {
    cy.visit('http://localhost:3000');
  });
});
  1. 运行测试:打开命令行窗口并输入 "npx cypress run"。这将在浏览器中启动 Cypress 测试运行器,并自动运行你的第一个测试。

集成 Cypress 与 React:

  1. 安装必要的依赖:输入 "npm install @cypress/react --save-dev",将 Cypress React 集成到你的项目中。
  2. 配置 Cypress:打开 cypress.json 文件,添加 "component":{ "supportFile": "cypress/support/component.js" } 行。
  3. 在 cypress/support/component.js 中添加以下代码:
import React from 'react';

function mountComponent(component) {
  const root = document.createElement('div');
  document.body.appendChild(root);
  ReactDOM.render(component, root);
  return root;
}

function unmountComponent(root) {
  ReactDOM.unmountComponentAtNode(root);
  root.parentNode.removeChild(root);
}

Cypress.Commands.add('mount', component => {
  cy.wrap(mountComponent(component));
});

Cypress.Commands.add('unmount', root => {
  cy.wrap(unmountComponent(root));
});
  1. 现在,你可以在测试中使用这些命令来挂载和卸载 React 组件。

自动化端对端测试:

  1. 编写测试用例:在 cypress/integration 文件夹中创建测试文件,并在每个测试用例中使用 Cypress 命令来验证应用的行为。
  2. 运行测试:打开命令行窗口并输入 "npx cypress run",即可运行所有测试用例。

Cypress 与 TDD:

  1. 在开发过程中持续编写测试用例,以确保在添加新功能时不会破坏现有功能。
  2. 使用 Cypress 的 "watch" 模式来在每次更改后自动运行测试。
  3. Cypress 集成到持续集成 (CI) 系统中,以便在每次代码提交时自动运行测试。

总结:

通过 Cypress,你能够编写自动化端对端测试来验证 React 应用的行为。它提供了简单易用的 API,并与 TDD 和 CI 系统良好集成。这使得 Cypress 成为构建可靠且可维护的 React 应用的宝贵工具。