Karma运行单一测试

时间:2014-10-24 16:59:51

标签: karma-runner

我使用业力来进行跑步测试。我有很多测试并且运行所有测试的过程非常缓慢。我想只运行一次测试才能花更少的时间,因为所有测试运行大约10分钟。

有可能吗?

感谢。

9 个答案:

答案 0 :(得分:67)

如果您使用 Karma / Jasmine 堆栈,请使用:

fdescribe("when ...", function () { // to [f]ocus on a single group of tests
  fit("should ...", function () {...}); // to [f]ocus on a single test case
});

......和:

xdescribe("when ...", function () { // to e[x]clude a group of tests
  xit("should ...", function () {...}); // to e[x]clude a test case
});

当您进入 Karma / Mocha

describe.only("when ...", function () { // to run [only] this group of tests
  it.only("should ...", function () {...}); // to run [only] this test case
});

......和:

describe.skip("when ...", function () { // to [skip] running this group of tests
  it.skip("should ...", function () {...}); // to [skip] running this test case
});

答案 1 :(得分:22)

更新:业力发生了变化。

现在使用fit()fdescribe()

f代表专注!

答案 2 :(得分:2)

将it()更改为iit()应该可以运行单个测试。 同样,对于describe()块,我们可以使用ddescribe()

答案 3 :(得分:2)

a)您可以将描述单个文件的模式作为命令行参数传递给karma start命令:

# build and run all tests
$ karma start

# build and run only those tests that are in this dir
$ karma start --grep app/modules/sidebar/tests

# build and run only this test file
$ karma start --grep app/modules/sidebar/tests/animation_test.js

来源:https://gist.github.com/KidkArolis/fd5c0da60a5b748d54b2

b)您可以使用Gulp(或Grunt等)任务为您启动Karma。这为您提供了更多关于如何执行Karma的灵活性。例如,您可以将自定义命令行参数传递给这些任务。如果要实现仅执行已更改测试的监视模式,此策略也很有用。 (Karma监视模式将执行所有测试。)另一个用例是在执行提交之前仅对具有本地更改的文件执行测试。 另见下面的Gulp示例。

c)如果使用VisualStudio,则可能需要将外部工具命令添加到解决方案资源管理器的上下文菜单中。这样,您可以从该上下文菜单而不是使用控制台启动测试。另见

How to execute custom file specific command / task in Visual Studio?

示例Gulp文件

//This gulp file is used to execute the Karma test runner
//Several tasks are available, providing different work flows
//for using Karma. 

var gulp = require('gulp');
var karma = require('karma');
var KarmaServerConstructor = karma.Server;
var karmaStopper = karma.stopper;
var watch = require('gulp-watch');
var commandLineArguments = require('yargs').argv;
var svn = require('gulp-svn');
var exec = require('child_process').exec;
var fs = require('fs');

//Executes all tests, based on the specifications in karma.conf.js
//Example usage: gulp all
gulp.task('all', function (done) {
    var karmaOptions = { configFile: __dirname + '/karma.conf.js' };
    var karmaServer = new KarmaServerConstructor(karmaOptions, done);
    karmaServer.on('browsers_change', stopServerIfAllBrowsersAreClosed); //for a full list of events see http://karma-runner.github.io/1.0/dev/public-api.html
    karmaServer.start();   
});

//Executes only one test which has to be passed as command line argument --filePath
//The option --browser also has to be passed as command line argument.
//Example usage:  gulp single --browser="Chrome_With_Saved_DevTools_Settings" --filePath="C:\myTest.spec.js"
gulp.task('single', function (done) {     

    var filePath = commandLineArguments.filePath.replace(/\\/g, "/");

    var karmaOptions = {
        configFile: __dirname + '/karma.conf.js',
        action: 'start',        
        browsers: [commandLineArguments.browser],       
        files: [
            './Leen.Managementsystem/bower_components/jquery/dist/jquery.js',
            './Leen.Managementsystem/bower_components/globalize/lib/globalize.js',
            { pattern: './Leen.Managementsystem/bower_components/**/*.js', included: false },
            { pattern: './Leen.Managementsystem.Tests/App/test/mockFactory.js', included: false },
            { pattern: './Leen.Managementsystem/App/**/*.js', included: false },
            { pattern: './Leen.Managementsystem.Tests/App/test/*.js', included: false },
            { pattern: filePath, included: false },
            './Leen.Managementsystem.Tests/App/test-main.js',
            './switchKarmaToDebugTab.js' //also see https://stackoverflow.com/questions/33023535/open-karma-debug-html-page-on-startup
        ]
    };

    var karmaServer = new KarmaServerConstructor(karmaOptions, done);   
    karmaServer.on('browsers_change', stopServerIfAllBrowsersAreClosed);
    karmaServer.start();     
});

