我有相当复杂且仍在增长的应用程序。我们使用带有钩子、上下文和其他有用东西的反应。一般来说,测试 react hooks@testing-library/react-hooks很容易。有时我们会遇到测试通过但出现奇怪警告的情况:
Warning: It looks like you're using the wrong act() around your test interactions.
Be sure to use the matching version of act() corresponding to your renderer:
// for react-dom:
import {act} from 'react-dom/test-utils';
// ...
act(() => ...);
// for react-test-renderer:
import TestRenderer from 'react-test-renderer';
const {act} = TestRenderer;
// ...
act(() => ...);
Run Code Online (Sandbox Code Playgroud)
这是带有测试的小型应用程序。不幸的是,它仅适用于 chrome。在 FF 上,测试永远不会结束。测试正在通过,但在控制台中是可见的警告。如果它不适合您,请查看图片:
如果有人能向我解释如何摆脱这个警告,我将不胜感激。我尝试了许多不同的方法,但最终,我们的许多测试都抛出了这个警告。
我在设置单元测试以确定使用正确参数调用函数时遇到问题。useAHook返回foo调用 function 的函数bar。代码看起来像这样
//myModule.js
export const useAHook = (arg1, arg2) => {
const foo = useCallback(() => {
bar(arg1, arg2);
}, [arg1, arg2]);
return foo;
}
export const bar = (a, b) => {
//does some stuff with a and b
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用renderHookand对这段代码进行单元测试jest.spyOn。我想确认调用函数会foo导致bar使用正确的参数调用。我的单元测试看起来像这样
//myModule.spec.js
import * as myModule from './myModule.js'
it('should call foo with correct arguments', () => {
const spy = jest.spyOn(myModule, 'bar');
const { …Run Code Online (Sandbox Code Playgroud) 我有一个自定义钩子,可以将可选的 ref 作为钩子作为参数的对象的属性传递给它:
export const useShortcuts = ({ ref }) => {
useEffect(() => {
const trapper = new mousetrap(ref.current);
Run Code Online (Sandbox Code Playgroud)
代码工作,但现在我试图写的测试此使用react-testing-library和@测试库/反应钩库。
我使用renderHook的@测试库/反应型挂钩,但我不知道如何创建裁判或模拟组件的裁判之外。
it('should create shortcuts with no ref', () => {
const ref = ????? // how do I do this
const { result } = renderHook(() => useShortcuts({ ref }), {
initialProps: true
});
});
Run Code Online (Sandbox Code Playgroud) 所以我对反应测试还很陌生。我有一个在组件内部调用的自定义挂钩。我正在使用renderHook中的方法react-hook-testing-library。
useEffect我需要测试是否调用自定义挂钩内的方法。我似乎无法弄清楚这一点。
在另一种情况下,我需要弄清楚是否trackPdpGtm没有被调用。
注意:该钩子不返回任何数据。这主要用于发送分析信息。
目前的方法:
使用PdpGtm.js
import { useEffect } from 'react';
import { trackPdpGtm } from 'utils/gtm/pdpGtmUtils';
import _ from 'utils/lodashImports';
export default function useGtmPdp(data = {}) {
console.log('are you getting called?');
const { relatedProducts, results, priceInfo, breadcrumbs } = data;
const relatedProductsLoaded = _.get(relatedProducts, 'relatedProductsLoaded');
useEffect(() => {
if (relatedProductsLoaded) {
trackPdpGtm(data);
}
}, [relatedProductsLoaded, results, priceInfo, breadcrumbs]);
}
Run Code Online (Sandbox Code Playgroud)
我需要测试是否trackPdpGtm被调用。还需要检查它是否在另一个测试用例中没有被调用。
gtm.test.js
import { renderHook, cleanup, act } from …Run Code Online (Sandbox Code Playgroud) javascript reactjs jestjs react-testing-library react-hooks-testing-library
我想测试一个自定义钩子react-testing-library,因此我将以下代码添加到 beforeEach 中:
let renderedHook ;
beforeEach(() => {
renderedHook = renderHook(() => useFetch());
});
test('.....', () => {
expect(renderedHook.current.data).toBe(1);
});
Run Code Online (Sandbox Code Playgroud)
上面的代码运行良好!但我使用的是 TypeScript,在这种情况下合适的类型是什么let renderedHook ?
typescript reactjs react-testing-library react-hooks-testing-library
然后,我的导航组件将在侧边栏中切换状态以及打开和关闭菜单,然后尝试在代码覆盖范围中获取此通道。当我登录测试时,我的状态始终显示为未定义。不知道如何在这里解决这个问题。
组件.js:
const Navigation = (props) => {
const {
classes,
...navProps
} = props;
const [anchorEl, setanchorEl] = useState(null);
const [sidebarOpen, setsidebarOpen] = useState(false);
const toggleSidebar = () => {
setsidebarOpen(!sidebarOpen);
};
const toggleMenuClose = () => {
setanchorEl(null);
};
const toggleMenuOpen = (event) => {
setanchorEl(event.currentTarget);
};
return (
<Fragment>
<Button
onClick={toggleMenuOpen}
/>
<SideMenu
toggleSidebar={toggleSidebar}
>
<Menu
onClose={toggleMenuClose}
>
</SideMenu>
</Fragment>
);
};
export default Navigation;
Run Code Online (Sandbox Code Playgroud)
测试.js:
import { renderHook, act } from '@testing-library/react-hooks';
// Components
import Navigation …Run Code Online (Sandbox Code Playgroud) 我有一些代码,在一个钩子中,来检测浏览器是否在线/离线:
export function useConnectivity() {
const [isOnline, setNetwork] = useState(window.navigator.onLine);
const updateNetwork = () => {
setNetwork(window.navigator.onLine);
};
useEffect(() => {
window.addEventListener('offline', updateNetwork);
window.addEventListener('online', updateNetwork);
return () => {
window.removeEventListener('offline', updateNetwork);
window.removeEventListener('online', updateNetwork);
};
});
return isOnline;
}
Run Code Online (Sandbox Code Playgroud)
我有这个基本测试:
test('hook should detect offline state', () => {
let internetState = jest.spyOn(window.navigator, 'onLine', 'get');
internetState.mockReturnValue(false);
const { result } = renderHook(() => useConnectivity());
expect(result.current.valueOf()).toBe(false);
});
Run Code Online (Sandbox Code Playgroud)
但是,我想运行一个测试,看看它在offline触发事件时是否返回正确的值,而不仅仅是在渲染时模拟返回值之后。解决这个问题的最佳方法是什么?到目前为止我得到的是这样的:
test('hook should detect offline state then online state', async () => {
const …Run Code Online (Sandbox Code Playgroud) reactjs jestjs react-testing-library react-hooks react-hooks-testing-library
我有一个简单的钩子,可以获取值并将其设置为选项,如下所示:
import Fuse from 'fuse.js'
import React from 'react'
// prefetches options and uses fuzzy search to search on that option
// instead of fetching on each keystroke
export function usePrefetchedOptions<T extends {}>(fetcher: () => Promise<T[]>) {
const [options, setOptions] = React.useState<T[]>([])
React.useEffect(() => {
// fetch options initially
const optionsFetcher = async () => {
try {
const data = await fetcher()
setOptions(data)
} catch (err) {
errorSnack(err)
}
}
optionsFetcher()
}, [])
// const fuseOptions = {
// …Run Code Online (Sandbox Code Playgroud) testing reactjs react-testing-library react-hooks-testing-library
我有一个自定义的 React 钩子,它本身使用了react-query useQuery():
const useFetchSomething = () => {
const { data, isLoading } = useQuery('key', ....);
return .......
}
Run Code Online (Sandbox Code Playgroud)
我必须创建一个自定义挂钩,然后使用useQuery()其中的挂钩,因为它有一些功能并从反应查询获取数据!
我尝试用以下方法测试这个钩子react-hooks-testing-library:
const { result } = renderHook(() => useFetchSomething());
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:
Error: Uncaught [Error: No QueryClient set, use QueryClientProvider to set one]
Run Code Online (Sandbox Code Playgroud)
为此,我该如何包装这部分:renderHook(() => useFetchSomething())与提供者?
javascript reactjs react-testing-library react-hooks-testing-library react-query
我有一个自定义钩子,我正在尝试编写使用 React hooks 测试库包的测试,我想知道如何测试未在自定义钩子中返回但在其他函数中使用的内部函数。
const customHook = () => {
const [count, setCount] = React.useState(0);
const doSomeThing = () => {
..code
}
const increment = () => {
doSomeThing(); //Would like to make assertations on this
setCount((x) => x + 1 );
}
return { count, increment }
}
export default customHook;
Run Code Online (Sandbox Code Playgroud)
测试
it('Should call increment', () => {
const { result } = renderHook(() => useCustomHook())
act(() => {
result.current.increment();
});
expect(doSomeThing).toHaveBeenCalled(); //end result of what I would …Run Code Online (Sandbox Code Playgroud) reactjs jestjs react-testing-library react-hooks-testing-library
react-hooks-testing-library ×10
reactjs ×8
jestjs ×4
react-hooks ×3
javascript ×2
testing ×2
react-query ×1
typescript ×1