Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
    />
  );
};
like image 787
Sam Avatar asked Dec 11 '25 04:12

Sam


1 Answers

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

like image 117
Sam Avatar answered Dec 13 '25 23:12

Sam