Cypress自動化框架筆記


Cypress的特點

1. 基於node.js環境的E2E前端自動化測試框架
2. 支持Chrome和Firefox瀏覽器,自動等待
3. 不用web driver驅動瀏覽器,運行速度快
4. 支持失敗用例自動截屏
5. 對運行過程的自動錄制視頻
6. 時光穿梭看各步驟的snapshoot
7. 支持CI和並發運行,收集測試結果
8. 支持Junit+Allure生成測試報告

 

安裝和使用

安裝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

 

演示用例 login.js

//用例集
describe('UI loginTest',function(){   
    //用例
    it('console root login',function(){   
        //打開頁面
        cy.visit('http://localhost:8080/rootlogin')
        cy.url().should('contain','randomKey')
        //輸入用戶,密碼,點擊登錄
        cy.get('[name=username]').type('root')
            .should('have.value','root')
        cy.get('[name=password]').type('password')
            .should('have.value','password')
        cy.get('.el-button').click()
        //登錄后進入頁面
        cy.title().should('contain','系統管理員')
        cy.wait(1000)
        //登出
        cy.contains('root').click()
        cy.contains("退出登錄").click()
        cy.url().should('contain','randomKey')
    })
    
    it('console user login', function(){
        // user login test 
    })
})

元素定位方式

cy.get() - 按CSS或元素特定屬性進行定位,累JQuery selection

cy.contains() - 按特定字符串匹配進行元素定位

cy.xpath() - 按XPATH進行定位,需安裝 cypress-xpath:

  1) npm install cypress-xpath --save-dev

  2) 在cypress/support/index.js 中添加: require('cypress-xpath')

 

頁面操作

 

HOOK 鈎子示例

describe('Hooks', () => {
  before(() => {
      // runs once before all tests in the block
      cy.log("所有的用例之前只執行一次,測試准備工作")
  })
  after(() => {
      // runs once after all tests in the block
      cy.log("所有的用例之后只執行一次")
  })
  beforeEach(() => {
      // runs before each test in the block
      cy.log("每個用例之前都會執行")
  })
  afterEach(() => {
      // runs after each test in the block
      cy.log("每個用例之后都會執行")
  })
  it('test case 1', () => {
      cy.log("test case 1")
      expect(true).to.eq(true)
  })
  it('test case 2', () => {
      cy.log("test case 2")
      expect(true).to.eq(true)
  })
})

 

測試數據准備

describe('The Dashboard Page', () => {
  beforeEach(() => {
    // reset and seed the database prior to every test
    // seed a user in the DB that we can control from our tests
    cy.exec('npm run db:reset && npm run db:seed')
    cy.request('POST', '/test/seed/user', { username: 'jane.lane' })
      .its('body')
      .as('currentUser')
  })

it('logs in programmatically without using the UI', function () {
    // destructuring assignment of the this.currentUser object
    const { username, password } = this.currentUser
    // programmatically log us in without needing the UI
    cy.request('POST', '/login', {
      username,
      password
    })
    // now that we're logged in, we can visit
    // any kind of restricted route!
    cy.visit('/dashboard')
   // our auth cookie should be present
    cy.getCookie('your-session-cookie').should('exist')
   // UI should reflect this user being logged in
    cy.get('h1').should('contain', 'jane.lane')
  })
})

 

參數化

describe('參數化案例,輸入不同的值', function() {
    // 定義測試數據
    var testdatas = ["北京", "上海", "南京"]
    // 前置-打開瀏覽器
    before(() => {
          cy.visit('https://www.baidu.com')
        })
    // 參數化
    testdatas.forEach((event) => {
        it("百度輸入框功能", function () {
            cy.get('#kw').type(event)
                .should('have.value', event)
                .clear()
                .should('have.value', '')
        })
    })
})

 

Fixture文件讀取測試數據

把賬號和密碼放login.json文件,

{
  "username": "admin",
  "password": "password",
  "include": "/test/my/",
  "text": "測試"
}

用login.json中的fixture數據登錄網頁

describe('登陸網站', function() {
    beforeEach(() => {
          cy.visit('http://ip:8080/login');
          cy.fixture('login.json').as('login')
        })

    it("登陸案例", function (){
        cy.log("讀取login.json文件賬號:"+this.login.username)
        cy.log("讀取login.json文件密碼:"+this.login.password)
        // let 定義變量
        let username = this.login.username
        let password = this.login.password
        let include = this.login.include
        let text = this.login.text

        //輸入用戶名
        cy.get('#account').type(username)
              .should('have.value', username)
        // 輸入密碼
        cy.get('[name="password"]').type(password)
              .should('have.value', password)
        // 提交表單
        cy.get('#submit').click()
        // 判斷頁面跳轉
        cy.url().should('include', include)
        cy.get('body').should('contain', text)
    })
})

 

多個用例共享Cookie

describe('Dashboard', () => {
    before (() => {
        cy.login()     // log in only once before any of the tests run.
    })
    
    beforeEach (() => {
        Cypress.Cookies.preserveOnce('session_id', 'remember_token')
    })
    
    it('displays stats', () => {
        // ...
    })
    
    it('can do something', () => {
        // ...
    })
})

 

JUnit/Allure產生測試報告

在cypress.json中添加配置, [hash]使得每個測試集產生自己的測試結果xml文件(否則會被覆蓋):

{
  "reporter": "junit",
  "reporterOptions": {
    "mochaFile": "results/test_report_[hash].xml", 
    "toConsole": true
  }
}

執行用例

$ npx cypress run

產生報告

$ allure generate ./result/ -o ./report/ --clean

 

關閉Chrome跨域檢查

在cypress.json中加入如下配置:

{
    "chromeWebSecurity": false,  
}

 

重跑失敗用例的插件

Cypress Test Runner上單跑或跳過某個用例
https://github.com/bahmutov/cypress-skip-and-only-ui

 

重跑失敗的用例
https://github.com/Bkucera/cypress-plugin-retries

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM