前端测试工具

136 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 27 天,点击查看活动详情

Cypress 是一个为现代网络而构建的下一代前端测试工具。
Cypress 简化了设置测试、编写测试、运行测试和调试测试的过程,支持端到端测试、集成测试、单元测试,可以对浏览器中运行的所有内容进行快速、轻松、可靠的测试。

1、Cypress 特点

  1. 基于 node.js 环境的 E2E 前端自动化测试框架
  2. 支持 Chrome 和 Firefox 浏览器,自动等待
  3. 不用 web driver 驱动浏览器,运行速度快
  4. 支持失败用例自动截屏
  5. 对运行过程的自动录制视频
  6. 时光穿梭看各步骤的snapshoot
  7. 支持 CI 和并发运行,收集测试结果
  8. 支持 Junit+Allure 生成测试报告
  9. 支持 Mac、Linux、Windows 平台

2、安装 Cypress

安装 node.js 之后,运行命令安装 Cypress

$ npm install cypress --save-dev

启动待测服务/应用

$ npm start & wait-on http://localhost:8080

启动 Cypress Test Runner

$ npx cypress open

运行指定用例,使用 Chrome 浏览器

$ npx cypress run --spec "cypress/integration/login.js" --browser chrome

3、编写第一个测试

添加测试文件

  1. 创建一个 sample_spec.js 文件。
  2. 观看 Cypress 更新我们的规格列表。
  3. 启动

让 cypress/integration 在创建的文件夹中创建一个新文件:

touch {your_project}/cypress/integration/sample_spec.js

创建该文件后,应该会看到 Cypress Test Runner 立即将其显示 在 Integration Tests 列表中。
可以单击 sample_spec.js 启动浏览器。

开始写第一个通过测试

访问一个网页

可以传递要访问的 URL cy.visit()。用下面实际访问页面的测试替换之前的测试:

describe('My First Test', () => {
  it('Visits the Kitchen Sink', () => {
    cy.visit('https://example.cypress.io')
  })
})

保存文件后,Cypress 会自动加载执行脚本,并运行输出测试结果。
现在已经加载了页面,需要对其执行一些操作

查询页面元素

describe('My First Test', () => {
  it('finds the content "type"', () => {
    cy.visit('https://example.cypress.io')

    cy.contains('type')
  })
})

此时运行时通过的,因为页面上包含 type 元素。即使没有添加断言,也会有默认断言。如果找不到对应的元素,测试结果则会是失败。

点击一个元素

现在要单击找到的链接。该怎么做?将.click()命令添加到上一个命令的末尾,如下所示:

describe('My First Test', () => {
  it('clicks the link "type"', () => {
    cy.visit('https://example.cypress.io')

    cy.contains('type').click()
  })
})

提出断言

对单击的新页面上的内容进行断言。

describe('My First Test', () => {
  it('clicking "type" navigates to a new url', () => {
    cy.visit('https://example.cypress.io')

    cy.contains('type').click()

    // Should be on a new URL which includes '/commands/actions'
    cy.url().should('include', '/commands/actions')
  })
})

特殊的调试命令

如pause,类似调试器,可以用来逐步执行每个命令

describe('My First Test', () => {
  it('Gets, types and asserts', () => {
    cy.visit('https://example.cypress.io')
    cy.contains('type').click()
    // Should be on a new URL which includes '/commands/actions'
    cy.url().should('include', '/commands/actions')
    // Get an input, type into it and verify that the value has been updated
    cy.get('.action-email')
      .type('fake@email.com')
      .should('have.value', 'fake@email.com')
  })
})

GitHub网址:github.com/cypress-io/…
官方文档:docs.cypress.io/guides/gett…