![](/img/trans.png)
[英]Zend framework You don't have permission to access js/ckeditor/ **
[英]How to test a function that you don't have direct access to
我正在嘗試測試從 useReducer 解構的dispatch
useReducer
。
我的 dispatch function 是在我的組件中創建的,因此,據我所知,我無法像往常一樣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 解構的調度useReducer
,但我無法訪問它(據我所知)。
理想情況下,我的初始 state 和 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.',
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.