Using the .mount () enzyme. setProps with a fallback provider

I have a test that sets props to observe some changes in a component. The only complication is that I wrap the rendered element in <Provider> because there are some related components next to it.

I pass through

 const el = () => <MyComponent prop1={ prop1 } />; const wrapper = mount(<Provider store={store}>{ el() }</Provider>); 

Then I try to notice some changes using the following:

 wrapper.setProps({ /* new props */ }); // expect()s etc. 

The problem is that setProps() does not set the details on the wrapped component. I assume this is because <Provider> does not actually pass props, since it is not HoC. Is there a better way to test this than simply changing the local prop variables and re-rendering?

+5
source share
1 answer

You should only call setProps for the wrapped component or parent.

A good rule of thumb is that your test should only test one component (the parent), so setting the props for children is not allowed by the enzyme.

https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/setProps.md#setpropsnextprops--self

If you have child components that we need to satisfy dependencies between stores (through the Provider and the context), then this is normal, but these child components should really have their own isolated tests.

Here you will be asked to write a test to change to setProps .

If you find that you are writing tests for a container or connector, you really only need to verify that the child component is receiving the correct details and / or state. For instance:

 import { createMockStore } from 'mocks' import { shallwo } from 'enzyme' // this component exports the redux connection import Container from '../container' const state = { foo: 'bar' } let wrapper let wrapped let store beforeEach(() => { store = createMockStore(state) wrapper = shallow(<Container store={store} />) wrapped = wrapper.find('MyChildComponent') }) it('props.foo', () => { const expected = 'bar' const actual = wrapped.prop('foo') expect(expected).toEqual(actual) }) 

Another tip is that it helps to understand the difference between shallow and mounted, so you do not need mocking dependencies for children in the test, the top answer is well read here:

When should you use rendering and shallow in Enzyme / React tests?

0
source

Source: https://habr.com/ru/post/1264833/


All Articles