JavaScript Testing utilities for React

Last update: May 11, 2022

Enzyme

Join the chat at https://gitter.im/enzymejs/enzyme

npm Version License Build Status Coverage Status

Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components' output. You can also manipulate, traverse, and in some ways simulate runtime given the output.

Enzyme's API is meant to be intuitive and flexible by mimicking jQuery's API for DOM manipulation and traversal.

Upgrading from Enzyme 2.x or React < 16

Are you here to check whether or not Enzyme is compatible with React 16? Are you currently using Enzyme 2.x? Great! Check out our migration guide for help moving on to Enzyme v3 where React 16 is supported.

Installation

To get started with enzyme, you can simply install it via npm. You will need to install enzyme along with an Adapter corresponding to the version of react (or other UI Component library) you are using. For instance, if you are using enzyme with React 16, you can run:

npm i --save-dev enzyme enzyme-adapter-react-16

Each adapter may have additional peer dependencies which you will need to install as well. For instance, enzyme-adapter-react-16 has peer dependencies on react and react-dom.

At the moment, Enzyme has adapters that provide compatibility with React 16.x, React 15.x, React 0.14.x and React 0.13.x.

The following adapters are officially provided by enzyme, and have the following compatibility with React:

Enzyme Adapter Package React semver compatibility
enzyme-adapter-react-16 ^16.4.0-0
enzyme-adapter-react-16.3 ~16.3.0-0
enzyme-adapter-react-16.2 ~16.2
enzyme-adapter-react-16.1 ~16.0.0-0 || ~16.1
enzyme-adapter-react-15 ^15.5.0
enzyme-adapter-react-15.4 15.0.0-0 - 15.4.x
enzyme-adapter-react-14 ^0.14.0
enzyme-adapter-react-13 ^0.13.0

Finally, you need to configure enzyme to use the adapter you want it to use. To do this, you can use the top level configure(...) API.

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

3rd Party Adapters

It is possible for the community to create additional (non-official) adapters that will make enzyme work with other libraries. If you have made one and it's not included in the list below, feel free to make a PR to this README and add a link to it! The known 3rd party adapters are:

Adapter Package For Library Status
enzyme-adapter-preact-pure preact (stable)
enzyme-adapter-inferno inferno (work in progress)

Running Enzyme Tests

Enzyme is unopinionated regarding which test runner or assertion library you use, and should be compatible with all major test runners and assertion libraries out there. The documentation and examples for enzyme use Mocha and Chai, but you should be able to extrapolate to your framework of choice.

If you are interested in using enzyme with custom assertions and convenience functions for testing your React components, you can consider using:

Using Enzyme with Mocha

Using Enzyme with Karma

Using Enzyme with Browserify

Using Enzyme with SystemJS

Using Enzyme with Webpack

Using Enzyme with JSDOM

Using Enzyme with React Native

Using Enzyme with Jest

Using Enzyme with Lab

Using Enzyme with Tape and AVA

Basic Usage

Shallow Rendering

import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import sinon from 'sinon';

import MyComponent from './MyComponent';
import Foo from './Foo';

describe('<MyComponent />', () => {
  it('renders three <Foo /> components', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find(Foo)).to.have.lengthOf(3);
  });

  it('renders an `.icon-star`', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find('.icon-star')).to.have.lengthOf(1);
  });

  it('renders children when passed in', () => {
    const wrapper = shallow((
      <MyComponent>
        <div className="unique" />
      </MyComponent>
    ));
    expect(wrapper.contains(<div className="unique" />)).to.equal(true);
  });

  it('simulates click events', () => {
    const onButtonClick = sinon.spy();
    const wrapper = shallow(<Foo onButtonClick={onButtonClick} />);
    wrapper.find('button').simulate('click');
    expect(onButtonClick).to.have.property('callCount', 1);
  });
});

Read the full API Documentation

Full DOM Rendering

import React from 'react';
import sinon from 'sinon';
import { expect } from 'chai';
import { mount } from 'enzyme';

import Foo from './Foo';

describe('<Foo />', () => {
  it('allows us to set props', () => {
    const wrapper = mount(<Foo bar="baz" />);
    expect(wrapper.props().bar).to.equal('baz');
    wrapper.setProps({ bar: 'foo' });
    expect(wrapper.props().bar).to.equal('foo');
  });

  it('simulates click events', () => {
    const onButtonClick = sinon.spy();
    const wrapper = mount((
      <Foo onButtonClick={onButtonClick} />
    ));
    wrapper.find('button').simulate('click');
    expect(onButtonClick).to.have.property('callCount', 1);
  });

  it('calls componentDidMount', () => {
    sinon.spy(Foo.prototype, 'componentDidMount');
    const wrapper = mount(<Foo />);
    expect(Foo.prototype.componentDidMount).to.have.property('callCount', 1);
    Foo.prototype.componentDidMount.restore();
  });
});

