5分钟学习Cypress

本文的主线 定义 => 安装 => 开发 (API Test & Web Test) => 部署

定义

Cypress是什么?

  • Cypress是一个简单、高效且全能的Web测试框架

安装

首先 安装Node环境

1
2
3
4
5
6
7
node -v
# v14.17.3

npm i -g cnpm --registry=https://registry.npm.taobao.org

cnpm -v
# cnpm@7.0.0

然后 安装Cypress

1
2
3
mkdir hello-cypress && cd hello-cypress

cnpm i --save-dev cypress

最后 启动Cypress并初始化项目如下图

1
npx cypress open

learn-cypress-in-5-minutes-01.png

自带示例测试用例可以尝试运行

开发

API Test

1
vim cypress/integration/api.spec.js
1
2
3
4
5
6
7
8
9
10
11
/// <reference types="Cypress" />

context('API', () => {
it('api test', () => {
cy.request('POST', 'https://login-api.zhgcloud.com/web/login-platform', {
platform_unique_key: 'hello', platform_password: 'world'
}).then((res) => {
expect(res.status).to.eq(200)
})
})
})
1
2
# 只运行cypress/integration/api.spec.js 否则会执行所有
npx cypress run --spec cypress/integration/api.spec.js

输出测试报告如下

learn-cypress-in-5-minutes-02.png

Web Test

1
vim cypress/integration/web.spec.js
1
2
3
4
5
6
7
8
9
10
11
/// <reference types="Cypress" />

context('Web', () => {
beforeEach(() => {
cy.visit('https://www.gongchengbing.com/')
})

it('web test', () => {
cy.get('.demand-list-body').should('have.length', 5)
})
})
1
2
# 只运行cypress/integration/web.spec.js 否则会执行所有
npx cypress run --spec cypress/integration/web.spec.js

输出测试报告如下

learn-cypress-in-5-minutes-03.png

部署

基于Ubuntu 1804 Server

首先 安装相关依赖包

1
2
# 参考官方文档 Installing Cypress https://docs.cypress.io/guides/getting-started/installing-cypress#System-requirements
sudo apt install -y libgtk2.0-0 libgtk-3-0 libgbm-dev libnotify-dev libgconf-2-4 libnss3 libxss1 libasound2 libxtst6 xauth xvfb

然后 验证Cypress运行环境

1
2
npx cypress verify
# ✔ Verified Cypress!

最后 运行Cypress

1
npx cypress run