【问题标题】:Cypress - import and export functionsCypress - 导入和导出功能
【发布时间】:2021-11-29 11:17:56
【问题描述】:

如何更好地组织我的 cypress 代码进行测试,以便我只需要导入一些函数?

我想首先创建一个用于在页面上进行身份验证的文件,然后我想将它导入到具有多个功能的测试中。

我尝试了以下导出代码,但似乎不正确,出现错误:

export function login() {
    cy.visit('https://*********')
    cy.get('input[name="Parameter.UserName"]').type('*****')
    cy.get('input[name="Parameter.Password"]').type('*****')
    cy.contains('Login').click()

}

export default {login};

在测试中:

import {login} from 'elements/pages/login.js'

【问题讨论】:

    标签: javascript function automation cypress


    【解决方案1】:

    您的导入需要一个相对 URL

    import {login} from '../elements/pages/login.js'  // relative from cypress/integration
    

    或者如果在cypress/suport/elements

    import {login} from '../support/elements/pages/login.js'  
    

    绝对导入(其中路径没有前导 ./ 或 ../)被假定为 node_modules 中的库包。

    【讨论】:

      【解决方案2】:

      赛普拉斯为此提供了一种称为自定义命令的东西,您可以阅读here

      转到cypress/support/commands.js 并在此处编写所有代码,例如:

      Cypress.Commands.add('login', () => {
        cy.visit('https://*********')
        cy.get('input[name="Parameter.UserName"]').type('*****')
        cy.get('input[name="Parameter.Password"]').type('*****')
        cy.contains('Login').click()
      })
      

      然后在你的任何一个测试中,你可以直接添加:

      cy.login()
      

      【讨论】:

      • 太好了,谢谢!有什么方法可以不将所有命令放在 commands.js 中,并以某种方式将它们组织在页面上(例如带有一些命令的日历页面、带有其他命令的设置页面、带有其他命令的预订页面)?
      • 是的,有办法。您可以在项目内的任何位置创建单独的 js 文件,然后将文件路径添加到 cypress/support/index.js 例如。假设我在integration/utils 文件夹中有一个文件login.js ,我需要做的就是在cypress/support/index.js 文件中添加import '../integration/utils/login.js',它就会起作用。
      • 如果我有“Cypress.Commands.add('login', () => { })”,我可以在这个测试中加入几个步骤吗?我的意思是几个步骤,每个步骤都有描述
      【解决方案3】:

      在测试内容中必须执行所有cys,也许你可以这样尝试:

      export default {
      
          // props
          visit: (url)=> { return cy.visit(url) }
          get: (el)=> { return cy.get(el) }
      
          // methods
          login(){
            cy.visit('https://*********')
            cy.get('input[name="Parameter.UserName"]').type('*****')
            cy.get('input[name="Parameter.Password"]').type('*****')
            cy.contains('Login').click()
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-19
        • 2017-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-19
        • 1970-01-01
        • 1970-01-01
        • 2018-02-24
        相关资源
        最近更新 更多