Enzyme expects an adapter to be configured

前端 未结 15 1437
太阳男子
太阳男子 2020-12-24 04:53

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

相关标签:
15条回答
  • 2020-12-24 05:18

    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', ()=> {
         ...
    })
    
    0 讨论(0)
  • 2020-12-24 05:23

    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', ()=> {
         ...
    })
    
    0 讨论(0)
  • 2020-12-24 05:24

    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

    0 讨论(0)
  • 2020-12-24 05:26

    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!

    0 讨论(0)
  • 2020-12-24 05:30

    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.

    0 讨论(0)
  • 2020-12-24 05:30

    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);
      });
    });
    
    0 讨论(0)
提交回复
热议问题