[英]Require/import svg during mocha tests
I have a project being built with webpack. 我有一个用webpack构建的项目。 This allows me to import .svg
files to create React components. 这允许我导入.svg
文件来创建React组件。
When running tests I have been attempting to avoid using webpack to avoid tying the mocha version to a webpack plugin. 在运行测试时,我一直试图避免使用webpack来避免将mocha版本绑定到webpack插件。 Unfortunately, when the .svg
imports are hit, they fail to be found. 不幸的是,当.svg
导入被攻击时,找不到它们。 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. 我们也使用css模块,他们允许我使用css-modules-require-hook
来处理css文件的导入。
Is there a technique I could use to accomplish the same thing with SVGs? 有没有一种技术可以用SVG来完成同样的事情?
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. 我看到这通过使用require.extensions
解决(在节点中这是不推荐的 ,但永远不会消失)强制导入这些类型的资产导致无操作。 Starting mocha
with the --require
flag lets us configure the runtime environment for our tests so starting mocha like this: 使用--require
标志启动mocha
可以让我们为测试配置运行时环境,这样就可以像这样启动mocha:
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: 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 types of files to return the noop
function instead of attempting to load the actual file. 这将导致所有上述类型的文件返回noop
函数,而不是尝试加载实际文件。
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. 我的代码使用的是es6
import
语法,但我假设babel
正在将其转换为require
的封面,这使得该技术能够正常工作。
Yes, I just find a way to mock .svg
module for mocha
here . 是的,我只是找到一种方式来嘲笑.svg
为模块mocha
这里 。
Mocha can use require hooks
to deal with universal javascript import, such as babel-register
for .js
. Mocha可以使用require hooks
来处理通用的javascript导入,比如babel-register
for .js
。
You can use require-hacker to add hooks to extensions of modules. 您可以使用require-hacker为模块的扩展添加挂钩。
You can use a null react component mock for other component loaders such as react-svg-loader
to load .svg
as a react component. 您可以将null react组件模拟用于其他组件加载器(例如react-svg-loader
以将.svg
作为反应组件加载。
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}`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.