Mocked redux store value returning empty string when it should have a value

38 views Asked by At

The following test should should return "Test Project" for

const projectName = container.querySelector('.Checklists-ProjectName');

but is returning an empty string. How can I confirm that the store is actually holding this value?

import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { act } from 'react-dom/test-utils';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';

import Checklists from '../Checklists';

const mockStore = configureStore([]);

let container = null;
beforeEach(() => {
  // setup a DOM element as a render target
  container = document.createElement('div');
  document.body.appendChild(container);
});

afterEach(() => {
  // cleanup on exiting
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});    

describe('Checklists', () => {
  test('renders checklists from state and displays the project name', async () => {
    const project = { name: 'Test Project' };
    const store = mockStore({ project });

    await act(async () => {
      render(
        <Provider store={store}>
          <Checklists />
        </Provider>,
        container
      );
    });

    const projectName = container.querySelector('.Checklists-ProjectName');
    expect(projectName.textContent).toBe(project.name);
  });
});

In the Checklists component useSelector returns an empty string:

const { project } = useSelector((state) => state.project);
console.log('Checklists project :', project); 
1

There are 1 answers

0
Lin Du On

The entire state tree is { project: { name: 'Test Project' } }, the selector function passed in useSelector hook selects the project state slice, you don't need to do destructuring assignment.

Change:

const { project } = useSelector((state) => state.project);

To:

const project = useSelector((state) => state.project);