waw*_*los 19 javascript promise cypress
我正在寻找一种方法来获取自定义 Cypress 命令返回的返回值。
我目前正在使用 Cypress 和 Cypress-promise lib ( https://www.npmjs.com/package/cypress-promise )
目前,结果是: log1=CAR 1 log2=null
我的错误在哪里?
测试文件:
it('Test 1', async function() {
const carName = await promisify(cy.set_typeCarName());
cy.log("log2 = " + carName );
});
Run Code Online (Sandbox Code Playgroud)
模块:
set_typeCarName() {
let carName = "CAR 1";
cy.get('#newSiteCityInput').type(carName);
cy.log("log1 = " + carName);
return carName;
};
Cypress.Commands.add('set_typeCarName',() => {
webnewsite.set_typeCarName();
});
Run Code Online (Sandbox Code Playgroud)
888*_*888 34
为此,我使用wrap()返回一个Chainable包含我想要返回的值。
模块
function foo() {
return cy.wrap('foo');
}
Cypress.Commands.add('foo', foo);
Run Code Online (Sandbox Code Playgroud)
测试文件
cy.foo().then(value => console.log(value)); // foo
Run Code Online (Sandbox Code Playgroud)
由于wrap()返回 a Cypress.Chainable,我们可以调用.then()我们的命令。传递wrap()给下一个命令的内容。
另请参阅:赛普拉斯 wrap() 文档
Cypress 引入了一种新的代码编写方式,而不是返回值,即使用别名。https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Closures
写代码的正常方式
async function compute(){
const value = await (asynchronous function);
return value;
}
const x = await compute(); // #a
console.log(x); // #b
Run Code Online (Sandbox Code Playgroud)
如何做到这一点在 Cypress 中,因为我们不能在 cypress 中使用 async/await
function() compute{
cy.get('p#text').then(p => {
const text = p.textContent;
cy.wrap(text).as('pText');
//even if we return text from here, it will not be accessible anywhere
});
}
compute(); // #a
cy.get('@pText').then(text => {
console.log(text); // #b
}
Run Code Online (Sandbox Code Playgroud)
关键是给值取别名,然后在下一个命令中使用它,
因为
赛普拉斯首先运行整个代码并在
代码进入队列后将命令放入队列,队列中的下一个命令只有在当前命令的所有回调完成后才会运行,因此我们可以使用上面的代码模式。
使用您的代码回答
Cypress.Commands.add('set_typeCarName',() => {
return cy.wrap(webnewsite.set_typeCarName()); //return the wrap and use in chain
});
function set_typeCarName() {
let carName = "CAR 1";
cy.get('#newSiteCityInput').type(carName);
cy.log("log1 = " + carName);
return carName;
};
Run Code Online (Sandbox Code Playgroud)
测试
it('Test 1', async function() {
cy.set_typeCarName().then(carName => {
cy.log("log2 = " + carName );
}
);
Run Code Online (Sandbox Code Playgroud)
Nor*_*Ste -1
该命令是否缺少return语句?
Cypress.Commands.add('set_typeCarName',() => {
return webnewsite.set_typeCarName(); // I added the initial `return`
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27681 次 |
| 最近记录: |