mar*_*tti 1 testing command-line exec node.js testcafe
我一直在寻找一个真正的例子,但我找不到任何例子。我对 node js 完全陌生。
我正在设置一个使用命令行工具获取密码的服务。
命令行“pw get key”返回与密钥关联的密码。命令行“pw set key password”设置与密钥关联的密码。
到目前为止,我拥有的部分代码是:
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function cmdPwGet(key) {
const { stdout, stderr } = await exec(`pw get ${key}`);
console.log('stdout:', stdout);
console.log('stderr:', stderr);
}
async function cmdPwPut(key, passwd) {
const { stdout, stderr } = await exec(`pw set ${key} ${passwd}`);
console.log('stdout:', stdout);
console.log('stderr:', stderr);
}
class PwService {
constructor (KEY){
this.basekey = KEY;
this.pwd = "";
}
setPw (key, passwd) {
key = this.basekey + "." + key;
var res = cmdPwPut(key, passwd);
/* missing bits */
}
getPw (key) {
key = this.basekey + "." + key;
var res = cmdPwGet(key);
/* missing bit */
}
}
module.exports = PwService;
Run Code Online (Sandbox Code Playgroud)
这将在 testcafe 环境中使用。这里我定义了一个角色。
testRole() {
let pwService = new PwService('a-key-');
let pw = pwService.getPw('testPW');
//console.log('pw: '+pw)
return Role('https://www.example.com/', async t => {
await t
.typeText(this.firstInput, 'testPW')
.typeText(this.secondInput, pw<??>)
.click(this.selectButton);
}, { preserveUrl: true });
}
Run Code Online (Sandbox Code Playgroud)
如果我对 pw 使用文字字符串,则 testcafe 代码有效。
/丢失的位/ 是空的,因为我尝试了很多不同的东西,但没有一个成功!
我想我可以让它与孩子的 *Sync 版本一起工作。但由于这是在一个可能并行运行的 testcafe 中,我更喜欢异步版本。
有什么建议吗?我知道这真的是为了理解 node.js 中的 promises 之类的东西,但我无法摆脱这一点。
看来这应该是 node.js 专家的标准练习。
Async/Await just make async code looks like sync code, your code still executed async. And the return result of the Async\Await function cmdPwGet is a Promise, not the password as you think.
the execute result of cmdPwGet is a promise
async function cmdPwGet(key) {
const { stdout, stderr } = await exec(`pw get ${key}`);
return stdout;
}
Run Code Online (Sandbox Code Playgroud)
make getPw Async/Await
async getPw(key) {
key = this.basekey + "." + key;
var res = await cmdPwGet(key);
return res;
}
Run Code Online (Sandbox Code Playgroud)
get the password
testRole() {
let pwService = new PwService('a-key-');
return Role('https://www.example.com/', async t => {
// get your password with await
let pw = await pwService.getPw('testPW');
await t
.typeText(this.firstInput, 'testPW')
.typeText(this.secondInput, pw<??>)
.click(this.selectButton);
}, { preserveUrl: true });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
909 次 |
| 最近记录: |