mardi 3 mai 2016

Webpack + babel loader + karma configuration

I've setup testing environment for the project with ES2015. I use webpack for bundling modules and transpiling ES2015 code to ES5 with babel loader. I do understand almost everything I've written except one small thing.

In karma.config.js file we have the following two properties:

// some config here

files: [
  'spec/tests.bundle.js'
],
preprocessors: {
    'spec/tests.bundle.js': ['webpack', 'sourcemap']
},

// and the rest config goes below

I do understand, that we say to karma "load this spec/tests.bundle.js file and run tests stored there". Also we say "hey, karma, make some pre-execute work with this spec/tests.bundle.js. I want you to webpack and sourcemap it before you run the tests."

But when I look at this tests.bundle.js file I'm confused a little. I have there this code (and it seems it's mandatory for all karma+webpack+babel set):

var context = require.context('.', true, /.+\.spec\.js?$/);
context.keys().forEach(context);
module.exports = context;

OK, here I can somehow understand the first line: I guess it's looking for all files that match /.+\.spec\.js?$/ pattern, i.e. all test files with spec.js on the end. As written in documentation, it stores it in context:

It(context) contains references to all modules in that directory that can be required with a request matching the regular expression. The context module contains a map which translates requests to module ids.

The last line is absolutely clear.

Confusion causes the middle line. If I console.log(context.keys()); it logs me an array of names of matched files. As I understand .forEach(context) part is traversing this array of names and apply context as a callback(iteratee) of this array. When calling console.log(context.keys().forEach(context)) it logs undefined.

So here is the question: could somebody easily explain what does this callback do to each of array element? Why it doesn't work without this middle line?

Aucun commentaire:

Enregistrer un commentaire