Enzyme: ReactWrapper::state() can only be called on class components

Created on 17 Oct 2019  路  4Comments  路  Source: enzymejs/enzyme

Writing unit testing in react using jest and enzyme. While checking with a component state , it throws an error "ReactWrapper::state() can only be called on class components ".

import React from 'react';
import { mount } from 'enzyme';
import expect from 'expect';
import CustomerAdd from '../CustomerAdd'
import MUITheme from '../../../../Utilities/MUITheme';
import { ThemeProvider } from '@material-ui/styles';

describe('<CustomerAdd />', () => {
    const wrapper = mount(
        <ThemeProvider theme={MUITheme}>
          <CustomerAdd {...mockProps}></CustomerAdd>
        </ThemeProvider>
        );
        test('something', () => {
            expect(wrapper.find(CustomerAdd).state('addNewOnSubmit')).toEqual(true);
        });
});

In the above code CustomerAdd Component is class component.I don't what wrong with my code. Can any one help me out of this problem. Thanks in advance.

Need More Information Need To Reproduce

Most helpful comment

@exapsy function components have no state; the useState hook is a misleading name as it does not, in fact, make the function stateful - all it does is notify React to store information in a side channel, which is state react holds, not your component.

As such, unless React itself provides a way for testing tools to directly interact with hook state, it remains impossible/impractical for testing tools to have any direct interaction with it.

All 4 comments

Are you sure CustomerAdd is a class component, and not an SFC, or wrapped in an HOC that's one? What's the source of CustomerAdd?

@ajeesh-s I have the problem same you. You can check where it is used and expect to it
ex:

<Foo>
  <Bar open={isOpen}/>
</Foo>

instead of check state isOpen of Foo component, i check wrap.find(Bar).prop('open')

Same issue, to be more specific though:
My component uses React hooks. Which might be the case after all. If that's the case, is there any other counter solution to this issue?

@exapsy function components have no state; the useState hook is a misleading name as it does not, in fact, make the function stateful - all it does is notify React to store information in a side channel, which is state react holds, not your component.

As such, unless React itself provides a way for testing tools to directly interact with hook state, it remains impossible/impractical for testing tools to have any direct interaction with it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

amcmillan01 picture amcmillan01  路  3Comments

rexonms picture rexonms  路  3Comments

potapovDim picture potapovDim  路  3Comments

ivanbtrujillo picture ivanbtrujillo  路  3Comments

thurt picture thurt  路  3Comments