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

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