Pregunta

I am using Backbone.js and RequireJs for a single page application.

When I run my karma tests, there is no css included. When debugging it is difficult to know what is going on or why something is not working because the html elements are not styled like they are in the production appplication.

Is is possible to inlcude css in the karma tests while debugging using webstorm?

I have already tried including all css in the files array

files: [
    {pattern: 'app/css/*.css', included: false},
    ...
],

This is the css file that is included in index.html of the production application, there is nowhere in the the karma configuration that I can find to add something like this.

<link rel="stylesheet" href="css/styles.css" />
¿Fue útil?

Solución

I worked it out:

  1. You need to add all your css to your karma.conf 'files' array.

    files: [
        {pattern: 'app/**/*.css', included: false},
        ...
    ],
    
  2. Create a new module called test_css.js, the location of this file will depend on your folder structure. In here you need to programatically inject all your css files into your the current document.

    define(function(require) {
        "use strict";
    
        require('jquery');
    
        //Modify to suit your requirements
        $('body').append('<link rel="stylesheet" href="/base/app/css/styles.css" />');
    
    });
    
  3. Include this module as part of the deps array in test-main.js

    requirejs.config({
        baseUrl: '/base/app/js',
    
        paths: {
            ...
            'test.css' : '../test_utils/test_css'
        },
    
        // ask Require.js to load these files (all our tests)
        deps: ['test.css'].concat(tests),
    
        // start test run, once Require.js is done
        callback: window.__karma__.start
    });
    

Otros consejos

jax answer was very helpful.

Additionally, for those not using jQuery but d3.js, your test-css.js can look like this:

define([
    'd3'
], function(d3) {
    "use strict";
    d3.select('body').append('link')
        .attr('rel', 'stylesheet')
        .attr('href', '/base/app/styles/mystyles.css');
});

I resolved a quite similar issue where my components were not appearing in Karma Test Runner by adding following to files key of karma.conf.js. I wanted Karma to automatically include the file so I set included to true.

.
.
.
files: [
  { pattern: 'node_modules/abc/abc.min.css', included:true, watched: false }
],

Upon doing this, I could then view my components in proper styling which made unit testing a lot faster and easier.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top