Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enzyme - how to test initial state of inner component?

I am mounting a component with another component inside it like so:

const wrapper = mount(<IntlProvider><SignUpForm /></IntlProvider>);

The component <SignUpForm /> should have an initial state of {errors: {}}. I am using the following assertion:

expect(wrapper.find(SignUpForm).state('errors')).to.equal({});

but I am receiving the following error when running the test:

Error: ReactWrapper::state() can only be called on the root

So, how do I acces the state of the <SignUpForm /> component?

like image 511
JoeTidee Avatar asked Dec 07 '25 11:12

JoeTidee


1 Answers

Well, you can't do that using enzyme (as far as I know), but there is a really good reason for that - unit tests should test some separated part of the application (never two parts in one test). This Provider is really a component, so you try to test child component mounting parent component...

The same issue is when you have components connected to the redux store, you can wrap them in Provider, but that is not the case. You should separate component from wrapped version, and then test only the component with isolation from third parties/parent/siblings.

I export component and connected component from one file (two exports, one named, one default) and in tests I only import named (NOT connected) component. I don't really wan't to test redux provider ;)

//component.jsx
export function MyComp() {}
export default connect()(MyComp)

//component.test.js
import {MyComp} from "./component"

//another component
import MyComp from "./component"
like image 71
kzg Avatar answered Dec 10 '25 22:12

kzg