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?
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.
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}`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With