函数正在返回未定义的值

如何解决函数正在返回未定义的值

我在下面定义了一个函数。该函数将文件一个一个地下载并移动到名为templates的目录中。最后,它应该返回目录的长度。问题是,它返回 undefined 值。我相信我在搞砸一些事情。有人可以帮忙吗?

this.no_of_templates = function () {
    var num;
    this.download_files.each( async function (elem) {
        wait.waitForElementVisibility(elem);
        js.highlighterElement(elem);
        elem.click();
        browser.driver.wait(function(){
            var filesArray = glob.sync(dirPath + '**/*.+(xlsx|docx|pptx)');
            if(typeof filesArray !== 'undefined' && filesArray.length > 0){
                return filesArray;
            }
        },60000).then(function(filesArray){
            var filename = filesArray[0];
            fileSystem.moveFile(filename,process.cwd()+'/templates/');
            if(fileSystem.getAllDirFiles(process.cwd()+'/templates/').length >= 6){
                num = fileSystem.getAllDirFiles(process.cwd()+'/templates/').length;
                return false;
            }

        });
    });

    return num;
}

getAllDirFiles() 定义为

this.getAllDirFiles = function (dirPath,arrayOfFiles) {
    var files = fs.readdirSync(dirPath);

    arrayOfFiles = arrayOfFiles || [];

    files.forEach(function (file) {
        if (fs.statSync(dirPath + "/" + file).isDirectory()) {
            arrayOfFiles = getAllDirFiles(dirPath + "/" + file,arrayOfFiles);
        } else {
            arrayOfFiles.push(file);
        }
    })
    return arrayOfFiles;
}

函数返回 undefined 值。

it('test if templates are downloadable',() => {
var templates = bt.no_of_templates();
expect(templates).toBe(6);

});

解决方法

因为您在每个中都使用了异步函数,所以它不会等待它们完成。

试试这个:


this.no_of_templates = async function () {
    var num;
    var holdon = this.download_files.map( async function (elem) {
        wait.waitForElementVisibility(elem);
        js.highlighterElement(elem);
        elem.click();
        return browser.driver.wait(function(){
            var filesArray = glob.sync(dirPath + '**/*.+(xlsx|docx|pptx)');
            if(typeof filesArray !== 'undefined' && filesArray.length > 0){
                return filesArray;
            }
        },60000).then(function(filesArray){
            var filename = filesArray[0];
            fileSystem.moveFile(filename,process.cwd()+'/templates/');
            if(fileSystem.getAllDirFiles(process.cwd()+'/templates/').length >= 6){
                num = fileSystem.getAllDirFiles(process.cwd()+'/templates/').length;
                return false;
            }

        });
    });
    await Promise.all(holdon)
    return num;
}

测试:

bt.no_of_templates().then(num => {
  expect(num).toBe(6);
});

只需要更改以匹配您的框架,它似乎不是纯javascript。


我在代码中发现了一些问题。 为什么每次下载任务都要计算文件数?

,

它抛出错误

(node:12451) UnhandledPromiseRejectionWarning: TypeError: [object Object] is not iterable
at Function.all (<anonymous>)
at BusinessTemplatesPage.no_of_templates (/home/vivek/simplifiedcredit-qa-automation/src/page-objects/business_templates.page.js:125:23)
at UserContext.it (/home/vivek/simplifiedcredit-qa-automation/src/specs/business_templates.spec.js:41:26)
at /home/vivek/simplifiedcredit-qa-automation/node_modules/jasminewd2/index.js:112:25
at new ManagedPromise (/home/vivek/simplifiedcredit-qa-automation/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:1077:7)
at ControlFlow.promise (/home/vivek/simplifiedcredit-qa-automation/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2505:12)
at schedulerExecute (/home/vivek/simplifiedcredit-qa-automation/node_modules/jasminewd2/index.js:95:18)
at TaskQueue.execute_ (/home/vivek/simplifiedcredit-qa-automation/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:3084:14)
at TaskQueue.executeNext_ (/home/vivek/simplifiedcredit-qa-automation/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:3067:27)
at asyncRun (/home/vivek/simplifiedcredit-qa-automation/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2974:25)

(node:12451) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误要么是因为在没有 catch 块的情况下抛出了异步函数,要么是因为拒绝了一个没有用 .catch() 处理过的承诺。 (拒绝编号:2) (节点:12451)[DEP0018] 弃用警告:不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止 Node.js 进程。

因为如果我不计算它会给出预期的结果

- Expected 1 to be 6.
- Expected 2 to be 6.
- Expected 3 to be 6.
- Expected 3 to be 6.
- Expected 5 to be 6.

而且我必须使用相同的功能来测试不同类别的模板。目前有4个类别,每个类别都有不同数量的模板。

,

this.download_files 是一个 ElementArrayFinder。

this.download_files = element.all(by.xpath('//button//img[@src="url_here"]'));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-