[英]Testing a custom context hook that uses a useEffect hook and apollo
我創建了一個上下文,該上下文公開了一個易於使用的鈎子。 在這個鈎子中,我已經確保在呈現頁面之前預加載了一些數據,如下所示:
export const MyContext = React.createContext({} as any);
function useMyContext() {
const context = React.useContext(MyContext);
if (context === undefined) {
throw new Error('useMyContext must be used within a MyContext');
}
return context;
}
function MyContextProvider(props: any) {
const client = useApolloClient();
const { user } = React.useContext(UserContext);
const [data, setData ] = React.useState({});
const findSomethingFromUser = () => {
return client.query({
query: FIND_SOMETHING_FROM_USER,
variables: { userId: user.id },
});
};
const load = () => {
findSomethingFromUser()
.then(({ data, errors }) => {
setData(data);
});
};
// Load user test
React.useEffect(load, []);
return (
<MyContext.Provider value={{ data }}>
{children}
</MyContext.Provider>
);
}
export { MyContextProvider, useMyContext };
我想使用測試庫對此進行測試,在閱讀了一些文章和 github 問題后,我得出以下結論:
const wrapper = ({ children }) => ( {children} );
it('should fetch the special user value', async () => {
const { result, waitForNextUpdate } = renderHook(useMyContext, { wrapper });
await waitForNextUpdate();
// await act(async () => {
// await waitForNextUpdate();
// });
expect(result.current.mySpecialUserValue).toEqual("something");
});
可悲的是,電流是 null。 我預計這是因為useEffect
導致 state 更新,因此首先返回 null (默認值)。 更新前。 這就是我介紹waitForNextUpdate
的原因。
但是,它給了我以下錯誤:
警告:傳遞給 TestRenderer.act(...) function 的回調不得返回任何內容。
It looks like you wrote TestRenderer.act(async () => ...) or returned a Promise from it's callback. Putting asynchronous logic inside TestRenderer.act(...) is not supported.
console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:102
Warning: Do not await the result of calling TestRenderer.act(...), it is not a Promise.
console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:102
Warning: An update to MyContextProvider inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
關於如何解決這個問題的任何想法?
在閱讀https://dev.to/theactualgivens/testing-react-hook-state-changes-2oga之后,我決定模擬useReducer
,因為調度導致 state 在useEffect
掛鈎中更新。 之后它起作用了。 我現在模擬減速器的初始 state。
const dispatch = jest.fn();
const useReducerSpy = jest.spyOn(React, 'useReducer');
useReducerSpy.mockImplementation((init: any) => [MY_CONTEXT_MOCK, dispatch]);
我的測試看起來像
it('should render', async () => {
const { result } = renderHook(useMyContext, { wrapper: bySlugWrapper });
expect(result.current.somevar).toEqual(MY_CONTEXT.somevar);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.