I created a new React application by create-react-app and I wanted to write a unit test to a component named \"MessageBox\" that I created in the application. This is the un
The file 'setupTests' has to be imported to the test file:
import MessageBox from "../MessageBox";
import { shallow } from 'enzyme';
import React from 'react';
import "../setupTests"
test('message box', ()=> {
...
})
Add it to your test case file.
import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { shallow, configure } from 'enzyme';
configure({adapter: new Adapter()});
test('message box', ()=> {
...
})
Also, if you don't want to import your setupTests.js file into every test file, you can place it in your package.json folder:
"jest": {
"setupTestFrameworkScriptFile": "./test/setupTests.js" }
Update:
Note: setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv.
https://jestjs.io/docs/en/configuration
I faced the same error and for some reason React wasn't picking up setupTests.js
file automatically.
I created a new file called jest.config.js
at the root directory and added
{ "jest": { "setupTestFrameworkScriptFile": "<rootDir>/path/to/your/file.js", } }
After this, error disappeared.
Note: Later on, I removed the jest.config.js
file but it still works now.
Not sure what was actually causing the problem though!
Add import React from 'react';
to the top of your file.
You are using JSX syntax <MessageBox app={app}/>
, which transpiles into React.createComponent(...)
. In order for this to work React
variable must be defined in the scope of the file.
Try sth like this;
import React from 'react';
import App from './containers/App';
import enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
enzyme.configure({ adapter: new Adapter() });
describe('App Screen', () => {
let mountedAppScreen;
let props;
const appScreen = () => {
if (!mountedAppScreen) {
mountedAppScreen = enzyme.mount(
<App {...props} />
);
}
return mountedAppScreen;
}
it("it always renders div", () => {
const divs = appScreen().find("div");
expect(divs.length).toBeGreaterThanOrEqual(1);
});
});