【问题标题】:Jest test case for UseEffect hooksUseEffect hooks 的 Jest 测试用例
【发布时间】:2020-03-20 12:19:55
【问题描述】:

我正在尝试为 useEffect 反应钩子编写 Jest-enzyme 测试用例,我真的迷路了,我想为 2 个反应钩子编写测试用例,一个进行异步调用,另一个对数据进行排序并设置数据使用 usestate 钩子,我的文件就在这里。

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>
);

}

当我编写如下测试用例时,

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);
})

});

我收到这个错误,即 api.fetchRegistryFunction 不是函数

【问题讨论】:

    标签: reactjs testing jestjs react-hooks enzyme


    【解决方案1】:

    这是我用来测试钩子的钩子包装器。

    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;
    }
    

    那么你可以这样使用它:

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

    然后照常测试结果:

     expect(availableVariants).toEqual(expected);
    

    【讨论】:

    • 感谢您的回答,但我并没有真正理解解决方案。
    • 好的,我会尝试修改我的答案,我看不到您上传的文件,所以我只是使用示例代码,您必须根据自己的需要进行调整。跨度>
    猜你喜欢
    • 2021-01-14
    • 1970-01-01
    • 2020-03-20
    • 2020-11-01
    • 2020-03-24
    • 1970-01-01
    • 2020-03-27
    • 2020-05-07
    • 1970-01-01
    相关资源
    最近更新 更多