我正在编写 Protractor 脚本。 我的问题是,我无法将值存储到全局变量中。既不进入 global.somevariable,也不进入 browser.params.somevariable。
我有 2 个文件: 1.登录.js 2.helper.js
通过 helper.js 文件中的匿名方法,我试图将值存储到全局变量中。我从一个 PageObject 文件的 js 文件中调用这个 helper.js 相关方法。
在 config.js 中,我声明了 2 个变量 - 一个带有 global 关键字。 第二个是 onPrepare() 方法,所以我可以使用 browser.params.someVar。但是,没有任何效果。
在该方法内部,变量内部的值没问题。但是,当我访问 helper.js 之外的相同变量时,它们为空/不正确。
配置.js
exports.config =
{
params:
{
tempVar:false
},
onPrepare:function()
{
global.result=false;
}
};
登录页面.js
var loginPage = function()
{
var un = element(by.id('un'));
var helper = new help();
helper.verifyElemExists(un);
console.log(global.result);//False,though promise returned true
console.log(browser.params.tempVar); // This is also false
if(global.result===true)
{
// Code will do something...
}
}
module.exports = login;
helper.js
var helper = function()
{
verifyElemExists = function(elem)
{
elem.isPresent().then(function(res)
{
browser.params.tempVar=res;
global.result =res;
});
}
module.exports = helper;
最佳答案
你需要知道nodejs执行 Protractor 脚本的过程。您的问题的根本原因来自以下代码片段:
helper.verifyElemExists(un);
// when nodejs execute above line, all promises generated in this function
// will be added into a list (you can call the list as protractor control flow),
// after all sync script be executed, the protractor control flow start to execute
// the promise in the list one by one in the order as they are added into list.
console.log(global.result);
console.log(browser.params.tempVar);
if(global.result===true)
{
// Code will do something...
}
// when nodejs execute above lines, because all of them are sync script,
// the execution result of then return immediately, and at the time point they are executed,
// the promise of `helper.verifyElemExists(un);`
// have not start to execute(or not complete execute),
// thus the `global.result` and `browser.params.tempVar` are still with init value: false
从上面的protractor脚本执行过程可以看出,当promise和sync代码执行完成后,会为promise代码创建一个promise列表,但不会为sync代码创建一个promise列表。然后执行列表中的 promise 。
要解决您的问题,您可以将上面的同步代码包装到一个 promise 中,以便它们在 helper.verifyElemExists(un);
helper.verifyElemExists(un);
// browser.getTitle() is a promise which be added into promise list after
// helper.verifyElemExists(un);
browser.getTitle().then(function(){
console.log(global.result);
console.log(browser.params.tempVar);
if(global.result===true)
{
// Code will do something...
}
})
// or change the `helper.verifyElemExists()` to return a promise
var helper = function()
{
verifyElemExists = function(elem)
{
return elem.isPresent().then(function(res)
{
browser.params.tempVar=res;
global.result =res;
});
}
module.exports = helper;
helper.verifyElemExists(un).then(function(){
console.log(global.result);
console.log(browser.params.tempVar);
if(global.result===true)
{
// Code will do something...
}
})
关于javascript - 无法将匿名函数的值存储到全局变量中 - Javascript 和 Protractor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54062697/