Search code examples
reactjsreact-testing-libraryredux-toolkit

testing-library/react rendering empty <div /> for a redux toolkit component


The issue it produces is it won't successfully render the MyComponent to the Mock DOM. console.log store displays the correct state in the store as well. But it's just rendering the empty in the body tag.

import React from 'react';
import configureMockStore from 'redux-mock-store';
import * as actions from 'store/reducer/reducer';
import { fireEvent, render, screen } from 'testUtils';
import MyComponent from 'components/MyComponent';
import { initialState } from 'store/reducer/reducer';

const mockStore = configureMockStore();
describe('my component', () => {
  let message;
  beforeAll(() => {
    message = 'testing';
  });
  it('test 1', () => {
    const store = mockStore({
      myState: {
        ...initialState,
        message,
      },
    });
    render(<MyComponent />, {
      store: store,
    });
    screen.debug();
    expect(screen.queryAllByText(message).length).toBe(1);
  });
});

// in testUtils

    function render(ui, { store = configureStore(), ...renderOptions } = {}) {
      function Wrapper({ children }) {
        return (
          // ..some other Providers
          <Provider store={store}>
            {children}
          </Provider>
        );
      }
export {render};

now the screen.debug() only shows

<body>
    <div />
</body>

// in MyComponent

const MyComponent = (): JSX.Element => {
  const dispatch = useDispatch();
  const myState = useSelector(myReducer);

  return (
    <AnotherComponent
      isOpen={myState?.isOpen}
      message={myState?.message}
    />
  );
};

Solution

  • I found the reason why it's not working. It's because, in myComponent, I had a typo in the conditional statement. Thanks, everyone.