gpt4 book ai didi

javascript - 如何测试您无权直接访问的功能

转载 作者:行者123 更新时间:2023-12-05 06:13:39 25 4
gpt4 key购买 nike

我正在尝试测试从 useReducer 中解构的 dispatch 函数。

我的调度函数是在我的组件中创建的,所以据我所知,我无法像往常一样expect(dispatch).toHaveBeenCalledWith({...}) .

我的组件看起来像这样:

const reducer = (state, action) => {
switch (action.type) {
case 'MY_ACTION':
return { ...state, myError: action.payload };
}
};

const Container = ({ someProp, anotherProp, aThirdProp }) => {

// This hook only works at this level of my application

const onlyAvailableInsideContainer = useonlyAvailableInsideContainer();



// Due to the above my initial state needs to be created here

const initialState = {
initialStateArr: [],
someProp,
myError: null,
aThirdProp,
anotherProp,
onlyAvailableInsideContainer,
};



// Which means I need to extract my state and dispatch functions within the Container also

const [state, dispatch] = useReducer(reducer, initialState);

const { fieldProps, formProps, errors } = someHook(
hookConfig(state, dispatch, aThirdProp, onlyAvailableInsideContainer),
);

return (
<div className="dcx-hybrid">
<MyContext.Provider
value={{ state, dispatch, fieldProps, formProps, errors }}
>
<SomeChildComponent />
</MyContext.Provider>
</div>
);
};

我需要测试从 useReducer 解构的调度函数,但我无法访问它(据我所知)。

理想情况下,我的初始状态和 useReducers 将专门从我的组件创建,但我需要只能从内部访问的信息。

像这样的事情是我认为我需要做的,但我不知道如何以一种它知道我想做什么的方式来格式化测试。

function renderContainer(props) {
// eslint-disable-next-line react/jsx-props-no-spreading
const utils = render(<Container {...props} />);

return {
...utils,
};
}

test('an error will be disatched when the endpoint returns a 4xx status', async () => {
fetchMock.post('/api/myendpoint', 400);

const component = renderContainer();

await act(async () => {
fireEvent.click(component.getByText('Continue'));
});

expect(dispatch).toBeCalledWith({
type: 'MY_ACTION',
payload: 'Some error message.',
});
});

最佳答案

尝试像这样监视 useReducer:

const dispatch= jest.fn();
const useReducerMock= (reducer,initialState) => [initialState, dispatch];
jest.spyOn(React, 'useReducer').mockImplementation(useReducerMock);

然后测试它:

   expect(dispatch).toBeCalledWith({
type: 'MY_ACTION',
payload: 'Some error message.',
});

关于javascript - 如何测试您无权直接访问的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63236822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com