我有一个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。之后,在下一组测试中,模拟响应保持不变。完成第一次测试后,如何重设状态对象?