目錄
testMatch定義的路徑明明對,卻Jest找不到test file
如果專案的結構是底下有多個workspace的(monorepo),且每個workspace有各自的jest.config.j(t)s,很可能是因為src並不是指向該workspace內的src
而是專案根目錄的src,但是專案根目錄底下根本沒有src,所以才找不到
這時可以用rootDir來改變src的指向為該workspace根目錄的src
Cannot use import statement outside module
使用Typescript的時
因為Jest不能直接讀Typescript,所以需要ts-jest來將它轉為Javascript
yarn add ts-jest --dev
//jest.config.js
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.ts?$': 'ts-jest',  // 重點在這行,這行的意思是用ts-jest把所有的ts檔編譯
  },
};
使用Javascript時
Jest在node環境下執行的,而node的預設標準是CommonJS,所以若是使用ESM的情況可能會報錯
可以使用babel-plugin-import,如果沒裝過@babel/core記得一同安裝
yarn add babel-plugin-import --dev
// babel.config.js
module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-typescript',
    [
      '@babel/preset-react',
      {
        runtime: 'automatic',
      },
    ],
  ],
  plugins:[ // 加上plugins
      ['import', {
          "libraryName": "@material-ui/core",
          // 相對於(你要用的)library的package.json,檔案所在的路徑,預設會是lib
          "libraryDirectory": "./node/index.js",
      }]
  ]
};
yarn add @babel/preset-env --dev
module.exports = {
  presets: [
    [ // 加上@babel/preset-env
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
  ],
};
Jest讀不懂TSX
因為Jest不能直接讀Typescript,當然TSX也不行
你可能會想問那為什麼create-react-app建立的專案可以,那是因為在你看不見的地方bundler都幫你處理好了

可以先照Next官方文件建立環境看看
要是再不行可以用@babel/preset-react、@babel/preset-typescript、@babel/preset-env,如果沒裝過@babel/core記得一同安裝
yarn add @babel/preset-react @babel/preset-typescript @babel/preset-env
然後新增babel.config.js
// babel.config.js
module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-typescript',
    [
      '@babel/preset-react',
      {
        // automatic會自動引入編譯JSX的function,預設值的classic則否
        runtime: 'automatic', 
      },
    ],
  ],
};


