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

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

本文关键字:模块 相对 路径 内部 测试 Jest 找不到      更新时间:2023-09-26

我有这个组件:

import React from 'react';
import VideoTag from './VideoTag';
import JWPlayer from './JWPlayer';
class VideoWrapper extends React.Component {
//... component code
}

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

找不到模块"./视频标记">

这三个 coponent 位于同一个目录中,这就是为什么当我转译它并在浏览器中看到它运行时它实际上有效,但看起来 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';

我如何告诉开玩笑如何处理相对路径?

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

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

希望这会帮助某人!

问题不在于路径,它只寻找扩展名为.js模块,它在开玩笑配置中添加 .jsx 后工作:

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

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

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

对于其他人最终试图将 Jest 与 TypeScript 一起使用: 您需要在moduleFileExtensions中包含ts,例如:

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

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

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