4

I am working on a web app that uses SVG graphics for most of its display and interaction. I would like to use Karma to create unit tests that load an SVG asset, makes sure that certain groups/paths are present, etc.

I haven't found any straightforward answers to how to do this yet, or figured it out on my own yet. I am attempting to get a simple test like this to pass (using mocha & chai):

describe("SimpleDecalRoulette", function() {
      it("decal SVG can be loaded", function() {
        var decalLoaded = false;    
        var SVG = Snap.load("/base/app/img/decal.svg", function(fragment) {
          decalLoaded = true;
        });
        expect(decalLoaded).to.be.true;
      });
    });

Initially, I assumed that including the svg file in the "files" directive of karma.conf.js would suffice:

files: [
  { pattern: 'app/bower_components/lodash/dist/lodash.min.js', watched: false, included: true, served: true },
  { pattern: 'app/bower_components/jquery/dist/jquery.min.js', watched: false, included: true, served: true },
  { pattern: 'app/bower_components/snap.svg/dist/snap.svg-min.js', watched: false, included: true, served: true },
  { pattern: 'app/js/\*\*/\*.js', watched: true, included: true, served: true },
  { pattern: 'app/img/decal.svg', watched: true, included: false, served: true },
  { pattern: 'app/img/assets.svg', watched: true, included: false, served: true },
  'tests/\*\*/\*_spec.js'
],
proxies: {
  '/app/img/': '/base/app/img/'
}

However, attempting to load the svg files from app/img/decal.svg or base/app/img/decal.svg both resulted in 404 errors. I have also tried using the 'proxies' directive, as detailed in this SO answer, but haven't gotten that to work yet either (as seen above).

Is this something that karma can do or is this a use case that should be handled differently? I need to load and interact with SVGs for karma to be useful in writing unit tests for this game.

Community
  • 1
  • 1
jmcmichael
  • 611
  • 1
  • 7
  • 11

1 Answers1

1

I'm doing this exact same thing and have just got it working.

My karma.conf.js includes the svg files in the files array:

{ pattern: 'src/svg/*.svg', included: false, served: true }

and in the test I can load this as:

Snap.load('base/src/svg/Drawing.svg',...);

The main difference in my test is the way that I use a deferred to make sure the SVG is loaded before I do any assertions. I'm using Jasmine 2.0 which allows for a done callback within the it function.

it('Should load the SVG', function(done) {
   Snap.load('base/src/svg/Drawing.svg', function (fragment) {
     expect(...).toBe(...);
     done();
   });
});

You can read more about Async Support here: http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support

and for version 1.3: http://jasmine.github.io/1.3/introduction.html#section-Asynchronous_Support

Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162