UI5-如何在没有allTests文件的情况下运行Karma,从文件夹运行所有测试

时间:2019-07-09 08:30:52

标签: unit-testing sapui5 karma-runner

我目前正在为UI5 Web应用程序准备一些单元测试POC。要运行它们,我们想使用业力赛跑者。在其安装指南中,我看到了

All tests should be listed in specific files. You can, for example, collect all unit tests in an allTests.js file. With the help of this file, Karma can find all tests that belong to specific modules or components.

    client: {
      openui5: {
        tests: [
          'test/unit/allTests',
          'test/integration/AllJourneys'

使用allTests.js文件,我确实能够执行单元测试。但是,现在我正在考虑使用此allTests.js文件是否绝对必要-因为现在,当我们向测试范围添加新的.js测试时,我们还需要将其路径添加到allTests.js文件中这似乎是多余的工作(如果忘记了,则可能会引起问题)。

我认为,如果.js路径中的所有"test/unit"文件都由Karma执行,而无需将它们全部收集在一个文件中,则会更好。但是,我还没有在网上找到任何可以做的方法,到目前为止,我的实验失败了。例如,我删除了配置文件的openui5/tests部分,并试图像这样在files部分中定义已加载的测试

files: ['https://openui5.hana.ondemand.com/1.65.1/resources/sap-ui-core.js', 'test/unit/*.js'],

有人可以建议吗?是否可以绕过allTests.js文件,如果可以,该如何做?谢谢。

1 个答案:

答案 0 :(得分:0)

最后,我们按照Ji aSH的建议进行了操作-在每次测试运行开始时,我们运行一个脚本来收集test / unit文件夹中所有.js文件的名称,并从中创建allTests.js文件。像这样

const fs = require('fs');
const path = require('path');

// List all files in a directory in Node.js recursively in a synchronous fashion
const walkSync = function (dir, filelist) {

    if (dir[dir.length - 1] != path.sep) dir = dir.concat(path.sep)

    const files = fs.readdirSync(dir);
    filelist = filelist || [];
    files.forEach(function (file) {
        if (fs.statSync(path.join(dir, file)).isDirectory()) {
            filelist = walkSync(path.join(dir, file), filelist);
        }
        else {
            if (path.extname(file) === '.js' && path.basename(file) !== 'allTests.js') {
                const filePath = `\n    '${dir}${path.basename(file, '.js')}'`;
                filelist.push(filePath.replace('webapp', path.join('xxx', 'xxxxl')));
            }
        }
    });
    return filelist;
};

const testFiles = walkSync(path.join('webapp', 'test', 'unit'), null);
const fileContent = `sap.ui.define([${testFiles},\n], () => { 'use strict'; });\n`;

fs.writeFileSync(path.join('webapp', 'test', 'unit', 'allTests.js'), fileContent);