Jest: cannot find module required inside module to

2019-06-17 05:45发布

问题:

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?

回答1:

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"
]


回答2:

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)



回答3:

For others ending up here trying to use Jest with TypeScript: you need to include ts in the moduleFileExtensions, e.g.:

"moduleFileExtensions": [
  "js",
  "jsx",
  "json",
  "node",
  "ts"
]

You also need a transform for *.ts files:

transform: {
  "^.+\\.vue$": "vue-jest",
  "^.+\\.js$": "babel-jest",
  "^.+\\.(ts|tsx)$": "ts-jest"
},