Jest / Enzyme - 不能将类称为函数

问题描述 投票:0回答:1

我正在将一个大型应用程序从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
}
reactjs enzyme jest
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.