Read the full API Documentation

Static Rendered Markup

import React from 'react';
import { expect } from 'chai';
import { render } from 'enzyme';

import Foo from './Foo';

describe('<Foo />', () => {
  it('renders three `.foo-bar`s', () => {
    const wrapper = render(<Foo />);
    expect(wrapper.find('.foo-bar')).to.have.lengthOf(3);
  });

  it('renders the title', () => {
    const wrapper = render(<Foo title="unique" />);
    expect(wrapper.text()).to.contain('unique');
  });
});

Read the full API Documentation

React Hooks support

Enzyme supports react hooks with some limitations in .shallow() due to upstream issues in React's shallow renderer:

  • useEffect() and useLayoutEffect() don't get called in the React shallow renderer. Related issue

  • useCallback() doesn't memoize callback in React shallow renderer. Related issue

ReactTestUtils.act() wrap

If you're using React 16.8+ and .mount(), Enzyme will wrap apis including .simulate(), .setProps(), .setContext(), .invoke() with ReactTestUtils.act() so you don't need to manually wrap it.

A common pattern to trigger handlers with .act() and assert is:

const wrapper = mount(<SomeComponent />);
act(() => wrapper.prop('handler')());
wrapper.update();
expect(/* ... */);

We cannot wrap the result of .prop() (or .props()) with .act() in Enzyme internally since it will break the equality of the returned value. However, you could use .invoke() to simplify the code:

const wrapper = mount(<SomeComponent />);
wrapper.invoke('handler')();
expect(/* ... */);

Future

Enzyme Future

Contributing

See the Contributors Guide

In the wild

Organizations and projects using enzyme can list themselves here.

License

MIT

GitHub

