mardi 20 octobre 2020

cypress react-unit-test: assertions on a nested component's useState

Just giving a shot to unit testing with Cypress, I wonder how can I inspect the state of React functional component that needs to be mounted wrapped in a bunch of providers (for redux, theme, context etc).

First I created a custom mount:

export function mountWithProviders(
  component,
  { initialState = {}, route = '/', history = createMemoryHistory({ initialEntries: [route] }), ...options } = {}
) {
  const store = createStore(rootReducer, initialState, applyMiddleware(thunk));
  return {
    ...mount(
      <Provider store={store}>
        <MuiThemeProvider theme={theme}>
          <ThemeProvider theme={theme}>
            <TContextProvider>
              <Router history={history}>{component}</Router>
            </TContextProvider>
          </ThemeProvider>
        </MuiThemeProvider>
      </Provider>,
      { ...options }
    )
  };
}

Not sure if I need all of that, didn't figure that out yet, but at least the Redux and Theme providers are needed or the test crashes.

So then, in my unit test, I mount my component this way:

mountWithProviders(<MyComp props={mockProps} />);

So the outermost component that gets mounted is Provider and MyComp is deeply nested.

Is there a way that I could access and inspect the state of a useState hook inside MyComp ?

I have seen examples with: cy.window().should('have.property', 'mycomp').its('state') etc..... but I don't understand it well and couldn't reproduce.

Aucun commentaire:

Enregistrer un commentaire