Subsecciones


Práctica: Conversor de Temperaturas con Karma y Travis

Donde

Véase la rama karma en el repositorio descrito en la sección 1.2. Esta rama no está disponible al alumno.

Requisitos

Lea

Karma

Karma: Como Funciona

Karma: Videos

Karma: Opciones en Línea de Comandos

[~/srcPLgrado/mocha-chai-browser-demo(master)]$ karma --help
Karma - Spectacular Test Runner for JavaScript.

Usage:
  /usr/local/bin/karma <command>

Commands:
  start [<configFile>] [<options>] Start the server / do single run.
  init [<configFile>] Initialize a config file.
  run [<options>] [ -- <clientArgs>] Trigger a test run.
  completion Shell completion for karma.

Run --help with particular command to see its description and available options.

Options:
  --help     Print usage and options.
  --version  Print current version.

Karma: Generando el Fichero de Configuración

In order to serve us well, Karma needs to know about our project in order to test it and this is done via a configuration file.

The configuration file can be generated using karma init:

$ karma init my.conf.js

Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> jasmine

Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no

http://requirejs.org/

Do you want to capture a browser automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome

What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
> 

Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.


Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> yes

Config file generated at "/Users/casiano/local/src/javascript/PLgrado/mocha-tutorial/karma.conf.js".

The configuration file can be written in CoffeeScript as well. In fact, if you execute karma init with a .coffee filename extension, it will generate a CoffeeScript file.

Of course, you can write the config file by hand or copy paste it from another project ;-)

[~/srcPLgrado/mocha-tutorial]$ cat karma.conf.js 
// Karma configuration
// Generated on Mon Jan 20 2014 16:21:22 GMT+0000 (WET)

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '',


    // frameworks to use
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
      
    ],


    // list of files to exclude
    exclude: [
      
    ],


    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['Chrome', 'Firefox'],


    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,


    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};

Arrancando Karma. Starting Karma

When starting Karma, the configuration file path can be passed in as the first argument. By default, Karma will look for karma.conf.js in the current directory.

# Start Karma using your configuration
$ karma start my.conf.js

Some configurations, which are already present within the configuration file, can be overridden by specifying the configuration as a command line argument for when Karma is executed.

karma start karma-conf.js --command-one --command-two

[~/srcPLgrado/mocha-tutorial]$ karma start --help
Karma - Spectacular Test Runner for JavaScript.

START - Start the server / do a single run.

Usage:
  /usr/local/bin/karma start [<configFile>] [<options>]

Options:
  --port                <integer> Port where the server is running.                            
  --auto-watch          Auto watch source files and run on change.                             
  --no-auto-watch       Do not watch source files.                                             
  --log-level           <disable | error | warn | info | debug> Level of logging.              
  --colors              Use colors when reporting and printing logs.                           
  --no-colors           Do not use colors when reporting or printing logs.                     
  --reporters           List of reporters (available: dots, progress, junit, growl, coverage). 
  --browsers            List of browsers to start (eg. --browsers Chrome,ChromeCanary,Firefox).
  --capture-timeout     <integer> Kill browser if does not capture in given time [ms].         
  --single-run          Run the test when browsers captured and exit.                          
  --no-single-run       Disable single-run.                                                    
  --report-slower-than  <integer> Report tests that are slower than given time [ms].           
  --help                Print usage and options.

Using Karma with Mocha

To use Karma with Mocha we need the karma-mocha adapter.

If we want to pass configuration options directly to mocha you can do this in the following way

// karma.conf.js
module.exports = function(config) {
  config.set({
    frameworks: ['mocha'],

    files: [
      '*.js'
    ],

    client: {
      mocha: {
        ui: 'tdd'
      }
    }
  });
};
(By default the ui is bdd).

Here is an example

[~/srcPLgrado/temperature(karma)]$ cat karma.conf.js 
// Karma configuration
// Generated on Thu Jan 29 2015 16:51:38 GMT+0000 (WET)

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['mocha'],

    client: {
          mocha: {
            ui: 'tdd'
          }
    },

    preprocessors: {
          'tests/test.html': ['html2js']
    },


    // list of files / patterns to load in the browser
    files: [
      'tests/test.html',
      'tests/*.js',
      'temperature.js'
    ],


    // list of files to exclude
    exclude: [

    ],


    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: [
               'Chrome',
               'Firefox',
               'PhantomJS',
               ],


    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,


    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
