3
import configureMockStore from 'redux-mock-store';
import NavBar from '../components/NavBar/NavBar';

const mockStore = configureMockStore(middlewares);
const store = mockStore(initialState);

wrapper = mount(
    <BrowserRouter> 
        <Provider store={store}>
            <NavBar {...props} />
        </Provider>
    </BrowserRouter> 
);

How can I update the state of NavBar component which is present in wrapper?

I tried updating using wrapper.setState({displayMenu:true}) but it was not updated because I think wrapper is wrap of component with Provider, so the state of NavBar is not updated.

M0nst3R
  • 5,186
  • 1
  • 23
  • 36

1 Answers1

1

To solve this problem, you can write like this:

import ConnectedNavBar, { NavBar } from '../components/NavBar/NavBar';

const wrapper = mount(
    <Provider store={store}>
        <ConnectedNavBar/>
    </Provider>
);

const navBarInstance = result.find(NavBar).instance() as NavBar;
navBarInstance.setState({displayMenu:true});

To get information about the redax-component

navBarInstance.props
navBarInstance.state

Notice! Pay attention to how the component is imported

import ConnectedNavBar, { NavBar } from '../components/NavBar/NavBar';

And the redax component is exported as follows:

export class NavBar extends Component<Props, State>{} 
/*...*/
export default connect<StateProps>(mapStateToProps)(NavBar);

I hope this solves your problem

Karina D.
  • 49
  • 1
  • 6
  • It is not a good practice to have two exports from same component just to fix tests. – Pankaj Manali Feb 01 '21 at 06:48
  • That's exactly the way I ended up doing it. Unfortunate that this seems to be the only viable way. As for bad practices, it is a terrible practise to give unconstructive feedback and not even explain why you think something should not be done this way. What is the author of the question supposed to do with such a comment? – jpo Aug 22 '22 at 12:50