自动化测试,让你上班拥有一杯咖啡的时间 | Day 6 - 使用 Custom Commands

此系列文章会同步发文到个人部落格,有兴趣的读者可以前往观看喔。

你有没有遇到这种状况,在网站上几乎都需要先登入,才能操作功能,因此测试脚本需要写重复的登入程序码。这时可以把登入当作公共方法,写在 command.js,就能减少重复的程序码了。

custom commands 介绍

custom command 可以自定义 commands 或是 覆写现有的 commands。

语法

Cypress.Commands.add(name, callbackFn)
Cypress.Commands.add(name, options, callbackFn)
Cypress.Commands.overwrite(name, callbackFn)

自定义command

  1. 在执行脚本前,会先跑 cypress/support/commands.js 档案,因此可以在这里写登入的脚本。
    https://ithelp.ithome.com.tw/upload/images/20210920/20140883vdRCMifbz3.png

    Cypress.Commands.add("login", ({ userId, password }) => {
        cy.get('.menu__item-link').contains("登入/注册").click({ force: true });
        cy.get('#account').type(userId, {force: true,});
        cy.get('#password').type(password, {force: true,});
        cy.get(".btn-agree").contains("登入").click({ force: true });
        cy.location("pathname").should("eq", "/");
    });
    
  2. 到测试脚本写上 cy.login

    describe('测试铁人赛登入', function() {
      it('输入正确帐密後应该要可以登入', function() {
        cy.visit('https://member.ithome.com.tw/login') //到登入页
        cy.get('#account').type("jennifershih"); //输入帐号 
        cy.get('#password').type("secret1234567890"); //输入密码
        cy.get('.btn-agree').click({force: true,}); //点选登入
        cy.get(".account-fontsize").contains("jennifershih").should("be.visible"); //要有帐号
        cy.get('li > a').contains("登出").click({force: true,}); //点选登出
      })
    })
    
  3. 执行脚本後,可以看到登入成功,但在 log 上会看到密码。
    https://ithelp.ithome.com.tw/upload/images/20210920/201408833AfWawOh7O.png

覆写 custom commands

当用 cy.type() 时,执行脚本会将输入的内容显示出来,但当输入的内容有机密如密码时,可以覆写 cy.type 的方法。

  1. 以登入为例,在 cypress/support/command.js 加上

    Cypress.Commands.overwrite('type', (originalFn, element, text, options) => {
        if (options && options.sensitive) {
          // turn off original log
          options.log = false
          // create our own log with masked message
          Cypress.log({
            $el: element,
            name: 'type',
            message: '*'.repeat(text.length),
          })
        }
    
        return originalFn(element, text, options)
      })
    
    	cy.get('#account').type("account"); //输入帐号 
        cy.get('#password').type('secret1234567890', { sensitive: true }); //输入密码
    
  2. 执行脚本後,在 log 上这时输入的密码会用********呈现。
    https://ithelp.ithome.com.tw/upload/images/20210920/20140883uN3NakGdFv.png

参考资料


<<:  【Day6】:GPIO输入输出(中)

>>:  资料结构的重要性

[Day 27] Reactive Programming - RSocket

前言 Reactive的世界里,我们已经知道了从接收request(Spring WebFlux)进...

Day 6 - 原型 (5): 帖子页的元件组合

前言 利用刚设计好的帖子页元件, 组合成帖子页。 元件组合 建立一个属於帖子页的frame 先在Pa...

IT 铁人赛 k8s 入门30天 -- day15 k8s Workload 简介

前言 今天要讲的是 k8s 丛集对於 Workload 管理做讲解 Pod 的管理 以下将会解释一些...

Day 25 - Spring Security (二) UserDetailsService

Spring Security 的验证作业实际是交由``AuthenticationProvider...

深度学习模型

LeNet LeNet-5为LeCun大神在1998年所提出的卷积神经网络算法。 卷积类神经网路 1...