mardi 23 février 2021

Testing a react component using useSelector hook

I am having a lot of trouble trying to implement tests for a component using the useSelector hook from react redux. I've seen some questions already about this subject but I didn't manage to fix my problem using the suggested solutions to those questions.

My component is pretty big so I won't post it all but the part giving me trouble looks like this :

Total.tsx

import React from 'react';

import clsx from 'clsx';
import i18next from 'i18next';
import { useSelector } from 'react-redux';
import { Trans } from 'react-i18next';

import Box from '@material-ui/core/Box';
import CustomTooltip from '../CustomTooltip/CustomTooltip';
import SkeletonTotal from 'components/Skeletons/Total';

import { ApplicationHelper } from 'helpers';

import './Total.scss';

//Some interfaces here for types since this is in TypeScript

function Total(props: TotalProps) {
  const { currency } = useSelector(
    (state: { currencyReducer: any }) => state.currencyReducer
  );
...
}

I first tried to test it like another component that doesn't use redux like so :

Total.test.js (first attempt)

import React from 'react';
import Total from './Total';
import { render } from '@testing-library/react';

test('test', () => {
  const { container } = render(
    <Total priceLoading={false} bookingPrice={bookingPrice} values={myFormValues} />
  );
});

But I was getting an error saying I need a react-redux context value and to wrap my component in a Provider which led me to try this :

Total.test.js (attempt 2)

import React from 'react';
import { Provider } from 'react-redux'
import Total from './Total';
import { render } from '@testing-library/react';

test('test', () => {
  const { container } = render(
    <Provider>
      <Total priceLoading={false} bookingPrice={bookingPrice} values={myFormValues} />
    </Provider>
  );
});

I am now getting a "Cannot read property 'getState' of undefined" error for the Provider component. I did try to mock a store to pass to my Provider as well as using jest to mock a return value like so

const spy = jest.spyOn(redux, 'useSelector')
spy.mockReturnValue({currency: 'cad'})

Unfortunately I was unsuccessful to make this work and could not find a working solution in the other questions that might relate to this. Any ideas how I could make this work? Thanks

Aucun commentaire:

Enregistrer un commentaire