Michael Ploeckinger
Michael Ploeckinger

Reputation: 1634

How to resolve "Cannot find module" Error when testing react components with mocha

In all my components i have imported other components like

import PrevArrow from 'components/Slider/PrevArrow';

when I want to test a component I always get the error:

Error: Cannot find module 'components/Slider/PrevArrow'

because it assumes the wrong path. Right import method would be

import PrevArrow from '../../components/Slider/PrevArrow';

with this the test passes, but I dont want to refactor all components just because of this.

Is there a way that i can leave my import statements as they are and still get my test passed?

Thanks in advance!

Upvotes: 2

Views: 1536

Answers (1)

Michael Ploeckinger
Michael Ploeckinger

Reputation: 1634

Turns out it is because we are using webpack in our codebase.

So mocha will not work as it should. I needed to install

npm install --save-dev mocha-webpack

and rewrite my test script in package.json from

"test": "mocha './build/**/*.test.js' --compilers js:babel-core/register --require ignore-styles"

to

"test": "mocha-webpack --webpack-config webpack.config.js './build/**/*.test.js'"

and now it works

Upvotes: 1

Related Questions