要求是基于依赖于函数“getSteps”的变量“data”运行 testRunner 函数
我的代码如下
function getSteps()
it('test', async function () {
testStepsArray = await excel.getColValue('smoke.xlsx', 'Sheet1', 'A')
return testStepsArray
});
}
function testRunner(count) { **//i want to run this function based on value of data variable below**
it('test', async function () {
for(var j=0;j<count;j++)
{
...
}
});
}
var data = getSteps();
console.log(data.length+"LENGTH") **//returns Cannot read property 'length' of undefined.**
for(var i=1; i<= data.length;i+=count)
{
...
testRunner(i)
}
我认为最后一个 block 不是在等待 getSteps 的结果。请提出建议。
更新: 输入后,我修改如下,我看到了差异。我现在可以正确获取数据值,但是当有一个函数环绕规范但与常规函数一起工作时执行失败
function testRunner(count) {
it('test', async function () {
for(var j=0;j<count;j++)
{
...
}
});
}
function test(){
...
}
let promise = new Promise((resolve,reject)=>{
it('test', async function () {
testStepsArray = await excel.getColValue('smoke.xlsx', 'Sheet1', 'A')
resolve(testStepsArray)
});
}
})
promise.then((data)=>{
console.log(data.length+"LENGTH")
for(var i=1; i<= data.length;i+=count)
{
testRunner(i) //fails if function is like testrunner() - function wrraped around specs
test() //works if function is like test() - regular function
}
})
更新 2:Promise 拒绝错误日志
[32m. [0mError: 'it' should only be used in 'describe' function
at ensureIsNotNested (\nodejs\node_modules\jasmine_3.5.0\node_modules\jasmine-core\lib\jasmine-core\jasmine.js:1786:15)
at Env.it (\nodejs\node_modules\jasmine_3.5.0\node_modules\jasmine-core\lib\jasmine-core\jasmine.js:1933:7)
at it (nodejs\node_modules\jasmine_3.5.0\node_modules\jasmine-core\lib\jasmine-core\jasmine.js:6576:21)
at testRunner (webapps\mysamples\testRunner.js:66:4)
at webapps\mysamples\testRunner.js:59:4
at processTicksAndRejections (internal/process/task_queues.js:97:5)
最佳答案
Promise 呢?它会等到您的函数解析“数据”
let promise = new Promise((resolve,reject)=>{
it('test', async function () {
testStepsArray = await excel.getColValue('smoke.xlsx', 'Sheet1', 'A')
resolve(testStepsArray)
});
}
})
promise.then((data)=>{
console.log(data.length+"LENGTH")
for(var i=1; i<= data.length;i+=count)
{
...
testRunner(i)
}
})
阅读更多关于 promise 的信息
更新
被拒绝的 promise 意味着您的代码执行没有按预期工作。
即网站 GET 请求。
let promise = new Promise((resolve,reject)=>{
$.get(some_website, function(data, status, error){
if(status==200){
//Get request success, then return the data from website
resolve(data);
} else {
//Get request fail, return error message
reject(error);
}
});
})
我猜你没有成功运行 excel.getColValue('smoke.xlsx', 'Sheet1', 'A')
尝试为失败案例添加 reject(something)。
然后在你的消费部分,添加这个:
promise.then((data)=>{
//blah blah blah
}).catch((err)=>{
console.log(err) //read what's up with your operation
})
或者如果你发现你的 promise 卡在了 for 循环中(没有等待 for 循环完成,请使用 promise.all() References
关于javascript - 如何基于依赖于 specs jasmine 中其他函数的变量值运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63575741/