You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现可复用的Cypress部门选择测试函数?

问题描述

我正在为登录场景创建可复用的Cypress测试函数,用户注册时需选择单个部门来定制内容。目前我已在teamSelector.js中定义了部门列表(JSON格式),但当前函数固定选择第一个选项。我希望改造该函数,不在其中指定索引,而是在loginTest.js中调用时,能从JSON的部门ID中指定任意选项,如何实现?


现有代码

loginTest.js

import emailSignup from './emailsignup'
import teamSelector from './teamSelector'

{/* <reference types = "cypress" /> */}
const {commands} = require('../support/commands')

const { Input } = require("@angular/core")
const { wrap } = require("module")
const { isExportSpecifier } = require("typescript")


describe('our first suite', () => {

    const signup = new emailSignup()
    const signindepartment = new teamSelector()

    it('first test', () => {
        cy.visit('/')
        signup.signupforfreelink().click()
        // cy.get('a[data-tracking-name="Sign up for free"]').click()
        cy.get('.flex').should('contain',"Create your free account")
        cy.get('[for="emailSignup"]').should('contain',"Work email")
        signup.email()
        signup.continuebtn()
        signup.firstandlastname()
        signup.password()
        signup.signInButton()
        signup.alertsignup()
        signup.closealert()
        signindepartment.loginselectors()
})
})

teamSelector.js

class teamSelector {
loginselectors() {
return cy.get('.flex').find('[type="checkbox"]').then(userselection => {
    // const department = {
    //         "mar": "Marketing",
    //         "prod": "Product & Design",
    //         "eng": "Engineering",
    //         "supp": "IT & Support",
    //         "oper": "Operations",
    //         "acctmgnt": "Sales & Account Mgmt.",
    //         "hr": "HR & Legal",
    //         "creative": "Creative Production",
    //         "customerservice": "Customer Service",
    //         "fin": "Finance",
    //         "manfact":"Manufacturing",
    //         "other": "Other / Personal"
    //      }
    cy.wrap(userselection)
    .first()
    .check({force:true})
    .should('be.checked')
})
}
}
export default teamSelector

实现方案

步骤1:重构teamSelector.js

  1. 把部门列表JSON作为类的静态属性,方便维护和调用
  2. 修改loginselectors方法,新增部门ID参数用于指定选择项
  3. 根据传入的ID匹配对应的部门,定位到目标复选框完成选择

修改后的teamSelector.js代码:

class teamSelector {
  // 定义部门映射关系,作为类静态属性统一维护
  static departments = {
    "mar": "Marketing",
    "prod": "Product & Design",
    "eng": "Engineering",
    "supp": "IT & Support",
    "oper": "Operations",
    "acctmgnt": "Sales & Account Mgmt.",
    "hr": "HR & Legal",
    "creative": "Creative Production",
    "customerservice": "Customer Service",
    "fin": "Finance",
    "manfact":"Manufacturing",
    "other": "Other / Personal"
  };

  loginselectors(deptId) {
    // 校验传入的部门ID是否有效,无效则抛出提示
    if (!deptId || !teamSelector.departments[deptId]) {
      throw new Error(`无效部门ID: ${deptId},可选ID列表:${Object.keys(teamSelector.departments).join(', ')}`);
    }

    const targetDept = teamSelector.departments[deptId];
    // 通过部门文本定位复选框(需根据实际DOM结构调整,示例为文本的父元素下找复选框)
    return cy.get('.flex')
      .contains(targetDept)
      .parent()
      .find('[type="checkbox"]')
      .check({force:true})
      .should('be.checked');
  }
}
export default teamSelector

优化提示:如果复选框自带对应部门ID的属性(比如data-dept-id),可以直接通过属性定位,效率更高:

return cy.get(`.flex [type="checkbox"][data-dept-id="${deptId}"]`)
  .check({force:true})
  .should('be.checked');

步骤2:在loginTest.js中指定部门调用

修改测试用例,调用loginselectors时传入目标部门ID即可:

import emailSignup from './emailsignup'
import teamSelector from './teamSelector'

{/* <reference types = "cypress" /> */}
const {commands} = require('../support/commands')

const { Input } = require("@angular/core")
const { wrap } = require("module")
const { isExportSpecifier } = require("typescript")


describe('our first suite', () => {

    const signup = new emailSignup()
    const signindepartment = new teamSelector()

    it('first test - select Engineering department', () => {
        cy.visit('/')
        signup.signupforfreelink().click()
        cy.get('.flex').should('contain',"Create your free account")
        cy.get('[for="emailSignup"]').should('contain',"Work email")
        signup.email()
        signup.continuebtn()
        signup.firstandlastname()
        signup.password()
        signup.signInButton()
        signup.alertsignup()
        signup.closealert()
        // 传入部门ID "eng",选择Engineering部门
        signindepartment.loginselectors("eng")
    })

    // 新增测试用例,验证不同部门选择逻辑
    it('second test - select Marketing department', () => {
        cy.visit('/')
        // ... 省略重复注册步骤
        signindepartment.loginselectors("mar")
    })
})

内容的提问来源于stack exchange,提问作者user2744620

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 21:40:16