question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Initializing Recoil Root for Jest/React-testing-library unit testing

See original GitHub issue

Hi! I’m having a hard time setting up a testing environment to mock my recoil state to test my component.

Getting error: Uncaught [Error: Missing definition for RecoilValue: “undefined”"]

I’m using atomFamily for my selectedRateState so that I can use a selector as default value but replicating this to test is proving quite difficult. If I switch selectedRateState to just atom like for currentRateInformation then I think it works. but I will need access to my selectors in default value which I can’t if I use atom. Any help would be appreciated.

/store/atom

export const currentRateInformation = atom({
    key: 'currentRateInformation',
    default: undefined,
});

export const selectedRateState = atomFamily({
    key: 'selectedRateState',
    default: getSelectedRate,
});

/selectors

export const getSelectedRate = selectorFamily({
    key: 'getSelectedRate',
    get: (id) => async () => {
        try {
            const { data } = await apiClient.getSelectedRate(id);
            const rateInfo = extractRelevantRateInfo(data);
            return rateInfo;
        } catch (error) {
            console.error('getSelectedRate error', error);
            throw error;
        }
    },
});

RateDetails.tsx

export const RateDetails = withI18n()(({ rateId, i18n, onBackClick }: any) => {
    const rate = useRecoilValue(selectedRateState(rateId));

    return (
        <>
            <StyledButtonContainer>
                <Button
                    data-testid="expanded-page-back-button"
                    secondary
                    icon={<ChevronIcon />}
                    label={i18n._('back')}
                    onClick={onBackClick}
                    size="medium"
                />
            </StyledButtonContainer>
         ...
        </>
    );
});

RateDetails-test.tsx

import React from 'react';
import { fireEvent, waitFor, render } from '@testing-library/react';
import { RecoilRoot } from 'recoil';

import { currentApplicationIdState, selectedRateState } from 'store/atom';
import { product } from 'components/rates/rate-page-subsection.test';

import { RateDetails } from '../[rateId]';

describe('Expanded Page', () => {
    const initializeState = ({ set }: any) => {
        set(currentApplicationIdState, 123);  <--- this works
        set(selectedRateState, () => product); <--- fails here
    };
    it('RateDetails: back button should go back', async () => {
        const backMock = jest.fn();

        const { findByTestId } = render(
            <RecoilRoot initializeState={initializeState}>
                <RateDetails rateId="16996" onBackClick={backMock} />
            </RecoilRoot>
        );

        const backButton = await findByTestId('expanded-page-back-button');

        fireEvent.click(backButton);
        expect(backMock).toHaveBeenCalled();
    });
});

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
drarmstrcommented, Jan 21, 2021

What is the issue you are trying to report? I see this comment in your source:

   set(selectedRateState, () => product); <--- fails here

This shouldn’t work because selectedRateState is an atom family, not an atom, so it is a function you need to call to get the actual atom.

   set(selectedRateState(id), () => product);
0reactions
itsankitvermacommented, Jun 2, 2022

This thread helped me a lot. Thanks for sharing.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Testing - Recoil
It can be helpful to test Recoil state when testing a component. You can compare the new state against expected values using this...
Read more >
Is there a way to initialize multiple atom states before testing a ...
I offer this edit: <RecoilRoot initializeState={(snap: any): any => {snap.set( oneTimeData, onetimeParameter); snap.set(errors, ...
Read more >
Jest, React Testing Library, eslint, GitHub Actions ... - YouTube
We will setup jest, react testing library, eslint plugi... ... 17K views 1 year ago React.js Unit Testing and Integration Testing Tutorial.
Read more >
An Easier Way to Generate Recoil Tests ft. Chromogen
Chromogen is a Jest unit-test generation tool for Recoil selectors. ... component within a RecoilRoot and update your Recoil imports.
Read more >
React testing library test modal open
JavaScript testing #1. Initialize React Project. In React Bootstrap, there is documentation for using the unit test cases but still writing unit test...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found