应测试以下钩子。
export function useSomethingSaver() {
let somethingMutation = useMutation(async (newSomething) => {
return await saveSomething(newSomething)
})
return {
saveSomething: somethingMutation.mutate,
saveSomethingAsync: somethingMutation.mutateAsync,
isLoading: somethingMutation.isLoading,
isError: somethingMutation.isError,
}
}
现在我想测试在调用
saveSomething
时是否使用正确的参数调用 saveSomethingAsync
方法。
import { act, renderHook, waitFor } from '@testing-library/react-native'
...
it('Something can be saved', async () => {
saveSomething.mockImplementation(() => SOMETHING_DATA)
const wrapper = ({ children }) => (
<BaseContexts queryClient={queryClient}>{children}</BaseContexts>
)
const { result } = renderHook(() => useSomethingSaver(), { wrapper })
await act(async () => {
await result.current.saveSomething(SOMETHING_SAVE_DATA)
})
await waitFor(() => !result.current.isLoading)
expect(saveSomething).toBeCalledWith(SOMETHING_SAVE_DATA)
})
测试是绿色的,但它会输出以下错误消息:
console.error
Warning: You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);
at printWarning (node_modules/react/cjs/react.development.js:209:30)
at error (node_modules/react/cjs/react.development.js:183:7)
at node_modules/react/cjs/react.development.js:2559:15
at tryCallOne (node_modules/promise/lib/core.js:37:12)
at node_modules/promise/lib/core.js:123:15
at flush (node_modules/asap/raw.js:50:29)
问题在于,显然正在等待
act()
的呼叫。有人可以向我解释一下为什么会显示此错误消息吗?
编辑:带分号的行为语句:
const { result } = renderUseSomethingSaver();
await act(async () => {
await result.current.saveSomethingAsync(SOMETHING_SAVE_DATA);
});
await waitFor(() => !result.current.isLoading);
这看起来是 Jest 库的打字稿定义错误。它指出它只是一个同步方法,这就是 lint 抛出错误的原因,但当回调被指定为异步时它可以是异步的。