Another example can be found at (https://github.com/crguezl/nathanuniversityexercisesPL/blob/master/scheem8/karma.conf.js).

Algunas dependencias para ejecutar Karma

De hecho, para poder usar Karma con los diferentes navegadores es necesario instalar unos cuantos módulos. Vea este fragmento de package.json
 "devDependencies": {
    "chai": "*",
    "mocha": "*",
    "karma": "*",
    "karma-mocha": "*",
    "karma-html2js-preprocessor": "*",
    "karma-chrome-launcher": "*",
    "karma-firefox-launcher": "*",
    "karma-phantomjs-launcher": "*"
  },

Load HTML files with Karma

If you have one html file:

[~/srcPLgrado/karma/html]$ cat template.html 
<div id="tpl">content of the template</div>
which you want to load and then get all elements from that html page in your test script, you can use the html2js preprocessor, which basically converts HTML files into JavaScript strings and include these files.
[~/srcPLgrado/karma/html]$ cat karma.conf.js 
module.exports = function(karma) {
  karma.configure({
    basePath: '',
    frameworks: ['jasmine'],
    files: [ '*.js', '*.html' ], 
    preprocessors: { '*.html': 'html2js' },
    ....
Then, you can access these strings in your test:
[~/srcPLgrado/karma/html]$ cat test.js 
describe('template', function() {
  it('should expose the templates to __html__', function() {
    document.body.innerHTML = __html__['template.html'];
    expect(document.getElementById('tpl')).toBeDefined();
  })
})

Preprocessors in Karma allow you to do some work with your files before they get served to the browser. The configuration of these happens in this block in the config file.

preprocessors = {
  '**/*.coffee': 'coffee',
  '**/*.html': 'html2js'
};

tests/tests.js usando Karma y Considerando el HTML

Por tanto modificamos nuestro fichero tests/tests.js como sigue:
[~/srcPLgrado/temperature(karma)]$ cat tests/tests.js 
var assert = chai.assert;

suite('temperature', function() {
    setup(function(){
      if (typeof __html__ !== 'undefined') {
          document.body.innerHTML = __html__['tests/test.html'];
          original = document.getElementById('original');
          converted = document.getElementById('converted');
      }
    });

    test('32F = 0C', function() {
        original.value = "32F";
        calculate();
        assert.deepEqual(converted.innerHTML, "0.0 Celsius");
    });
    test('45C = 113.0 Farenheit', function() {
        original.value = "45C";
        calculate();
        assert.deepEqual(converted.innerHTML, "113.0 Farenheit");
    });
    test('5X = error', function() {
        original.value = "5X";
        calculate();
        assert.match(converted.innerHTML, /ERROR/);
    });
});

tests/test.html usando Karma y Considerando el HTML

El fichero html inicial también cambia, ya que Karma se encarga de la carga de los ficheros HTML y de su pre-procesado:

[~/srcPLgrado/temperature(karma)]$ cat tests/test.html 
<html>
  <head>
    <title>Mocha</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

  </head>
  <body>
    <div id="mocha"></div>
    <input id="original" placeholder="32F" size="50">
    <span class="output" id="converted"></span>

    <script src="../temperature.js"></script>
    <script>mocha.setup('tdd')</script>
    <script src="tests.js"></script>

    <script>
      mocha.run();
    </script>
  </body>
</html>
Obsérvese que no cargamos mocha, etc porque son cargados por Karma (como especificamos en el fichero de configuración).

Karma y HTML: Véase

See

Karma y Gulp

Para automatizar la ejecución de las pruebas con karma y gulp añadimos un par de tareas a nuestor gulpfile. Las tareas test y default:

[~/srcPLgrado/temperature(karma)]$ cat gulpfile.js 
var gulp    = require('gulp'),
    gutil   = require('gulp-util'),
    uglify  = require('gulp-uglify'),
    concat  = require('gulp-concat');
var karma   = require('gulp-karma');
...

gulp.task('test', function() {
  // Be sure to return the stream
  return gulp.src([])
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: 'run'
    }))
    .on('error', function(err) {
      // Make sure failed tests cause gulp to exit non-zero
      throw err;
    });
});

gulp.task('default', function() {
  gulp.src([])
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: 'watch'
    }));
});

Karma y Travis

Véase http://karma-runner.github.io/0.12/plus/travis.html.

Casiano Rodríguez León
2016-03-27