Cypress前端测试框架使用教程

Cypress前端测试框架使用教程

一、简介

cypress是即end to end(端到端)功能测试框架,它基于node js,Jquery。开箱即用,不仅支持本地浏览器直接模拟测试,也支持终端测试。还有测试录屏功能,方便在测试失败的时候,查看当时的失败的场景,方便定位。

二、安装

通过npm来安装Cypress

npm install cypress --save-dev

直接下载Cypress压缩包

https://download.cypress.io

三、使用

项目中使用

在项目中,执行npm install cypress --save-dev安装。
在package.json中加入
"cypress": "cypress run","cypress-gui": "cypress open"
快捷执行方式。
在项目根目录下增加配置文件cypress.json。

{    "baseUrl": "http://localhost:8080", // 测试域名,这里可具体项目更改
    "integrationFolder": "cypress/integration", // 测试文件存放目录
    "testFiles": "**/*.cypress.spec.js", // 根据规则匹配具体测试文件,可根据喜好任意更改
    "videoRecording": false, // 是否使用录制功能 需要的话具体去看官方介绍就好,这边暂时用不上
    "viewportHeight": 800, // 测试浏览器视口高度
    "viewportWidth": 1600 // 测试浏览器视口宽度
}

在 package.json 文件添加对应启动脚本:

"scripts": {
   "cypress:open": "cypress open",
   "cy:run": "node scripts/cypress.js"
 }

在根目录中的cypress/integration中创建js执行脚本后。
启动执行:
npm run cy:run

// cypress/integration/test.cypress.test.js
describe('测试', () => {    // 测试用例触发前调用的函数钩子
    before(() => {        // 进入测试页面
        cy.visit('/');
    });

    it('测试是否包含指定文案', () => {
        cy.contains('Hello cypress');
    });
    
    it('获取指定元素', () => {
        cy.get('.test').contains('我是');
    }); 
    
    it('代理本地请求并修改成任意数据', () => {
        cy.server();        // 拦截/api/user请求并传入自定义数据
        cy.route('/api/user', {user: 'frank'}).as('user');
        cy.visit('/');
    });
    
    it('代理本地请求并使用mock数据', () => {
        cy.server();        // 请求本地 cypress/fixtrues/user.json文件(需要先创建) then方法可修改成任意数据,若不需要修改可不写
        cy.fixture('/user.json').then(data => data).as('fix_user');        // 拦截/api/user请求并传入mock数据
        cy.route('/api/user', '@fix_user').as('user');
        cy.visit('/');
    });
});

提取登录

使用request 请求进行登录
cypress 推荐在每个用例的登录步骤,不调用 UI ,直接使用 request 登录。下面是一个例子:

describe('My first test case for cypress',function(){
    it('login as admin without UI:',function(){
        const accountTypes = {   // 设置账号类型
            admin:{
                account:'admin',
                password:'123456'
            }
        }

        cy.request({
            url:'http://yourhost/login',
            method:'POST',
            form:true,
            body:accountTypes['admin']      // 使用 admin 账号登录(跳过 UI 的登录)
        })
        cy.visit('/profile')
        cy.url().should('include','profile')     //验证目标url 是否正确
        cy.get('#headerTitle')
        .should('have.text','个人信息')   // 验证是否包含标题 个人信息, 
    })
})

提取登录方法为公共方法

Cypress.Commands.add('login', (userType, options = {}) => {
        const accountTypes = {   // 设置账号类型
            admin:{
                account:'admin',
                password:'123'
            }
        }

        cy.request({
            url:'http://yourhost/login',
            method:'POST',
            form:true,
            body:accountTypes[userType]      // 使用 admin 账号登录
        })
    })

describe('login with different account',function(){
    beforeEach(function() {
        cy.login('admin')
        cy.visit('/')
    })

    it('进入商品列表页面',function(){

        cy.contains('商品列表').click()
        cy.get('#headerTitle')
        .should('have.text','商品列表')   // 验证是否包含标题 商品列表
    })

    it('进入订单列表页面',function(){
        cy.contains('订单列表').click()
        cy.get('#headerTitle')
        .should('have.text','订单列表')   // 验证是否包含标题 订单列表
    })
})

单独使用

创建文件夹,在文件夹下执行
npm install cypress --save-dev
./node_modules/.bin/cypress open启动Cypress

describe('My first test case for cypress',function(){
    it('visit baidu home page and search for testerhome:',function(){
        cy.visit('http://www.baidu.com') //访问url
        cy.title().should('contain','百度一下,你就知道')   //验证页面 title 是否正确
        cy.get('#kw')      //根据 css 定位搜索输入框
         .type('testerhome')        //输入关键字
        .should('have.value','testerhome')  //验证关键字自动是否展示正确
        cy.get('#su').click()   //根据 css 定位搜索按钮并点击
        cy.url().should('include','wd=testerhome')     //验证目标url 是否正确包含关键字
        cy.title().should('contain','testerhome_百度搜索')  //验证页面 title 是否正确
        cy.get('[id="1"]')   
        .should('contain','TesterHome')   // 验证第一个结果中是否包含TesterHome
        cy.screenshot()
    })
})

四、生成报告

生成Junit-allure报表

在 cypress.json 中添加依赖:

"reporter": "junit",
"reporterOptions": {
  "mochaFile": "results/my-test-output[hash].xml",   // 通过hash 标签区分不同文件的用例结果
  "toConsole": true
}

执行 cypress run 的时候会自动生成xml文件
使用 allure 生成对应报告:

// 生成allure 报告
allure generate results --clean

// 打开报告
allure open allure-report

生成 mocha awsome 报告

安装对应模块:
注意: mocha 必须指定 5.2.0, 否则会报错

npm install --save-dev [email protected] mochawesome mochawesome-merge mochawesome-report-generator
配置cypress 对应报告信息 cypress.json:

"reporter": "mochawesome",
"reporterOptions": {
  "overwrite": false,
  "html": false,
  "json": true
},

编写执行测试和生成报告的脚本:
scripts\cypress.js

const cypress = require('cypress')
const fse = require('fs-extra')
const { merge } = require('mochawesome-merge')
const generator = require('mochawesome-report-generator')

async function runTests() {
  await fse.remove('mochawesome-report')
  const { totalFailed } = await cypress.run()
  const jsonReport = await merge()
  await generator.create(jsonReport)
  process.exit(totalFailed)
}

runTests()

查看报告:
mochawesome-report\mochawesome.html

参考文档:

http://www.likecs.com/show-60344.html

https://www.imooc.com/article/details/id/28054

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章