【问题标题】:Jest/Enzyme - Cannot call a class as a functionJest/Enzyme - 不能将类作为函数调用
【发布时间】:2017-12-18 23:42:40
【问题描述】:

我正在将一个大型应用程序从 Karma/Mocha 迁移到 Jest 进行测试。我为我们的主页组件设置了一些非常基本的测试,但是当我运行它们时,我得到了相同的TypeError: Cannot call a class as a function 错误。简单组件示例:

import React, { Component } from 'react'

export default class Intro extends Component {
    render() {
        const intro = 'this is a test message'

        return (
            <div>
                <p>
                    { intro }
                </p>
            </div>
        )
    }
}

超级基础测试:

import React from 'react'
import ReactDOM from 'react-dom'
import Intro from 'Intro'

it('renders without crashing', () => {
    const div = document.createElement('div')
    ReactDOM.render(<Intro />, div)
})

这个测试给出了前面提到的TypeError。我相信这个问题与 Jest 如何与 Babel/Webpack (v1.12.9) 集成有关,但我无法弄清楚具体是什么问题。这是我的babel.rc

{
  "presets": ["env", "react", "stage-0"],
  "plugins": ["transform-runtime", "add-module-exports", "transform-decorators-legacy", "transform-flow-strip-types"]
}

还想知道这是否是 Babel 对等依赖项的问题?以下是我的package.json 中的一些相关部分:

"babel-core": "^6.3.17",
"babel-eslint": "^5.0.0-beta6",
"babel-jest": "^21.2.0",
"babel-loader": "^6.2.0",
"babel-plugin-add-module-exports": "^0.1.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-plugin-transform-flow-strip-types": "^6.22.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-react-hmre": "^1.0.0",
"babel-preset-stage-0": "^6.3.13",
"babel-register": "^6.3.13",
"babel-runtime": "^6.26.0",
"jest": "^22.0.1",
"jest-cli": "^22.0.0",
"jest-enzyme": "^4.0.1"

任何想法是什么原因造成的?如有需要,可以分享更多代码。

编辑:这是我的jest.config.js

module.exports = {
    moduleFileExtensions: ['js', 'jsx'],
    moduleDirectories: ['node_modules'],
    moduleNameMapper: {
        Intro: '<rootDir>/src/components/Home/Intro.jsx',
        styles: '<rootDir>/src/styles/index.js'
    },
    roots: ['<rootDir>/tests/'],
    verbose: true
}

【问题讨论】:

  • 您是否尝试过使用Intro的相对路径?
  • 是的。我已经用我的jest.config.js 文件修改了我的问题以及我如何使用moduleNameWrapper

标签: reactjs enzyme jestjs


【解决方案1】:

原来问题出在我设置moduleNameMapper 的方式上。我通过在初始目录中包含测试文件而不是创建新的测试文件夹来更改我的文件夹结构。我还将我的 Jest 配置移至 package.json 并在那里进行了一些小改动。现在我的测试失败了,但方式与我预期的一样。

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 2020-12-13
    • 2018-03-28
    • 1970-01-01
    • 2019-09-26
    • 2017-06-25
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多