Skip to main content
Cypress应用

模块API

您可以从被测应用程序中将Cypress作为Node模块引入,并通过Node.js运行Cypress。这在您希望运行后直接访问测试结果时非常有用。例如,通过此工作流您可以:

  • 发送包含截图图像的失败测试通知
  • 重新运行单个失败的测试文件
  • 触发其他构建或脚本
info
Yarn Plug'n'Play

Yarn Plug'n'Play环境中通过Node.js运行Cypress时,请使用yarn node代替node

cypress.run()

通过Node.js运行Cypress测试并解析所有测试结果。参见Cypress模块API示例

// e2e-run-tests.js
const cypress = require('cypress')

cypress.run({
reporter: 'junit',
browser: 'chrome',
config: {
baseUrl: 'http://localhost:8080',
video: true,
},
env: {
login_url: '/login',
products_url: '/products',
},
})

然后您可以通过在终端或npm脚本中运行以下命令来执行Cypress:

node e2e-run-tests.js

选项

cypress run命令行选项类似,您可以传递修改Cypress运行方式的选项。

选项类型描述
autoCancelAfterFailuresnumber | false指定记录到云端的运行在失败次数达到该值时自动取消,或false禁用自动取消。
browserstring指定运行测试的不同浏览器,可以是名称或文件系统路径
ciBuildIdstring为运行指定唯一标识符以启用分组并行化
configobject指定配置
configFilestring要使用的配置文件路径。
envobject指定环境变量
groupstring将记录的测试分组到单个运行下
headedboolean显示浏览器而不是无头运行
headlessboolean隐藏浏览器而不是有头运行(cypress run期间默认)
keystring指定您的秘密记录密钥
exitboolean是否在所有测试运行后关闭Cypress
parallelboolean在多台机器上并行运行记录的测试
portnumber覆盖默认端口
projectstring特定项目的路径
quietboolean如果传递,Cypress输出将不会打印到stdout。仅打印配置的Mocha报告器的输出。
recordboolean是否记录测试运行
reporterstring指定Mocha报告器
reporterOptionsobject指定Mocha报告器选项
runnerUiboolean是否显示Cypress Runner UI。当Test Replay启用时默认为false。否则默认为true
slowTestThresholdnumbercypress run期间认为测试"慢"的时间(毫秒)。慢测试将在默认报告器中显示为橙色文本。
specstring指定要运行的测试,参见下面的示例
tagstring使用一个或多个标签标识运行
testingTypestring指定要执行的测试类型;e2ecomponent。默认为e2e

示例

运行单个测试文件

这是一个以编程方式运行测试文件的示例。注意文件路径是相对于当前工作目录的。

// e2e-run-tests.js
const cypress = require('cypress')

cypress
.run({
// 路径相对于当前工作目录
spec: './cypress/e2e/examples/actions.cy.js',
})
.then((results) => {
console.log(results)
})
.catch((err) => {
console.error(err)
})

然后您可以通过在终端或npm脚本中运行以下命令来执行Cypress:

node e2e-run-tests.js

使用通配符运行测试

您可以传递通配符模式来运行所有匹配的测试文件

const cypress = require('cypress')

cypress.run({
// 通配符路径相对于当前工作目录
spec: './cypress/e2e/**/api*.js',
})

以编程方式控制运行的浏览器

您可以传递浏览器选项来指定在哪个浏览器中运行测试,从而以编程方式控制每个浏览器中运行哪些测试。

// 运行 'node cypress-chrome.js'
const cypress = require('cypress')

cypress.run({
spec: './cypress/e2e/**/chrome-test*.js',
browser: 'chrome',
})
// 运行 'node cypress-firefox.js'
const cypress = require('cypress')

cypress.run({
spec: './cypress/e2e/**/firefox-test*.js',
browser: 'firefox',
})

使用现代语法

如果您的Node版本允许,您可以使用现代的async / await语法来等待cypress.run方法返回的Promise。

const cypress = require('cypress')

;(async () => {
const results = await cypress.run()
// 使用结果对象
})()

结果

cypress.run()返回一个Promise,解析为包含测试结果的对象。典型的运行可能返回如下内容:

