【问题标题】:Jest: cannot find module required inside module to be tested (relative path)开玩笑:在要测试的模块内找不到所需的模块(相对路径)
【发布时间】:2016-05-24 23:30:00
【问题描述】:

我有这个组件:

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

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

这基于某些逻辑会在内部呈现另一个组件(VideoTag 或 JWPlayer),但是当我尝试在 jest 文件中对其进行测试时,我得到了错误:

找不到模块“./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 如何处理相对路径?

【问题讨论】:

    标签: javascript node.js unit-testing reactjs jestjs


    【解决方案1】:

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

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

    希望这将帮助某人!

    【讨论】:

    • 这救了我,谢谢!!!我在本地有多个库,tsconfig 管理他们的paths,我猜jesttypescript 没有正确映射源文件的模块导入(即使它在测试文件中的导入工作正常)。
    • 如果你能提供一个例子,那就太棒了
    • @JoãoIgnacio 假设您将其导入原始 js 文件 import * as Components from '/static/myApp/js/components.js'。然后在 moduleNameWrapper 中,您将拥有以下内容:"^/static/myApp/js/(.*)": "&lt;rootDir&gt;/myProject/myApp/static/myApp/js/$1"。请注意,我以 Django 项目和应用程序为例。查看 /static/myApp/js/ 是如何放在 moduleNameWrapper 中的
    【解决方案2】:

    问题不在于路径,它只是在寻找带有 .js 扩展名的模块,在 jest 配置中添加 .jsx 后它就可以工作了:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

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

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

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

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

          【讨论】:

            猜你喜欢
            • 2021-05-30
            • 1970-01-01
            • 2020-03-25
            • 2020-12-21
            • 1970-01-01
            • 2019-07-27
            • 1970-01-01
            • 1970-01-01
            • 2019-02-22
            相关资源
            最近更新 更多