https://github.com/enzymejs/enzyme
Comments
  • 1. Add support for react context element types, fixes #1509

    There are some outstanding support concerns here with shallow rendered per https://github.com/facebook/react/issues/12152 but i wasn't attempting to fix those here. This just adds support for traversal over said elements. I was not sure how to structure the peer deps in a way that would exercise this test as well...

    cc @aweary

    Reviewed by jquense at 2018-02-05 16:18
  • 2. Testing a Redux-connected component using Enzyme

    Enzyme

    i) What is the least error-prone way to test a Redux-connected Componet using Enzyme? I have checked many links and articles but haven't found a satisfactory answer. It's confusing me a lot. ii)How can I test whether my component is getting certain props or not using Enzyme?

    Versions

    • React-Boilerplate : Current Version
    • Node/NPM: ^6
    • Browser: Chrome
    • Enzyme: Current Version
    Reviewed by mrsaeeddev at 2017-06-23 10:16
  • 3. Testing Hooks with shallow: Invariant Violation

    Current behavior

    When testing component which contains newly released React Hooks using shallow, it crashes: Invariant Violation: Hooks can only be called inside the body of a function component.

    Everything works fine at run time or when testing with render:

    My test component:

    import * as React from 'react';
    
    function Test() {
        const [myState, setMyState] = React.useState('Initial state');
    
        const changeState = () => setMyState('State updated');
    
        return (
            <div>
                {myState}
                <button onClick={changeState}>Change</button>
            </div>
        );
    }
    
    export default Test;
    

    My test file:

    import { shallow } from 'enzyme';
    import * as React from 'react';
    import Test from './Test';
    
    it('renders without crashing', () => {
        const comp = shallow(<Test />);
    
        expect(comp.find('Test')).toMatchSnapshot();
    });
    

    Error stack trace:

    Invariant Violation: Hooks can only be called inside the body of a function component.
    
        at invariant (node_modules/react/cjs/react.development.js:125:15)
        at resolveDispatcher (node_modules/react/cjs/react.development.js:1450:28)
        at Object.useState (node_modules/react/cjs/react.development.js:1473:20)
        at Test (src/Test.tsx:4:11)
        at node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:440:38
        at ReactShallowRenderer.render (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:412:39)
        at node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:444:37
        at withSetStateAllowed (node_modules/enzyme-adapter-utils/build/Utils.js:137:16)
        at Object.render (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:443:70)
        at new ShallowWrapper (node_modules/enzyme/build/ShallowWrapper.js:206:22)
        at Object.shallow (node_modules/enzyme/build/shallow.js:21:10)
        at Object.<anonymous> (src/Test.test.tsx:6:18)
            at new Promise (<anonymous>)
        at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
        at process._tickCallback (internal/process/next_tick.js:68:7)
    

    Expected behavior

    Tests should run

    Your environment

    Fresh create-react-app-typescript install with react 16.7.0-alpha-0

    API

    • [x] shallow
    • [ ] mount
    • [ ] render

    Version

    | library | version | ------------------- | ------- | enzyme | 3.8.0 | react | 16.7.0-alpha.0 | react-dom | 16.7.0-alpha.0 | react-test-renderer | | adapter (below) |

    Adapter

    • [x] enzyme-adapter-react-16
    • [ ] enzyme-adapter-react-16.3
    • [ ] enzyme-adapter-react-16.2
    • [ ] enzyme-adapter-react-16.1
    • [ ] enzyme-adapter-react-15
    • [ ] enzyme-adapter-react-15.4
    • [ ] enzyme-adapter-react-14
    • [ ] enzyme-adapter-react-13
    • [ ] enzyme-adapter-react-helper
    • [ ] others ( )
    Reviewed by TdyP at 2018-12-11 11:02
  • 4. Support React.lazy and React.Suspense

    Fixes #1917 .

    Given a component wrapped by React.lazy in <Suspense /> It'll plainly render a <Lazy /> in shallow and render fallback component in mount.

    There are something I'm not sure / still working on:

    1. What should displayName of the component returned by React.lazy be? Currently I directly named it as Lazy. Not sure if it's something we could define by ourselves.

    2. I'm trying to add an waitUntilLazyLoaded() on ReactWrapper, which will return a promise resolving when the dynamic import loaded and React trigger the re-render, so we can write some tests like:

    
    const LazyComponent = lazy(() => import('/path/to/dynamic/component'));
    const Fallback = () => <div />;
    const SuspenseComponent = () => (
        <Suspense fallback={<Fallback />}>
          <LazyComponent />
        </Suspense>
    );
    
    const wrapper = mount(<SuspenseComponent />)
    await wrapper.waitUntilLazyLoaded()
    
    expect(wrapper.find('DynamicComponent').to.have.lengthOf(1)
    
    

    But I don't know how to detect if all the lazy loaded component inside <Suspense /> has completeted loading. It looks like that we have to hack around react fiber. @ljharb Would you know any way to detect this?

    Also note that this PR add babel-plugin-dynamic-import-node and babel-plugin-syntax-dynamic-import for using import(), babel-eslint in enzyme-adapter-react-16 and enzyme-test-suite for dynamic import support of eslint.

    Reviewed by chenesan at 2019-01-10 17:11
  • 5. Setting text value of input

    To set the value of an input currently I have to do:

    const form = mount(<MyComponent />);
    const input = form.find('input').get(0);
    input.value = 'Blah blah';
    

    It would be really nice in my opinion if I could instead do something akin to jQuery:

    form.find('input').text('Blah blah')
    // or probably better
    form.find('input').value('Blah blah')
    

    What are your thoughts on that? I'd be happy to attempt to work on the PR :)

    Reviewed by jackfranklin at 2015-12-16 13:43
  • 6. Webpack build issues

    I'm trying to get enzyme working using a pretty standard webpack/karma setup. Webpack throws a bunch of errors related to the dependencies enzyme imports, including sinon, cheerio, and jsdom. Sinon gives webpack heartburn because it uses it's own require (which seems to be documented here: https://github.com/webpack/webpack/issues/304), and then there are a bunch of "Module not found" errors for jsdom and cheerio.

    I'm importing enzyme as described in the docs and can't really think of anything else I might be missing, so I'm curious if anyone else is trying to use webpack and running into a similar issue, or if there's just something weird with my configuration. I'd expect to be able to just import it and have it work, but maybe I need to do something with those external libraries?

    Here's my test file for reference:

    import expect from 'expect';
    import { shallow } from 'enzyme';
    import React from 'react';
    import Button from '../Button';
    
    describe('Button', () => {
        it('should render children passed in', () => {
            const wrapper = shallow(
                <Button><div className="foo" /></Button>
            );
    
            expect(wrapper.contains(<div className="foo" />)).toBe(true);
        });
    });
    

    I won't paste the entire error log from webpack because it's pretty long, but here's a sample:

    
    WARNING in ./~/enzyme/~/jsdom/~/acorn/dist/acorn.js
    Critical dependencies:
    1:478-485 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
     @ ./~/enzyme/~/jsdom/~/acorn/dist/acorn.js 1:478-485
    
    WARNING in ./~/enzyme/~/jsdom/~/acorn/dist/walk.js
    Critical dependencies:
    1:503-510 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
     @ ./~/enzyme/~/jsdom/~/acorn/dist/walk.js 1:503-510
    
    ERROR in ./~/enzyme/build/react-compat.js
    Module not found: Error: Cannot resolve module 'react/lib/ExecutionEnvironment' in /Users/agoggin/www/vhosts/hammerhead/node_modules/enzyme/build
     @ ./~/enzyme/build/react-compat.js 22:2-43
    
    ERROR in ./~/enzyme/~/cheerio/index.js
    Module not found: Error: Cannot resolve module 'json' in /Users/agoggin/www/vhosts/hammerhead/node_modules/enzyme/node_modules/cheerio
     @ ./~/enzyme/~/cheerio/index.js 11:18-38
    
    ERROR in ./~/enzyme/~/jsdom/lib/jsdom.js
    Module not found: Error: Cannot resolve module 'fs' in /Users/agoggin/www/vhosts/hammerhead/node_modules/enzyme/node_modules/jsdom/lib
     @ ./~/enzyme/~/jsdom/lib/jsdom.js 6:9-22
    

    My webpack/karma config is pretty vanilla, but it'd help I can post that, too.

    Reviewed by kgoggin at 2015-12-04 18:29
  • 7. Testing component methods

    I couldn't find any information on this, if this is a duplicate excuse me for stealing your time.

    I'm trying to test this application, but I ran into a wall when testing component methods. As an example, take this component:

    class Button extends React.Component {
      handleClick() {
        // Do something here
      }
      render() {
        // Component here
      }
    }
    

    How could I test the handleClick method here when shallowly rendering this component? (The same question applies to lifecycle methods)

    Reviewed by mxstbr at 2016-02-22 18:39
  • 8. Error: This method is only meant to be run on single node. 0 found instead.

    Clearly rendering a node. It's not picking it up..?

    render() {
        let groceriesComponents = [],
            newProductInput,
            newProductAddButton,
            clearListButton;
    
        for(var index = 0; index < this.state.groceries.length; index++) {
          groceriesComponents.push(
              <GroceryListItem
                key={index}
                grocery={this.state.groceries[index]}
              />
          );
        }
    
        newProductInput = <input className='new-item' type="text" onChange={this.inputChanged}/>;
        newProductAddButton = <button className='add-product' onClick={this.addGroceryItem}>Add new Product</button>;
        clearListButton = <button onClick={this.clearList} className='clear-list'>Clear the List</button>;
    
        return (
          <div>
            <ul>
              {groceriesComponents}
            </ul>
            {newProductInput}
            {newProductAddButton}
            {clearListButton}
          </div>
        );
      }
    }
    
    describe("Task #3 - clearing groceries list", () => {
    
        beforeEach( () => {
          component = mount(<GroceryListPart3 />);
        });
    
        it('Should render required tags', () => {
          try { component.find(".clear-list"); }
          catch(err){
            throw new Error("I can't find 'Clear the List' button");
          }
        });
    
        it('is possible to remove all list items', () => {
    
          let clearListButton = component.find(".clear-list");
          clearListButton.simulate('click');
          let groceryListItems = component.find("li");
    
          assert.equal(groceryListItems.length, 0, "There should be exactly zero elements on the groceries list");
        });
      });
    
    Error: This method is only meant to be run on single node. 0 found instead.
    
    Reviewed by cameronroe at 2016-02-14 05:05
  • 9. shallow().dive() does not work with react-redux Provider

    it('should work', () => {
      const Component = () => {
        return <div>Hello World</div>;
      };
      const wrapper = shallow(
        <Provider store={mockStore()}>
          <Component />
        </Provider>
      ).dive();
      expect(wrapper).toMatchSnapshot();
    });
    

    This is just a simple example - please assume that Component needs to have access to the react-redux context so I can use useSelector() in there, so something like .find(Component).dive() won't work

    Current behavior

    exports[`<UserMenu /> hopefully works 1`] = `<Component />`;
    

    Expected behavior

    exports[`<UserMenu /> hopefully works 1`] = `
    <div>
      Hello World
    </div>
    `;
    

    API

    • shallow

    Version

    | library | version | ------------------- | ------- | enzyme | 3.10.0 | react | 16.8.6 | react-dom | 16.8.6 | react-test-renderer | - | adapter (below) | 1.14.0

    Adapter

    • enzyme-adapter-react-16
    Reviewed by ThiefMaster at 2019-07-25 11:13
  • 10. Mount find() Does Not Find Rendered Marker

    This one is pretty frustrating. I mount this container. It does hit the code I expect that contains my css feature marker (ft-playback-error). But in the end I end up with not found.

    screencast of this issue: https://youtu.be/kh-UJTig3Qg

       it.only('renders a coordinates message in the player when no coordinates exist', () => {
          const store = createStore(reducers, {}),
    
            liveScreen = mount(
              <Provider store={createStore(reducers, {})}>
                <Live
                  breakpoint="site-web"
                  coordinates={null}
                  renderInfoInDetail={() => {}}
                  setOverlay={() => {}}
                  store={store}
                  AccessEnablerUrl=""
                  getUseUtagGlobal={() => {}}
                  pageViewEvent={() => {}}
                />
              </Provider>),
            message = liveScreen.find('.ft-playback-error');
    
          expect(message).to.have.length(1);
        });
    

    message.nodes ends up being 0 (or aka not found). Why? screen shot 2017-10-05 at 10 54 05 am

    I assumed when you mounted, it runs every child's render() (every child that's being hit down the codepath of container..obviously depending on whatever logic is in its render will determine which children are being rendered) method of this container.

    Reviewed by dschinkel at 2017-10-05 15:58
  • 11. Support React 16

    React is currently in v16.0.0-alpha.12, but is it already planned to support it by enzyme? My specific issue currently is #875.

    Is it too early to implement it, as it is in alpha?

    Reviewed by JPeer264 at 2017-05-05 12:36
  • 12. Add contextType support

    @ljharb I've rebased #2507 , applied your suggestions and added test cases for dynamic context values. Unfortunately, the test which uses wrappingComponent does not pass, it keeps rendering the initial context value. The context is correctly updated in the RootFinder though, but it's not propagated down the tree.

    I tried my best to understand what is happening but I don't understand yet how things work internally yet. If you have any hint to point me in the right direction, I'll gladly move this PR forward.

    Thank you for all the great work :)

    Reviewed by pablopalacios at 2022-03-20 09:49
  • 13. Setting state on unmounted functional components should issue a warning and fail the test

    Consider this simple component, which sends an API request on mount and sets component's state to the response:

    import React, { useState, useEffect } from 'react';
    
    export const TestComponent = ({
      fetchSomethingFromAPI,
    }) => {
      const [state, setState] = useState('');
    
      useEffect(() => {
        fetchSomethingFromAPI().then((result) => setState(result));
      }, []);
    
      return <div>{state}</div>;
    };
    

    If the component had unmounted by the time the request completed, the 'infamous' "Can't perform a React state update on an unmounted component" warning would have been printed to console. However, when I try to write a failing test for this case, enzyme doesn't issue a warning and considers the test to have passed. This is my test's code:

    import React from 'react';
    import { mount } from 'enzyme';
    import { act } from 'react-dom/test-utils';
    
    // auxiliary class
    class MockPromise {
      const thenCallbacks = [];
    
      then(callback) {
        this.thenCallbacks.push(callback);
        return this;
      }
    
      resolve(val) {
        this.thenCallbacks.forEach((callback) => callback(val));
      }
    }
    
    describe('TestComponent', () => {
      test('should not set state on unmounted component', () => {
        const promise = new MockPromise();
        const fetchSomethingFromAPI = () => promise;
        const wrapper = mount(<TestComponent fetchSomethingFromAPI={fetchSomethingFromAPI} />);
        wrapper.unmount();
        act(() => {
          promise.resolve(null);
        });
        wrapper.update();
      });
    });
    

    This problem seems to only be affecting functional components, for class components the test would fail with the "setState() can only be called on class components" error message; while the message is not the same as it would be in dev environment, at least it allows me to test my class components for this particular case.

    Current behavior

    Setting state on an unmounted functional component doesn't issue a warning and allows the test to pass

    Expected behavior

    Setting state on an unmounted functional component should issue a warning and fail the test

    Your environment

    API

    • [ ] shallow
    • [x] mount
    • [ ] render

    Version

    | library | version | ------------------- | ------- | enzyme | 3.11.0 | react | 16.8.3 | react-dom | 16.8.3 | react-test-renderer | | adapter (below) | 1.15.5

    Adapter

    • [x] enzyme-adapter-react-16
    • [ ] enzyme-adapter-react-16.3
    • [ ] enzyme-adapter-react-16.2
    • [ ] enzyme-adapter-react-16.1
    • [ ] enzyme-adapter-react-15
    • [ ] enzyme-adapter-react-15.4
    • [ ] enzyme-adapter-react-14
    • [ ] enzyme-adapter-react-13
    • [ ] enzyme-adapter-react-helper
    • [ ] others ( )
    Reviewed by fruttut at 2021-12-07 21:20
  • 14. Method “type” is meant to be run on 1 node. n found instead

    Update

    React 16 + enzyme-adapter-react-16 reduced use case sandbox here: https://github.com/enzymejs/enzyme/issues/2549#issuecomment-982954339

    Current behavior

    React 17, using all the latest packages.

    I follow one of the enzyme unit test workaround to include Mui's ThemeProvider + styled-components's ThemeProvider

    function UnitTestThemeWrapper (props: any) {
      // console.log(props.theme);
      return (
        <StyledEngineProvider injectFirst>
          <MuiThemeProvider theme={props.theme || LightTheme}>
            <ThemeProvider theme={props.theme || LightTheme}>
              <GlobalStyle />
              <CssBaseline />
              {props.children}
            </ThemeProvider>
          </MuiThemeProvider>
        </StyledEngineProvider>
      );
    }
    
    const shallowWithTheme = (node: ReactElement, options?: ShallowRendererProps): ShallowWrapper => {
      // The only way to get it to work, is to manually wraps the node ourselves.
      // return shallow(UnitTestThemeWrapper(node), options);
    
      // Note: For some reason the wrappingComponent from Enzyme is broken.
      // It would not properly calls the wrappingComponent when using shallow.
      // It throws a cryptic error message which has nothing to do with the issues:
      //    "Method “type” is meant to be run on 1 node. 3 found instead."
     
      options = options || {
        wrappingComponent: UnitTestThemeWrapper
      };
      return shallow(node, options); // <= this throw "Method type is meant to be run on 1 node. 3 found instead.
      // */
    };
    

    My UT only has the following:

    describe('Blah', () => {
      let wrapper: ShallowWrapper | ReactWrapper;
      it('should render', () => {
        wrapper = shallow(<Menu open={false} anchorEl={dummy} />);
      });
    });
    

    How can I get it to work? When I try to dump the node, this is what it prints out:

      console.log
        { '$$typeof': Symbol(react.element),
          type: [Function: Menu],
          key: null,
          ref: null,
          props: { open: false, anchorEl: HTMLDivElement {} },
          _owner: null,
          _store: {} }
    
          at shallowWithTheme (src/themes/testUtils.tsx:30:11)
    

    Expected behavior

    Your environment

    API

    • [x] shallow

    Version

        "@emotion/css": "^11.5.0",
        "@emotion/jest": "^11.6.0",
        "@emotion/react": "^11.6.0",
        "@emotion/styled": "^11.6.0",
        "@types/enzyme": "^3.10.10",
        "@types/enzyme-adapter-react-16": "^1.0.6",
        "@wojtekmaj/enzyme-adapter-react-17": "^0.6.5",
        "@mui/material": "^5.2.2",
        "@mui/styles": "^5.2.2",
        "enzyme": "^3.11.0",
        "enzyme-adapter-react-16": "^1.15.6",
        "enzyme-to-json": "^3.6.2",
        "identity-obj-proxy": "^3.0.0",
        "jest": "^26.6.0",
        "jest-emotion": "^11.0.0",
        "jest-enzyme": "^7.1.2",
        "jest-junit": "^12.2.0",
        "jest-styled-components": "^7.0.8",
    

    Adapter

    • [x] enzyme-adapter-react-16
    • [x] others ("@wojtekmaj/enzyme-adapter-react-17": "^0.6.5",)
    Reviewed by totszwai at 2021-11-30 04:16
  • 15. Cannot invoke an object which is possibly 'undefined'

    Thanks for reporting an issue to us! We're glad you are using and invested in Enzyme. Before submitting, please read over our commonly reported issues to prevent duplicates!

    All common issues

    Notoriously common issues

    If you haven't found any duplicated issues, please report it with your environment!

    Current behavior

    I'm getting the error in the title. Maybe i'm not setting it up correctly. I'm looking to update onGetErrorMessage which then checks it what I pass in is valid. IF it is not valid it updates the ariaLabel which is what i'm expected to equal test error.

     test('should set error when page number not valid and update aria-label', () => {
                const pageChangeCallback = jest.fn().mockName('pageChange callback');
    
                const tree = mount(
                    <DemoPagination
                        pageCount={10}
                        selectedPage={1}
                        onPageChange={pageChangeCallback}
                        validationErrorMessageText="test error"
                    />
                )
    
                const selectedPage = tree.find(TextField);
                console.log('PEPE:', tree.props())
                console.log('SSSS:', selectedPage.props())
                // tree.prop('onGetErrorMessage')('a');
                // console.log('III:', selectedPage.setProps({ onGetErrorMessage: onGetErrorMessage('a') }))
                // selectedPage.instance()
                selectedPage.invoke('onGetErrorMessage')('a');
                // selectedPage.props().onGetErrorMessage('a');
                console.log('AFFFT:', selectedPage.props())
                // selectedPage.props().onGetErrorMessage('a') as any;
                const errorMessage = tree.find(Text).at(2);
                // console.log('EERR:', errorMessage.props())
                expect(errorMessage).toBeDefined();
                // expect(selectedPage.prop('ariaLabel')).toContain('test error');
      });
    
    
      <>
          <Text>{initialPagingText}</Text>
          <TextField
              theme={theme}
              styles={classNames.textFieldStyles}
              value={selectedPageString}
              onKeyPress={onKeyPress}
              onChange={onChange}
              onBlur={onBlur}
              onGetErrorMessage={onGetErrorMessage}
              ariaLabel={errorMessage ? `alert error ${errorMessage}` : pagingText}
          />
          <Text>{endingPagingLabelText ?? getEndingPagingText(rangeEndIndex, pageCount)}</Text>
      </>
    

    Expected behavior

    For the property function to be called without getting the object which is possibly 'undefined'.

    Your environment

    API

    • [ ] shallow
    • [x] mount
    • [ ] render

    Version

    | library | version | ------------------- | ------- | enzyme | 3.11 | react | 16.8.5 | react-dom | 16.8.5 | react-test-renderer | n/a | adapter (below) | 16

    Adapter

    • [x] enzyme-adapter-react-16
    • [ ] enzyme-adapter-react-16.3
    • [ ] enzyme-adapter-react-16.2
    • [ ] enzyme-adapter-react-16.1
    • [ ] enzyme-adapter-react-15
    • [ ] enzyme-adapter-react-15.4
    • [ ] enzyme-adapter-react-14
    • [ ] enzyme-adapter-react-13
    • [ ] enzyme-adapter-react-helper
    • [ ] others ( )
    Reviewed by rogerprz at 2021-11-22 18:30
  • 16. No explanation what to do with configuration file

    It is not a big issue, however, it is a bit frustrating that I can not find in the "Installation" section what is the best way and how to implement configured enzyme instance in my project:

    import Enzyme from 'enzyme';
    import Adapter from 'enzyme-adapter-react-16';
    
    Enzyme.configure({ adapter: new Adapter() });
    

    If you can give an idea how to handle it it would be nice 😃

    Reviewed by konrazem at 2021-11-17 16:12
  • 17. Error: Method “text” is meant to be run on 1 node. 0 found instead

    Your environment

    Test

    API

    • [x] mount
    • [x] render

    Version

    | library | version | ------------------- | ------- | enzyme | 3.11.0 | react | 16.13.1 | react-dom | 16.13.1 | react-test-renderer | ^10.0.4

    Adapter

    • [x] enzyme-adapter-react-16

    I am getting this type of error while executing enzyme test case in React. Below is my test case. Can anyone please help.

    context("testing case1", () => {
    
    it("contains correct context notification text", () => {
    const date = "2019-05-05"
    const testOrder = Object.assign({}, XYZ, { type: ABC, status: A })
    const textExpected = abc ${moment(date).format("DD.MM.YYYY")}
    expect(renderCtxNotification(testOrder).find("section").text()).to.equal(textExpected)
    })
    })
    const renderCtxNotification = (orderData) => mount(resolveOrderStatusContents(orderData).ctxNotification.renderContents(orderData)
    

    **Below is the error:

    Error: Method “text” is meant to be run on 1 node. 0 found instead. at ReactWrapper.single (node_modules/enzyme/src/ReactWrapper.js:1168:13) at ReactWrapper.text (node_modules/enzyme/src/ReactWrapper.js:629:17)**

    section is present in .jsx file:

    <section>
                <H4><LocalizedText locKey="text1" /></H4>
                <BodyText>
                  <LocalizedTextWithPlaceholders locKey="text2" placeholders={[formatDate(date)]} />
                </BodyText>
              </section>
    
    Reviewed by smrititaneja18 at 2021-11-16 10:08
Delightful JavaScript Testing.
Delightful JavaScript Testing.

?? Delightful JavaScript Testing ????‍?? Developer Ready: A comprehensive JavaScript testing solution. Works out of the box for most JavaScript projec

May 18, 2022
Chai.js assertions and convenience functions for testing React Components with enzyme
Chai.js assertions and convenience functions for testing React Components with enzyme

chai-enzyme Chai.js assertions for enzyme. Table of Contents Installation Setup Debug output in assertion exceptions Assertions 1. checked() 1. classN

Apr 24, 2022
Chainable, easy to read, React testing library

##Legit Tests This is a super friendly testing library for React, inspired by express middleware, it's easily extendable. Why did I make this when you

Dec 24, 2021
Plugin for http://unexpected.js.org to enable testing the full React virtual DOM, and also the shallow renderer
Plugin for http://unexpected.js.org to enable testing the full React virtual DOM, and also the shallow renderer

unexpected-react Plugin for unexpected to allow for testing the full virtual DOM, and against the shallow renderer (replaces unexpected-react-shallow)

Apr 1, 2022
⚛️ React testing made easy. Supports DOM and custom renderers.

Rut Rut is a DOM-less React testing library that aims to be lightweight, encourage great testing practices, and reduce flakiness and code smells. It i

Sep 2, 2021
An isolated development space with integrated fuzz testing for your components. See them individually, explore them in different states and quickly and confidently develop them.
An isolated development space with integrated fuzz testing for your components. See them individually, explore them in different states and quickly and confidently develop them.

Carte Blanche IMPORTANT: This project is unfinished and not maintained. Do not try to use it, it likely does not work anymore. Carte Blanche is an iso

Mar 6, 2022
Testing hooks with Jest

Jooks (Jest ❤ + Hooks ????) If you're going through hell testing React Hooks, keep going. (Churchill) What are Custom React Hooks React Hooks are a ne

Apr 20, 2022
Human resource management system with react javascript
Human resource management system with react javascript

HRMS (Human Resource Management System) UML Component Diagram Getting Started with Create React App This project was bootstrapped with Create React Ap

Oct 26, 2021
A comprehensive Eslint configuation package for JavaScript & TypeScript projects, with support for React.

AngaBlue Eslint Config ????‍?? A comprehensive Eslint configuation package for JavaScript & TypeScript projects, with support for React. ?? Homepage I

May 5, 2022
An implementation of Minesweeper game using Javascript and React.js

Minesweeper About An implementation of a Minesweeper game. Built with Typescript and React. Getting started git clone https://github.com/FakeMetalFan/

Jan 10, 2022
🌟 JavaScript Style Guide, with linter & automatic code fixer
🌟 JavaScript Style Guide, with linter & automatic code fixer

JavaScript Standard Style Sponsored by English • Español (Latinoamérica) • Français • Bahasa Indonesia • Italiano (Italian) • 日本語 (Japanese) • 한국어 (Ko

May 9, 2022
Foxpage SDK for JavaScript in the browser and Node.js.

Foxpage SDK JS Foxpage SDK for JavaScript in the browser and Node.js. ✨ Project <Project Root> ├── .storybook // storybook config

Dec 16, 2021
A rollup plugin to generate javascript files that export the text of the css files

rollup-plugin-css-text A rollup plugin to generate javascript files that export the text of the css files. The plugin functionality This plugin will s

Dec 16, 2021
A desktop app for inspecting your React JS and React Native projects. macOS, Linux, and Windows.
A desktop app for inspecting your React JS and React Native projects. macOS, Linux, and Windows.

Join our Community Slack Quick Installation Guide What is Reactotron? Reactotron is a macOS, Windows, and Linux app for inspecting your React JS and R

May 18, 2022
A desktop app for inspecting your React JS and React Native projects. macOS, Linux, and Windows.
A desktop app for inspecting your React JS and React Native projects. macOS, Linux, and Windows.

Join our Community Slack Quick Installation Guide What is Reactotron? Reactotron is a macOS, Windows, and Linux app for inspecting your React JS and R

May 16, 2022
A desktop app for inspecting your React JS and React Native projects. macOS, Linux, and Windows.
A desktop app for inspecting your React JS and React Native projects. macOS, Linux, and Windows.

Join our Community Slack Quick Installation Guide What is Reactotron? Reactotron is a macOS, Windows, and Linux app for inspecting your React JS and R

May 14, 2022
A mobile-first React prototyping tool with React-Bootstrap component integration
A mobile-first React prototyping tool with React-Bootstrap component integration

A mobile-first React prototyping tool with React-Bootstrap component integration

Apr 17, 2022
Let's learn React by building react within 100 lines of code
Let's learn React by building react within 100 lines of code

kReact Let's learn React by building react within 100 lines of code ???? Medium article: https://kamesh-dev.medium.com/kreact-building-your-own-react-

Nov 4, 2021
Add Prometheus metrics to your React App. Built on top of promjs and react-performance libraries
  Add Prometheus metrics to your React App. Built on top of promjs and react-performance libraries

prom-react Add Prometheus metrics to your React App. Built on top of promjs and react-performance libraries Scope and purpose The main objective of th

Mar 23, 2022