Jest:在要测试的模块中找不到所需的模块(相对路径)

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

我有这个组件:

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

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

基于某些逻辑在内部呈现另一个组件(VideoTag 或 JWPlayer)但是当我尝试在一个笑话文件中测试它时我得到错误:

找不到模块“./VideoTag”

这三个组件在同一个目录中,这就是为什么当我转译它并在浏览器中看到它在运行时它实际上起作用但看起来 Jest 在解析这些相对路径时遇到问题,这是 jest 文件:

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} />
  );

  });
});

错误在行:

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

如何告诉 jest 如何处理相对路径?

问题不在于路径,它正在寻找仅具有 .js 扩展名的模块,在 jest 配置中添加 .jsx 后它起作用了:

"moduleFileExtensions": [
  "js",
  "jsx"
]

你不需要在配置中为这两个选项添加 moduleFileExtensions,因为 jest 默认使用 ['js'、'jsx'、'json'、'node']文件扩展名。 (除非你想特别跳过任何选项)

对于最终在这里尝试将 Jest 与 TypeScript 结合使用的其他人:您需要在 moduleFileExtensions 中包含 ts,例如:

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

您还需要对 *.ts 个文件进行转换:

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

我还必须将 moduleNameMapper 添加到我的 tsconfig 路径映射的 jest 配置中,以便让我的测试识别我设置的路径映射。像这样:

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

希望这对以后的人有所帮助!

在我的案例中,问题是 import 也区分大小写。检查您的 import 语句并确保它与文件名完全匹配!