首页 > 解决方案 > 如何在另一个 spec.js 中重用代码?

问题描述

我有两个必须由第三个调用的测试脚本。我不想为所有使用相同两个脚本并在之后做许多其他事情的测试用例复制代码。

我尝试使用require命令,但它似乎被忽略了,并且执行后的代码跳过了预期的脚本AbrirNavegador.spec.js

before(function() {require('./AbrirNavegador.spec.js')});

没有关于错误或其他信息的信息。它只是被跳过了。

标签: cypress

解决方案


我从来没有让它工作。但我确实使用了另一种解决方法。我所做的:

// commands.js
Cypress.Commands.add('reuseMethod1', function({
  // first set of steps that need to be reused
})
Cypress.Commands.add('reuseMethod2', function({
  // second set of steps that need to be reused
})
// testscript_1.js
cy.reuseMethod1()
// testscript_2.js
cy.reuseMethod1()
cy.reuseMethod2()

您可以在任何地方调用这些方法,也可以在 before/beforeEach/after/afterEach 中调用。因此,您拥有的唯一代码重复是调用该方法的部分。


推荐阅读