2.6 万 Star!Web 已进化,前端测试工具也该变了

【导语】:Cypress 是为现代网络而构建的下一代前端测试工具,用于解决开发者和测试工程师在测试现代应用程序时面临的难题。

简介

Cypress简化了设置测试、编写测试、运行测试和调试测试的过程,支持端到端测试、集成测试、单元测试,可以对浏览器中运行的所有内容进行快速、轻松、可靠的测试。,支持Mac、Linux、Windows平台。

cypress 官网截图

Cypress支持以下功能:

1、 历史记录。测试后可以在Test Runner中查看运行时的历史记录

2、 实时重新加载

3、 支持单元测试

4、 运行结果一致性

5、 可使用开发者工具进行性调试

6、 支持异步操作

7、 支持Mock

8、 自动截图和录制视频

项目地址:

https://github.com/cypress-io/cypress

下载安装

1、 使用npm安装

npm install cypress --save-dev

2、 使用yarn安装

yarn add cypress –dev

3、 启动。安装完成后,进入安装目录,执行以下命令即可启动:

cypress open

简单使用

下面使用一个简单例子演示如何使用cypress。

1、 访问页面。使用脚本打开一个页面,通过cy.visit来传递访问的url,创建一个js文件,输入以下内容。

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

保存文件后,Cypress会自动加载执行脚本,并运行输出测试结果。上述代码没有断言,测试结果也是通过的。

2、 查询页面元素。通过脚本查询页面上某个元素,将脚本修改为如下:

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

此时运行时通过的,因为页面上包含type元素。如果找不到对应的元素,测试结果则会是失败。而且Cypress在失败后会自动等待并重试。

3、 点击一个元素。查找到某个元素后,执行点击动作,使用.click方法。

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

4、 使用断言。对单击的新页面上的内容进行断言,确保新的URL是预期的URL,使用.should方法。

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')
  })
})

5、 添加更多的命令和断言。下面的代码,使用get进行CSS类选择元素,然后使用type在选定的输入中输入文本,最后使用should判断元素值是否包含目标文本。

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('[email protected]')
      .should('have.value', '[email protected]')
  })
})

6、 特殊的调试命令,如pause,类似调试器,可以用来逐步执行每个命令。

describe('My First Test', () => {
  it('clicking "type" shows the right headings', () => {
    cy.visit('https://example.cypress.io')
    cy.pause()
    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('[email protected]')
      .should('have.value', '[email protected]')
  })
})

小结

Cypress是自集成的,无需借助其他外部工具,允许编写所有类型的测试,其背后是Node的Process控制的Proxy进行转发,因此Cypress不仅可以修改进出浏览器的内容,还可以更改可能影响自动化操作的代码,相比其他测试工具来说,可以从根本上控制整个自动化测试的流程。

开源前哨 日常分享热门、有趣和实用的开源项目。参与维护 10万+ Star 的开源技术资源库,包括:Python、Java、C/C++、Go、JS、CSS、Node.js、PHP、.NET 等。

你可能感兴趣的:(2.6 万 Star!Web 已进化,前端测试工具也该变了)