Suman
Suman

Reputation: 33

Jest test case for UseEffect hooks

I am trying to write the Jest-enzyme test case for useEffect react hooks, and I am really lost, I want to write test case for 2 react hooks, one making the async call and another sorting the data and setting the data using usestate hooks, my file is here.

export const DatasetTable: React.FC = ({id, dataset, setDataset, datasetError, setDataSetError}) => { const [sortedDataset, setSortedDataset] = useState();

useEffect(() => {
    fetchRegistryFunction({
        route:`/dataset/report?${constructQueryParams({id})}`,
        setData: setDataset,
        setError: setDataSetError
    })();
}, [id, setDataset, setDataSetError]});

useEffect(() => {
    if(dataset) {
        const sortedDatasetVal = [...dataset];
        sortedDatasetVal.sort(a, b) => {
            const dateA: any = new Date(a.date);
            const dateA: any = new Date(a.date);
            return dataA - dateB;
        }
        setSortedDataset(sortedDatasetVal);
    }
}, [dataset])

return (
    <div>
        <DatasetTable
            origin="Datasets"
            tableData={sortedDataset}
            displayColumns={datasetColumns}
            errorMessage={datasetError}
        />

    </div>
);

}

When I am writing test case like below,

describe('<DatasetTable />', () => {
let wrapper: shallowWrapper;
const DatasetVar = reportMock[0] // its imported
const props: DatasetTableProps = {
    id: 23,
    dataset: DatasetVar,  //defined above
    setDataset: jest.fn(),
    datasetError: undefined,
    setDatasetError: jest.fn()
};
jest.mock('./index.tsx', (props: any) => (
    <span id='faked-dataset-table'>{JSON.stringify(props.dataset)}</span>
));
jest.mock('./api.ts', () => {
    fetchRegistryFUnction: jest.fn(() => promise.resolve({data: {}}))
});
const expectedSortedData = [
    {
        "id": 23,
        "datasetId": 7086,
        "snapshotCOntext": "sksfhasj"
        "datasetCount": 2198,
        "completion": 0.0
    },
    {
        "id": 24,
        "datasetId": 76,
        "snapshotCOntext": "23-04-2019"
        "datasetCount": 2198,
        "completion": 0.0
    }
];
it('passes sorted data to datasetTable', () => {
    const wrapper =  mount(<DatasetTable {...props}/>);
    expect(fetchRegistryFunction).tohavebeencalledwith({
        route: 'dataset/report/datasetVersionId=23',
        setData: jest.fn(),
        setError: jest.fn()
    });
    expect(JSON.parse(wrapper.find("faked-dataset-table").text())).toEqual(expectedSortedData);
})

});

I am getting this error that api.fetchRegistryFunction is not a function

Upvotes: 1

Views: 1005

Answers (1)

Josh Dando
Josh Dando

Reputation: 2153

Heres a hook wrapper I use for testing hooks.

import { mount, shallow } from 'enzyme';
import React from 'react';

interface ResultProps<T> {
    result: T;
}
function Result<T>({ result }: ResultProps<T>) {
    return <span data-output={result} />;
}

export function testHook<A, R>(runHook: (...args: A[]) => R, flushEffects = false): R {
    function HookWrapper() {
        const output = runHook();

        return <Result result={output} />;
    }

    const wrapper = flushEffects ? mount(<HookWrapper />) : shallow(<HookWrapper />);

    return wrapper.find(Result).props().result;
}

Then you can use it like so:

const { availableVariants } = testHook(() =>
            useProductVariants({ variantAttributes, variants })
        );

And then test the result as usual:

 expect(availableVariants).toEqual(expected);

Upvotes: 0

Related Questions