簡體   English   中英

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),但是當我嘗試在 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 如何處理相對路徑?

問題不在於路徑,它正在尋找僅具有 .js 擴展名的模塊,在 jest 配置中添加 .jsx 后它起作用了:

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

我還必須將moduleNameMapper添加到我的 tsconfig 路徑映射的 jest 配置中,以便讓我的測試識別我設置的路徑映射。 像這樣的東西:

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

希望這會幫助某人!

您不需要在這兩個選項的配置中添加 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"
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM