Mocha error when using babel and webpack

So, I use webpack, babel and mocha. When I have a code like this:

import userImage from '../../images/user.png';

and I create using webpack, userImage leads to a file path string, since I use a file loader for images (requirements require me not to embed images), however, when I try to run my mocha tests using:

./node_modules/.bin/babel-node ./node_modules/.bin/babel-istanbul cover ./node_modules/.bin/_mocha

I get a syntax error:

SyntaxError: /repositories/react-seed/web/app/images/user.png: Unexpected character ' ' (1:0)
> 1 |  PNG
    | ^
  2 |
  3 | 

I also get this error when uninstalling istanbul. Thus, it looks like it is trying to load the actual image file, but can parse it like JavaScript, since that is not the case.

Does anyone know a way to solve this problem?

+4
source share
2 answers

-compilers, nodejs, png . :

mocha --compilers png:./mochacfg.js

test/mocha.opts, ( ):

--compilers png:./mochacfg.js

./mochacfg.js:

require.extensions['.png'] = function(){ return null; }

png ( , ). ​​

- :

var fs = require('fs');
require.extensions['.png'] = function(module, filepath) {
  var src = fs.readFileSync(filepath).toString ('base64');
  return module._compile('module.exports = "data:image/png;base64,' + src + '";');

}
+9

, , , .

test-config.js mocha.

var jsdom = require('jsdom').jsdom;
process.env.NODE_ENV = 'test';

// -------------------------------
// Disable webpack-specific features for tests since
// Mocha doesn't know what to do with them.

['.css', '.scss', '.png', '.jpg'].forEach(ext => {
  require.extensions[ext] = () => null;
});

package.json

"test": "mocha ./test/test-setup.js './test/**/*.spec.js' --compilers js:babel-core/register",

, -.

0

Source: https://habr.com/ru/post/1629803/


All Articles