2014-10-24 1 views
32

Uso il karma per eseguire i test. Ho molti test ed eseguo tutti i test è un processo molto lento. Voglio eseguire solo un singolo test per trascorrere meno tempo, perché tutti i test durano circa 10 minuti.Test single test Karma

È possibile?

Grazie.

+2

Se si utilizza il gelsomino è possibile utilizzare ddescribe/IIT. –

+0

Problema relativo al karma: https://github.com/karma-runner/karma/issues/1507#issuecomment-320383049 – Stefan

risposta

0

Cambia il tuo karma conf per includere solo il test che desideri eseguire invece di una directory completa.

all'interno dei file: [...]

Si potrebbe desiderare di commentare i preprocessori se avete bisogno/desidera eseguire il debug di test in cromo per evitare di avere i js minified.

2

Cambiarlo() in iit() dovrebbe funzionare per l'esecuzione del test singolo. Inoltre, per il blocco describe() possiamo usare ddescribe()

+1

a seconda della versione di karma, potrebbe essere necessario utilizzare 'fdescribe()' e 'fit()' as brendan indica – mgojohn

13

Aggiornamento: il karma è cambiato.

Ora utilizzare in forma() e fdescribe()

F sta per concentrato!

+0

ahhh 'f' sta per' focused' ... kinda muto ma lo prenderò lol –

48

Se si utilizza il Karma/Jasmine pila, uso:

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

... e:

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

Quando sei in Karma/Mocha:

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

... e:

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

Ma cosa succede se un contributore che ha eseguito il debug di qualcosa e rinominato alcuni test per restringere il problema si dimentica di farlo e lo impegna ? Trovo stupido modificare il test avanti e indietro per mettere a fuoco e sfocarlo. Non c'è modo di usare la CLI per essere come "Esegui questo test e solo questo test"? –

+0

Di solito ci sono diversi casi di test e gruppi in un file, ea volte è necessario eseguire solo uno di essi, ad esempio. La funzione "focus" è "must have" in qualsiasi libreria di test delle unità. Inoltre, è possibile aggiungere "git-hook" che verifica l'aspetto del codice '.lyly' o' fit' e rifiuta il commit se trovato. –

+0

Vedo - buon punto! Ma non posso controllare un git-hook in VCS, posso? –

1

a) È possibile passare un modello che descrive il singolo file da riga di comando argomento del comando di avvio del karma:

# 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 

Fonte: https://gist.github.com/KidkArolis/fd5c0da60a5b748d54b2

b) è possibile utilizzare un Gulp (o Grunt ect.) compito che avvia Karma per te. Questo ti dà più flessibilità su come eseguire il Karma. Ad esempio, è possibile passare argomenti personalizzati della riga di comando a tali attività. Questa strategia è utile anche se si desidera implementare una modalità di visualizzazione che esegue solo i test modificati. (La modalità di controllo Karma eseguirà tutti i test.) Un altro caso d'uso sarebbe di eseguire solo i test per i file con modifiche locali prima di eseguire un commit. Vedere anche esempi di Gulp di seguito.

c) Se si utilizza VisualStudio, è possibile aggiungere un comando di strumento esterno al menu di scelta rapida di Solution Explorer. In questo modo, puoi avviare il test da quel menu contestuale invece di usare la console.Vedere anche il file

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

Esempio 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) { 

errore tiro; }

impostazioni di esempio per ExternalToolCommand in VisualStudio:

Titolo: Run Karma usando Chrome

comando: cmd.exe

Argomenti:/c sorso singolo --browser =" Chrome_With_Saved_DevTools_Settings "--filePath = $ (ItemPath)

Directory iniziale: $ (SolutionDir)

Usa finestra di output: true