In a simple setup to get going with testing React components with Jest, I'm getting the error "TypeError: Cannot call a class as a function" on each test run, with npm test
The actual React page builds fine and renders with no errors.
I've looked at the other posts related to this error, but none that can help with this issue seem to be specific to Jest.
Thanks to anyone that can help.
Here's my setup:
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>
)
}
}
__ tests __/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();
});
The problem is this:
TestComponent('should display component version', () => {
const comp = renderer.create(<TestComponent/>);
let tree = comp.toJSON();
expect(tree).toMatchSnapshot();
});
It's interpreting this as you wanting to call the TestComponent() function
Change it to something like:
describe('TestComponent', () => {
it('should display component version', () => {
const comp = renderer.create(<TestComponent/>);
let tree = comp.toJSON();
expect(tree).toMatchSnapshot();
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With