{
"cypressVersion": "3.0.2",
"endedTestsAt": "2018-07-11T17:53:35.675Z",
"browserName": "electron",
"browserPath": "path/to/browser",
"browserVersion": "59.0.3071.115",
"config": {...},
"osName": "darwin",
"osVersion": "14.5.0",
"runs": [{
"error": null,
"reporter": "spec",
"reporterStats": {...},
"spec": {...},
"stats": {
"suites": 1,
"tests": 1,
"passes": 0,
"pending": 0,
"skipped": 0,
"failures": 1,
"startedAt": "2020-08-05T08:38:37.589Z",
"endedAt": "2018-07-11T17:53:35.675Z",
"duration": 1171
},
"screenshots": [{
"name": null,
"takenAt": "2020-08-05T08:52:20.432Z",
"path": "User/janelane/my-app/cypress/screenshots/cy.js/test (failed).png",
"height": 720,
"width": 1280
}],
"tests": [{
"title": [ "test" ],
"state": "failed",
"displayError": "AssertionError: expected true to be false\n' +
' at Context.eval (...cypress/e2e/cy.js:5:21",
"attempts": [{
"state": "failed",
}],
}],
"video": "User/janelane/my-app/cypress/videos/abc123.mp4"
}],
"runUrl": "https://cloud.cypress.io/projects/def456/runs/12",
"startedTestsAt": "2018-07-11T17:53:35.463Z",
"totalDuration": 212,
"totalFailed": 1,
"totalPassed": 0,
"totalPending": 0,
"totalSkipped": 0,
"totalSuites": 1,
"totalTests": 1,
}

您可以在cypress/cli/types文件夹中找到结果对象的TypeScript定义。

错误处理

即使测试失败或测试出错,Promise也会解析为测试结果。如果测试出错,错误消息将位于runs数组中的error字段下。只有当Cypress由于某种原因无法运行时(例如未安装二进制文件或找不到模块依赖项),Promise才会被拒绝。在这种情况下,Promise将被拒绝并附带详细错误。

还有第三种情况 - Cypress可以运行,但由于某种原因测试无法启动。在这种情况下,解析值是一个包含两个字段的对象

{
"failures": 1, // 非零数字
"message": "..." // 错误消息
}

为了处理这些可能的错误,您可以向cypress.run()添加catch

// e2e-run-tests.js
const cypress = require('cypress')

cypress.run({...})
.then(result => {
if (result.failures) {
console.error('无法执行测试')
console.error(result.message)
process.exit(result.failures)
}

// 以失败测试数量作为退出码
process.exit(result.totalFailed)
})
.catch(err => {
console.error(err.message)
process.exit(1)
})

cypress.open()

通过Node.js打开Cypress测试。

// e2e-open-tests.js
const cypress = require('cypress')

cypress.open({
config: {
baseUrl: 'http://localhost:8080',
},
env: {
login_url: '/login',
products_url: '/products',
},
})

然后您可以通过在终端或npm脚本中运行以下命令来打开Cypress:

node e2e-open-tests.js

选项

命令行选项类似,您可以传递修改Cypress运行方式的选项。

选项类型描述
browserstring指定自定义浏览器的文件系统路径
configobject指定配置
configFilestring要使用的配置文件路径。
detachedboolean以分离模式打开Cypress
envobject指定环境变量
globalboolean以全局模式运行
portnumber覆盖默认端口
projectstring特定项目的路径
testingTypestring指定要执行的测试类型;e2ecomponent。默认为e2e

示例

// e2e-open-tests.js
const cypress = require('cypress')

cypress.open({})

然后您可以通过在终端或npm脚本中运行以下命令来打开Cypress:

node e2e-open-tests.js

cypress.cli

parseRunArguments()

如果您正在编写一个围绕cypress.run()命令的工具,您可能希望使用与cypress run相同的逻辑来解析用户提供的命令行参数。在这种情况下,您可以使用内置的parseRunArguments函数。

// wrapper.js
const cypress = require('cypress')

const runOptions = await cypress.cli.parseRunArguments(process.argv.slice(2))
const results = await cypress.run(runOptions)
// 处理"cypress.run()"结果

从终端运行的示例用法可能是:

node ./wrapper cypress run --browser chrome --config ...

**注意:**传递给parseRunArguments的参数应以cypress run开头。

历史

版本变更
12.6.0向运行选项添加了autoCancelAfterFailures
10.0.0slowTestThreshold现在限定于每种测试类型。
8.7.0添加了slowTestThreshold配置选项。
7.3.0添加了testingType配置选项。
5.0.0cypress.run()返回的测试结果变更。
4.11.0添加了带有parseRunArguments函数的cypress.cli
4.9.0cypress.run()添加了quiet选项