gpt4 book ai didi

reactjs - 类型错误 : Cannot call a class as a function when running Jest test

转载 作者:行者123 更新时间:2023-12-03 14:17:00 25 4
gpt4 key购买 nike

在使用 Jest 测试 React 组件的简单设置中,我在每次测试运行时收到错误“TypeError: Cannot call a class as a function”,使用 npm test

实际的 React 页面构建良好并且渲染没有错误。

我查看了与此错误相关的其他帖子,但没有一个可以帮助解决此问题的帖子似乎专门针对 Jest。

感谢任何可以提供帮助的人。

这是我的设置:

package.json

{
"name": "test-bed",
"main": "index.js",
"dependencies": {
"react": "^16.10.2",
"react-dom": "^16.10.2"
},
"devDependencies": {
"babel-jest": "^24.9.0",
"jest": "^24.9.0",
"react-test-renderer": "^16.10.2",
"@babel/core": "^7.1.2",
"@babel/plugin-proposal-class-properties": "^7.1.0",
"@babel/preset-env": "^7.1.0",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.4",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"html-webpack-plugin": "3.2.0",
"webpack": "4.22.0",
"webpack-cli": "3.1.2",
"webpack-dev-server": "3.1.10"
},
"scripts": {
"start": "webpack-dev-server --mode development",
"build": "webpack --mode production",
"test": "jest"
}
}

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import TestComponent from './components/TestComponent';

ReactDOM.render(<TestComponent />, document.getElementById('app'));

src/components/TestComponent.js

export default class TestComponent extends React.Component {

render() {
return (
<p>I'm v0.0.1 of TestComponent</p>
)
}
}

__ 测试 __/test-component.snapshot.test.js

import React from 'react';
import renderer from 'react-test-renderer';

import TestComponent from '../src/components/TestComponent';

TestComponent('should display component version', () => {
const comp = renderer.create(<TestComponent/>);
let tree = comp.toJSON();
expect(tree).toMatchSnapshot();
});

最佳答案

问题是这样的:

TestComponent('should display component version', () => {
const comp = renderer.create(<TestComponent/>);
let tree = comp.toJSON();
expect(tree).toMatchSnapshot();
});

它将此解释为您想要调用 TestComponent() 函数

将其更改为:

describe('TestComponent', () => {
it('should display component version', () => {
const comp = renderer.create(<TestComponent/>);
let tree = comp.toJSON();
expect(tree).toMatchSnapshot();
});
})

关于reactjs - 类型错误 : Cannot call a class as a function when running Jest test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58346939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com