//Starts a watch mode for all *.spec.js files. Executes a test whenever it is saved with changes. 
//The original Karma watch mode would execute all tests. This watch mode only executes the changed test.
//Example usage:  gulp watch 
gulp.task('watch', function () {

    return gulp //
        .watch('Leen.Managementsystem.Tests/App/**/*.spec.js', handleFileChanged)
        .on('error', handleGulpError);

    function handleFileChange(vinyl) {

        var pathForChangedFile = "./" + vinyl.replace(/\\/g, "/");

        var karmaOptions = {
            configFile: __dirname + '/karma.conf.js',
            action: 'start',
            browsers: ['PhantomJS'],
            singleRun: true,
            files: [
                    './Leen.Managementsystem/bower_components/jquery/dist/jquery.js',
                    './Leen.Managementsystem/bower_components/globalize/lib/globalize.js',
                    { pattern: './Leen.Managementsystem/bower_components/**/*.js', included: false },
                    { pattern: './Leen.Managementsystem.Tests/App/test/mockFactory.js', included: false },
                    { pattern: './Leen.Managementsystem/App/**/*.js', included: false },
                    { pattern: './Leen.Managementsystem.Tests/App/test/*.js', included: false },
                    { pattern: pathForChangedFile, included: false },
                    './Leen.Managementsystem.Tests/App/test-main.js'
            ]
        };

        var karmaServer = new KarmaServerConstructor(karmaOptions);
        karmaServer.start();

    }

});

//Executes only tests for files that have local changes
//The option --browser has to be passed as command line arguments.
//Example usage:  gulp localChanges --browser="Chrome_With_Saved_DevTools_Settings"
gulp.task('localChanges', function (done) {   

    exec('svn status -u --quiet --xml', handleSvnStatusOutput);

    function handleSvnStatusOutput(error, stdout, stderr) {

        if (error) {
            throw error;
        }

        var changedJsFiles = getJavaScriptFiles(stdout);   
        var specFiles = getSpecFiles(changedJsFiles);


        if(specFiles.length>0){
            console.log('--- Following tests need to be executed for changed files: ---');
            specFiles.forEach(function (file) {
                console.log(file);
            });
            console.log('--------------------------------------------------------------');
        } else{
            console.log('Finsihed: No modified files need to be tested.');
            return;
        }

        var files = [
                './Leen.Managementsystem/bower_components/jquery/dist/jquery.js',
                './Leen.Managementsystem/bower_components/globalize/lib/globalize.js',
                { pattern: './Leen.Managementsystem/bower_components/**/*.js', included: false },
                { pattern: './Leen.Managementsystem.Tests/App/test/mockFactory.js', included: false },
                { pattern: './Leen.Managementsystem/App/**/*.js', included: false },
                { pattern: './Leen.Managementsystem.Tests/App/test/*.js', included: false }];

        specFiles.forEach(function (file) {
            var pathForChangedFile = "./" + file.replace(/\\/g, "/");
            files = files.concat([{ pattern: pathForChangedFile, included: false }]);
        });

        files = files.concat([ //
            './Leen.Managementsystem.Tests/App/test-main.js', //
            './switchKarmaToDebugTab.js'
        ]);

        var karmaOptions = {
            configFile: __dirname + '/karma.conf.js',
            action: 'start',
            singleRun: false,
            browsers: [commandLineArguments.browser],
            files: files              
        };

        var karmaServer = new KarmaServerConstructor(karmaOptions, done);
        karmaServer.on('browsers_change', stopServerIfAllBrowsersAreClosed);
        karmaServer.start();
    }  


});

function getJavaScriptFiles(stdout) {
    var jsFiles = [];

    var lines = stdout.toString().split('\n');
    lines.forEach(function (line) {
        if (line.includes('js">')) {
            var filePath = line.substring(9, line.length - 3);
            jsFiles.push(filePath);
        }
    });
    return jsFiles;
}

function getSpecFiles(jsFiles) {

    var specFiles = [];
    jsFiles.forEach(function (file) {

        if (file.endsWith('.spec.js')) {
            specFiles.push(file);
        } else {
            if (file.startsWith('Leen\.Managementsystem')) {
                var specFile = file.replace('Leen\.Managementsystem\\', 'Leen.Managementsystem.Tests\\').replace('\.js', '.spec.js');
                if (fs.existsSync(specFile)) {
                    specFiles.push(specFile);
                } else {
                    console.error('Missing test: ' + specFile);
                }
            }
        }
    });
    return specFiles;
}

function stopServerIfAllBrowsersAreClosed(browsers) {
    if (browsers.length === 0) {
        karmaStopper.stop();
    }
}

function handleGulpError(error) {


  throw error;
}

VisualStudio中ExternalToolCommand的示例设置:

  

标题:使用Chrome运行Karma

     

命令:cmd.exe

     

参数:/ c gulp single   --browser =“Chrome_With_Saved_DevTools_Settings”--filePath = $(ItemPath)

     

初始目录:$(SolutionDir)

     

使用输出窗口:true

答案 4 :(得分:2)

如果要使用angular运行业力测试,只需修改test.ts文件。

找到第const context = require.context('./', true, /\.spec\.ts$/);

如果要运行your.component.spec.ts,请将行修改为:const context = require.context('./', true, /your\.component\.spec\.ts$/);

答案 5 :(得分:2)

对于Angular用户!

我知道两种方法:

  1. Visual Studio代码扩展:

最简单的方法是使用vscode-test-explorer扩展名及其子级angular-karma-test-explorerjasmine-test-adapter,如果需要,您将获得一份当前测试列表,以逐项运行:

enter image description here

  1. 直接修改test.ts

对于我来说,由于this bug,我无法使用扩展方式,因此我最终修改了test.ts文件(如{{3 }} here),只是为了在此处合并该答案,默认情况下上下文如下:

const context = require.context('./', true, /\.spec\.ts$/);

您应该修改它的RegExp以匹配您要测试的文件,例如,如果您要测试一个名为“ my.single.file.custom.name.spec.ts”的文件,它将看起来这样:

const context = require.context('./', true, /my\.single\.file\.custom\.name\.spec\.ts$/);

有关require参数的更多详细信息,您可以找到Shashi

  1. 业力赛跑者进步

当前有一个开放的问题可以改善他们的当前行为,您可以在其github页面(here at their wiki)上关注他们的进展。

答案 6 :(得分:0)

将您的业力配置更改为仅包含您要运行的测试而不是完整目录。

文件内部:[...]

如果您需要/想要在chrome中调试测试以避免缩小js,可能需要对预处理器进行注释。

答案 7 :(得分:0)

是的,这是旧线程。

在过去的几年中,现在我发生了2至3次以下情况。更重要的是,当我没有做太多的单元测试并回到原来的状态时。

我启动了我的Karma,发现测试在初次启动后应该在1秒钟内完成,现在需要20秒。此外,尝试在Chrome中调试单元测试变得非常乏味。网络标签显示了所有文件,每个文件耗时2-3秒。

解决方案:我不知道Fiddler是开放的。关闭它并重新开始测试。

答案 8 :(得分:0)

特殊的Angular / IE案例的答案建议:到目前为止,为了将IE作为浏览器运行,使用“ karma-ie-launcher”对我来说唯一有效的方法是修改 tsconfig的“ include”属性。 spec.json 以使用通用限定路径而非glob显式引用目标测试文件“ C:\ filepath \ my-test.spec.ts”,用于编译。 test.ts 文件的“附加”应该适当地修改为目标文件,以限制测试文件的目的。请注意,要使此方案生效,首先需要在IE中删除缓存。

(对于仅对test.ts进行Angular / Chrome案例修改就足够了。)