因果运行单项测试


77

我使用业力进行运行测试。我有很多测试,并且运行所有测试的过程非常缓慢。我只想运行一个测试,以节省时间,因为所有测试都运行约10分钟。

可能吗 ?

谢谢。



你可以改变describefdescribe,并it通过fit
埃内斯托·阿方索

Answers:


98

如果您使用的是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
});

16
但是,如果贡献者调试了某些东西并重命名了一些测试以缩小问题范围,而忘记这样做并提交了该怎么办?我发现来回编辑测试以使其聚焦和不聚焦是愚蠢的。有没有办法使用CLI来像“仅运行此测试,并且仅运行此测试”?
Ingwie Phoenix

1
通常,在一个文件中有几个测试用例和组,例如,有时您只需要运行其中一个。在任何单元测试库中,“焦点”功能都是“必须具备”的东西。另外,您可以添加“ git-hook”来检查外观.only或对fit外观进行编码,并在找到后拒绝提交。
Dan KK

我明白了-好点!但是我无法检查到VCS的git-hook,可以吗?
Ingwie Phoenix

这个问题很好,但是似乎超出了这个问题。
Dan KK


14

对于Angular用户!

我知道两种方法:

  1. Visual Studio代码扩展:

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

在此处输入图片说明

  1. 直接修改test.ts

对我来说,我是不能够使用扩展方式,因为这个错误,所以我结束了修改test.ts文件(如说明这里通过沙市),只是在这里巩固答案,默认情况下这个样子的:

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参数的更多详细信息,请参见其Wiki

  1. 业力赛跑者改善

当前有一个开放的问题可以改善他们的当前行为,您可以在他们的github页面(https://github.com/karma-runner/karma/issues/1507)上关注他们的进展。


6

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,则可能要在解决方案资源管理器的上下文菜单中添加外部工具命令。这样,您可以从该上下文菜单开始测试,而无需使用控制台。另见

如何在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 /programming/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


6

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

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

如果要运行your.component.spec.ts修改行,请执行以下操作:const context = require.context('./', true, /your\.component\.spec\.ts$/);


1
这是第一个Angular答案!
路易斯·利马斯


0

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

在文件内部:[...]

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


0

是的,这是旧线程。

在过去的几年中,以下情况在我身上发生了2至3次。更重要的是,在我没有做太多单元测试并且又回到它上面时。

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

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


0

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.