尝试测试功能组件时重置钩子中的全局状态对象

时间:2020-08-04 06:09:10

标签: reactjs jestjs react-hooks

我有一个react自定义钩子,如下所示:


let listeners = [];
let state = { settingsStatus: statusEnum.DEFAULT };

const setState = (newState) => {
    state = { ...state, ...newState };
    listeners.forEach((listener) => {
        listener(state);
    });
};

const useSettings = (graphQLClient) => {
    const newListener = useState()[1];

    useEffect(() => {
        listeners.push(newListener);
        if (state.settingsStatus === statusEnum.DEFAULT) {
            setState({ settingsStatus: statusEnum.LOADING });
            getSettingsData(graphQLClient).then((response) => {
                setState({
                    settingsStatus: statusEnum.LOADED,
                    isCashBasis: response.cashBasis
                });
            });
        }
        return () => {
            // Called just before the component unmount
            listeners = listeners.filter((listener) => listener !== newListener);
        };
    }, [graphQLClient, newListener]);

    return [state];
};

export default useSettings;

当我在一次开玩笑的测试中尝试模拟上述钩子的返回值时,

const settingsPromiseMock = new Promise((resolve) => {
     resolve({ ok: true, json: () => settingsResponse });
});
props.graphQLClient.query.mockReturnValue(settingsPromiseMock);

然后将settingsStatus首次设置为LOADED。之后,在下一组测试中,模拟响应保持不变。完成第一次测试后,如何重设状态对象?

0 个答案:

没有答案