【问题标题】:Testing ES6 class with Jest throws 'not a constructor' error用 Jest 测试 ES6 类会抛出“不是构造函数”错误
【发布时间】:2018-10-02 03:44:15
【问题描述】:

我发现了一个类似的问题here,但似乎没有答案。

我正在尝试使用 Jest 测试一个 ES6 类,如下所示:

// src/myclass.js
export default class MyClass {
    constructor(options) {
        // currently this is empty while I debug this problem
    }
}

和测试:

// test/myclass.test.js
import { MyClass } from '../src/myclass.js';

describe("Test Constructor", () => {

    test("doesn't throw error when constructed", async () => {
        expect(() => {
            const testMyClass = new MyClass();
        }).not.toThrowError();
    }

});

当我运行测试时,Jest 抛出一个错误:

TypeError: _myClass.MyClass 不是构造函数

我最好的猜测是这是 babel 配置的问题,但我似乎无法弄清楚。如果我将 MyClass 更改为函数而不是类并删除导出/导入(即类前的处理方式),那么它会按预期工作。

这是我在 package.json 中的配置:

"devDependencies": {
    "@babel/core": "^7.1.2",
    "@babel/preset-env": "^7.1.0",
    "babel-core": "^7.0.0-bridge.0",
    "gulp": "^3.9.1",
    "gulp-babel": "^8.0.0",
    "gulp-jest": "^4.0.2",
    "gulp-rename": "^1.4.0",
    "gulp-uglify": "^3.0.1",
    "jest": "^23.6.0",
    "jest-cli": "^23.6.0",
    "pump": "^3.0.0",
    "regenerator-runtime": "^0.12.1"
  },
  "babel": {
    "presets": [
      "@babel/preset-env"
    ]
  },
  "jest": {
    "testPathIgnorePatterns": [
      "<rootDir>/node_modules/",
      "<rootDir>/test/._*.test.js"
    ],
    "testEnvironment": "jsdom",
    "setupFiles": [
      "<rootDir>/src/myclass.es6.js"
    ]
  }

【问题讨论】:

    标签: javascript babeljs jestjs es6-class babel-jest


    【解决方案1】:

    您的导入和导出语法不匹配。您需要更改其中一个才能使其正常工作。如果要使用默认导出,例如:

    export default class MyClass { ... }
    

    那么对应的import就是:

    import MyClass from '../src/myclass.js'
    

    或者,如果您想继续使用相同的导入语法,则在导出时删除“默认”:

    export class MyClass { ... }
    

    然后:

    import { MyClass } from '../src/myclass.js'
    

    【讨论】:

      【解决方案2】:

      您的课程默认导出...

      // try this
      import MyClass from '../src/myclass.js';
      // instead of this
      import { MyClass } from '../src/myclass.js';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-31
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-05
        • 1970-01-01
        • 2018-09-27
        相关资源
        最近更新 更多