使用Jest抛出而不是构造函数测试ES6类时出错 [英] Testing ES6 class with Jest throws 'not a constructor' error

查看:38
本文介绍了使用Jest抛出而不是构造函数测试ES6类时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了类似的问题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"
    ]
  }

推荐答案

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

export default class MyClass { ... }

则对应的导入为:

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

或者如果您希望继续使用相同的导入语法,则在导出时删除"default":

export class MyClass { ... }

然后:

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

这篇关于使用Jest抛出而不是构造函数测试ES6类时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