Require / import svg during mocha tests

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

When running the tests, I tried to avoid using webpack to avoid binding the mocha version to the webpack plugin. Unfortunately, when .svg imports are imported, they cannot be found. We also use css modules, and they allowed me to use css-modules-require-hook to work with importing css files.

Is there a way I could use to accomplish the same thing with SVG?

+7
javascript webpack mocha
source share
2 answers

Yes, I just found a way to exhaust the .svg module for mocha here .

Mocha can use require hooks to work with generic javascript imports, like babel-register for .js .

You can use require-hacker to add bindings to module extensions.

You can use the zero reaction component for other component loaders, such as react-svg-loader , to load .svg as a react component.

here is an example:

 import requireHacker from 'require-hacker'; const fakeComponentString = ` require('react').createClass({ render() { return null; } }) `; // for fake component requireHacker.hook('svg', path => `module.exports = ${fakeComponentString}`); 
+3
source share

I realized that this is allowed using require.extensions (in node it is deprecated , but should never go away) in order to force import of these asset types in order to result in no-op. Running mocha with the --require flag allows us to customize the runtime for our tests, starting with moka as follows:

 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 :

 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 file types to return the noop function instead of trying to load the actual file.

My code uses es6 import syntax, but I assume that babel convert it to require under covers, which allows you to use this technique.

+7
source share

All Articles