通过Jest使用export {default}

时间:2019-07-17 17:03:10

标签: javascript export jestjs

我正在使用index.js文件从同一文件夹(对象/矩形)中导出多个文件:

// index.js
export { default } from './RectangleBuilder'
export { default as Rectangle } from './Rectangle'
export { default as MovableRectangle } from './MovableRectangle'

一切正常,请在运行测试时期待: 开玩笑正在尝试运行这段代码

import RectangleBuilder from 'objects/Rectangle'
import Point from 'objects/Point'
import TrapSystem from 'objects/TrapSystem'
import Interval from 'objects/Interval'
import Color from 'effects/Color'

const spawn = new RectangleBuilder(20 * 2, 100 * 2, 80 * 2, 80 * 2)
  .withColor(new Color('lightblue'))
  .build()

这给了我这个错误:

TypeError: _Rectangle2.default is not a constructor

   6 | 
   7 | console.log(RectangleBuilder)
>  8 | const spawn = new RectangleBuilder(20 * 2, 100 * 2, 80 * 2, 80 * 2)
     |               ^
   9 |   .withColor(new Color('lightblue'))
  10 |   .build()
  11 | 

RectangleBuilder的确是undefined

是否有办法让Jest正确导入,就像在浏览器中运行代码时一样?

编辑:

Jest需要将es6导入转换为commonJS导入,因为它正在节点中运行。 这可能来自我的配置吗?

// .babelrc
{
  "plugins": [
    [
      "module-resolver",
      {
        "root": ["./src"],
        "alias": {
          "test": "./test",
          "underscore": "lodash"
        }
      }
    ]
  ],
  "presets": [["@babel/preset-env", { "targets": { "node": "current" } }]],
  "env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}


// webpack.config.babel.js
module.exports = {
  entry: './src/sketch.js',
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
}

1 个答案:

答案 0 :(得分:0)

我能够使用模拟解决此问题。

例如,我从测试文件physics.spec.js中收到此错误

TypeError: _RectangleBuilder.default is not a constructor

   5 | import Color from 'effects/Color'
   6 | 
>  7 | const spawn = new RectangleBuilder(20 * 2, 100 * 2, 80 * 2, 80 * 2)
     |               ^
   8 |   .withColor(new Color('lightblue'))
   9 |   .build()
  10 | 

  at Object.<anonymous> (src/maps/1.js:7:15)
  at Object.<anonymous> (src/sketch.js:23:1)
  at Object.<anonymous> (src/engine/physics.js:5:1)
  at Object.<anonymous> (src/objects/Rectangle/Rectangle.js:2:1)
  at Object.<anonymous> (src/objects/Rectangle/RectangleBuilder.js:1:1)
  at Object.<anonymous> (src/objects/Rectangle/index.js:1:1)
  at Object.<anonymous> (src/engine/__tests__/physics.spec.js:1:1)

我遇到的主要问题是那些进口链。一个文件导入另一个文件,该文件导入另一个我不需要测试的文件:

// physics.spec.js
import {
  isPointInRectangle,
  segmentIntersectsCircle,
  circleIntersectsRectangle
} from '../physics.js'

// physics.js
import { WIDTH, HEIGHT } from 'sketch.js'

我唯一要做的就是添加此行:

jest.mock('sketch.js')

physics.spec.js中,以便它在测试期间完全忽略此文件。