Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest: cannot find module required inside module to be tested (relative path)

I have this component:

import React from 'react';
import VideoTag from './VideoTag';
import JWPlayer from './JWPlayer';

class VideoWrapper extends React.Component {
//... component code
}

That based on some logic renders another component inside ( VideoTag or JWPlayer) but when I try to test it in a jest file i get the error:

Cannot find module './VideoTag'

The three coponents are in the same directory that's why it actually works when I transpile it and see it in action in a browser but looks like Jest is having problems resolving those relative paths, this is the jest file:

jest.dontMock('../src/shared/components/Video/VideoWrapper.jsx');

import React from 'react';
import ReactDOM from 'react-dom';
TestUtils from 'react-addons-test-utils';

import VideoWrapper from '../src/shared/components/Video/VideoWrapper.jsx';

describe('VideoWrapper tests', () => {
  it('Render JWPlayer', () => {

      let vWrapper = TestUtils.renderIntoDocument(
      < VideoWrapper model={model} />
  );

  });
});

The error is at line:

import VideoWrapper from '../src/shared/components/Video/VideoWrapper.jsx';

How do I tell jest how to handle relative paths?

like image 685
ferflores Avatar asked Feb 13 '16 22:02

ferflores


3 Answers

The problem were not the paths, It was looking for modules only with .js extension, it worked after adding the .jsx in the jest configuration:

"moduleFileExtensions": [
  "js",
  "jsx"
]
like image 177
ferflores Avatar answered Nov 08 '22 18:11

ferflores


I also had to add the moduleNameMapper to my jest configuration for my tsconfig path maps in order to get my tests to recognize the path maps I had setup. Something like this:

"moduleNameMapper": {
      "^yourPath/(.*)": "<rootDir>\\yourPath\\$1"
    }

Hopefully this will help someone down the line!

like image 14
Justin Avatar answered Nov 08 '22 19:11

Justin


You don't need to add moduleFileExtensions in the configuration for these two options since jest uses ['js', 'jsx', 'json', 'node'] as default file extensions. (Unless you want to specifically skip any option that is)

like image 1
Sahil Jain Avatar answered Nov 08 '22 18:11

Sahil Jain