Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require/import svg during mocha tests

I have a project being built with webpack. This allows me to import .svg files to create React components.

When running tests I have been attempting to avoid using webpack to avoid tying the mocha version to a webpack plugin. Unfortunately, when the .svg imports are hit, they fail to be found. We are also using css modules, and they allowed me to use the css-modules-require-hook to work around the importing of css files.

Is there a technique I could use to accomplish the same thing with SVGs?

like image 319
Matt Avatar asked May 16 '16 17:05

Matt


2 Answers

I saw this solved by using require.extensions (in node this is deprecated, but should never go away) to force importing these types of assets to result in an no-op. Starting mocha with the --require flag lets us configure the runtime environment for our tests so starting mocha like this:

NODE_PATH=./app mocha -w --compilers js:babel-core/register --require ./app/lib/testHelper.js --require ./app/lib/testNullCompiler.js 'app/**/*.spec.@(js|jsx)' --watch-extensions js,jsx

where testNullCompiler.js is:

const noop = () => 1;

require.extensions['.css'] = noop;
require.extensions['.scss'] = noop;
require.extensions['.png'] = noop;
require.extensions['.jpg'] = noop;
require.extensions['.jpeg'] = noop;
require.extensions['.gif'] = noop;
require.extensions['.svg'] = noop;

This will cause all the above types of files to return the noop function instead of attempting to load the actual file.

My code is using the es6 import syntax but I'm assuming that babel is converting that to require under the covers which enables this technique to work.

like image 62
pherris Avatar answered Nov 09 '22 22:11

pherris


Yes, I just find a way to mock .svg module for mocha here.

Mocha can use require hooks to deal with universal javascript import, such as babel-register for .js.

You can use require-hacker to add hooks to extensions of modules.

You can use a null react component mock for other component loaders such as react-svg-loader to load .svg as a react component.

here is the example:

import requireHacker from 'require-hacker';

const fakeComponentString = `
  require('react').createClass({
    render() {
      return null;
    }
  })
`;

// for fake component
requireHacker.hook('svg', path => `module.exports = ${fakeComponentString}`);
like image 21
Mr.D.Q Avatar answered Nov 09 '22 23:11

Mr.D.Q