也许 exec 在与被调用命令交互的方式上太有限了,你需要一个可编程的 API 而不仅仅是配置选项。
您可以尝试使用任务,有一个库 node-ssh 将与赛普拉斯任务交互。
我不熟悉 ssh 协议,因此您必须填写这些详细信息,但这里是 Cypress 任务和 node-ssh 库的基本示例
cypress/plugins/index.js
module.exports = (on, config) => {
on('task', {
ssh(params) {
const {username, host, remoteCommand} = params // destructure the argument
const {NodeSSH} = require('node-ssh')
const ssh = new NodeSSH()
ssh.connect({
host: host,
username: username,
privateKey: '/home/steel/.ssh/id_rsa' // maybe parameterize this also
})
.then(function() {
ssh.execCommand(remoteCommand, { cwd:'/var/www' })
.then(function(result) {
console.log('STDOUT: ' + result.stdout)
console.log('STDERR: ' + result.stderr)
})
})
return null
},
})
}
返回结果
以上 ssh 代码仅来自 node-ssh 的示例页面。如果你想返回result 的值,我想这样就可以了。
module.exports = (on, config) => {
on('task', {
ssh(params) {
const {username, host, remoteCommand} = params // destructure the argument
// returning promise, which is awaited by Cypress
return new Promise((resolve, reject) => {
const {NodeSSH} = require('node-ssh')
const ssh = new NodeSSH()
ssh.connect({
host: host,
username: username,
privateKey: '/home/steel/.ssh/id_rsa'
})
.then(function() {
ssh.execCommand(remoteCommand, { cwd:'/var/www' })
.then(function(result) {
resolve(result) // resolve to command result
})
})
})
},
})
}
测试中
cy.task('ssh', {username: 'username', host: '111.111.1.1', command: '\file.exe'})
.then(result => {
...
})
一个任务只允许一个参数,所以传入一个对象并在任务内部对其进行解构,如上所示。