我有这个自定义钩子
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
const useZRoutes = () => {
const navigate = useNavigate();
const { search, hash } = useLocation();
const [searchParams, setSearchParams] = useSearchParams();
return {
getQueryParam: <T>(key: string): T | null => {
if (searchParams.has(key)) {
const value = searchParams.get(key);
return value as unknown as T;
}
return null;
},
deleteQueryParam: (key: string): void => {
if (searchParams.has(key)) {
searchParams.delete(key);
setSearchParams(searchParams);
}
},
extendsNavigate: (pathname: string) => navigate({ pathname, search, hash }), …Run Code Online (Sandbox Code Playgroud) 我正在使用react-testing-library和jest。在 componentdidupdate 中尝试获取“ this.testRef.current.offsetHeight ”,即使在加载内容后,offsetHeight 仍为0 。我想要 DOM 的精确 offsetHeight 因为有一些基于它的条件。
在反应测试库和笑话中是否有任何可能的解决方案可以解决。
我正在使用angerouslySetInnerHTML来绑定testRef 元素的html 内容。
我有一些正在进行的测试,这是按预期工作的:
describe('Parent', () => {
afterEach(() => {
cleanup();
jest.resetModules();
});
describe('Test 1', () => {
const wrapper = render(
<MockProvider>
<MyComponent />
</MockProvider>,
);
test('1 ', () => {
expect(wrapper.baseElement).toMatchSnapshot();
expect(wrapper.getByText('Apply').disabled).toBe(true);
});
});
describe('Test 2', () => {
test('1 ', () => {
const wrapper = render(
<MockProvider>
<MyComponent />
</MockProvider>,
);
console.log(wrapper.getByText('Apply').disabled);
expect(1).toBe(1);
});
});
});
Run Code Online (Sandbox Code Playgroud)
但是,当我将第二个渲染函数移出测试时,它会出错:
describe('Parent', () => {
afterEach(() => {
cleanup();
jest.resetModules();
});
describe('Test 1', () => {
const wrapper = render(
<MockProvider>
<MyComponent …Run Code Online (Sandbox Code Playgroud) 我试图模拟被拒绝的值并收到此错误。奇怪的是,这种构造在“成功”的情况下有效addUser.mockImplementation(value => jest.fn().mockResolvedValue(value)),但是当我尝试用拒绝做同样的技巧时,它不起作用并说“无法读取 null 的属性 'createEvent'”
这是我的测试用例
it('receives invalid value and throws an error', async () => {
addUser.mockImplementation(() =>
jest.fn().mockRejectedValue(new Error('Sample error'))
)
const enqueueSnackbar = jest.fn()
useSnackbar.mockReturnValue({ enqueueSnackbar })
const { emailInput, form, submitButton } = setup()
await act(async () => {
fillIn(emailInput, 'sample@mail.com')
})
expect(emailInput.value).toBe('sample@mail.com')
expect(submitButton).toHaveProperty('disabled', false)
await act(async () => {
fireEvent.submit(form)
})
expect(enqueueSnackbar).toHaveBeenCalledTimes(1)
expect(enqueueSnackbar).toHaveBeenCalledWith(`Sample error`, {
variant: 'error'
})})
Run Code Online (Sandbox Code Playgroud)
有谁知道如何使它工作?
我有一个 h1 标签,我试图使用特定的标题级别获取节点,但运行时出现错误:
找到多个具有“标题”角色的元素
根据文档,此查询应该仅返回 h1。
这是例子:
import React from "react";
import { render, screen } from "@testing-library/react";
it("Should found only header1", async () => {
render(
<div>
<h1>editable content</h1>
<p>and</p>
<h2>other header</h2>
</div>
);
screen.debug(screen.getByRole("heading", { level: 1 }));
});Run Code Online (Sandbox Code Playgroud)
这是错误:
Found multiple elements with the role "heading"
(If this is intentional, then use the `*AllBy*` variant of the query (like `queryAllByText`, `getAllByText`, or `findAllByText`)).
<body>
<div>
<div>
<h1>
editable content
</h1>
<p>
and
</p>
<h2>
other …Run Code Online (Sandbox Code Playgroud)我正在尝试在我的 React 应用程序中进行快照测试。我已经使用react-testing-library进行一般单元测试。然而,对于快照测试,我在网上看到了不同的方法,要么使用react-test-renderer,要么使用react-testing库。这里有3个例子,它们之间有什么区别以及首选是什么?
1.使用react-test-renderer
test('renders correctly', () => {
const tree = renderer
.create(<Link page="http://www.facebook.com">Facebook</Link>)
.toJSON();
expect(tree).toMatchSnapshot();
});
Run Code Online (Sandbox Code Playgroud)
2.使用react-testing-library和asFragment()
test('renders correctly', () => {
const { asFragment } = render(<NotFound />);
expect(asFragment()).toMatchSnapshot();
});
Run Code Online (Sandbox Code Playgroud)
3.使用react-testing-library和容器
test('renders the component', () => {
const container = render(<Component />)
expect(container.firstChild).toMatchSnapshot()
})
Run Code Online (Sandbox Code Playgroud) 我正在第一次渲染时测试组合框,组合框的初始值未定义。然后使用查询参数和 useEffect 组件找到相关选项并为其设置值状态。
const Component = () => {
[value, setValue] = useState(undefined);
useEffect(() => {
setValue("hello")
}, [])
return(
<Combobox value={value}/>
)
}
Run Code Online (Sandbox Code Playgroud)
it("should render with value as hello", () => {
const {getByText} = render(<Component/>)
const text = getByText("hello")
})
Run Code Online (Sandbox Code Playgroud)
该测试套件抛出此错误:
TestingLibraryElementError: Unable to find an element with the text: Photobug. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your …Run Code Online (Sandbox Code Playgroud) javascript reactjs react-testing-library react-hooks react-state
我正在尝试用于userEvent测试 UI 交互。但是,它似乎无法正常工作。我用这个文档作为参考。是否需要进行一些必要的设置才能使其正常工作?
这是测试代码:
test('A', () => {
//setup
const user = userEvent.setup();
const sensing = jest.fn();
const subject = (<button onClick={sensing}>testButton</button>);
render(subject);
// run
user.click(screen.getByText('testButton'));
// check
expect(sensing).toBeCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)
使用fireEvent.click代替确实user.click有效。
package.json 的一部分
"react": "^18.1.0",
"react-dom": "^18.1.0",
"@storybook/react": "^6.4.22",
"@storybook/testing-library": "^0.0.9",
"@testing-library/dom": "^8.13.0",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.2.0",
"@testing-library/react-hooks": "^8.0.0",
"@testing-library/user-event": "^14.2.0",
...
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 React 测试库创建单元测试,单击 React Router 链接来验证某些页面的显示。我使用的设置与此处找到的答案非常相似。当我运行测试时,我得到了ReferenceError: Request is not defined. 由于我使用的是 RouterProvider,我无法完全遵循 React 测试库文档。
我在专用文件中设置了路线:
\nexport const routes: RouteObject[] = [{\n path: \'/\',\n element: <AppWrapper />,\n errorElement: <PageNotFoundScreen />,\n children: [{\n path: \'/\',\n element: <FeaturedSearchScreen />\n },{\n path: \'auth\',\n element: <AuthScreen />,\n children: [{\n path: \'login\',\n element: <LoginForm />\n },{\n path: \'signup\',\n element: <SignUpForm />\n }]\n },{\n path: \'dashboard\',\n element: <DashboardScreen />\n },{\n path: \'search\',\n element: <SearchResultsScreen />,\n loader: searchLoader\n } \n ]\n}];\nRun Code Online (Sandbox Code Playgroud)\n … 我正在使用 create-react-app、Jest 和 react-testing-library 来配置聊天机器人项目。
我有一个使用 useRef 钩子的功能组件。当一条新消息到来时,会触发 useEffect 钩子并通过查看 ref 的当前属性引起滚动事件。
const ChatBot = () => {
const chatBotMessagesRef = useRef(null)
const chatBotContext = useContext(ChatBotContext)
const { chat, typing } = chatBotContext
useEffect(() => {
if (typeof chatMessagesRef.current.scrollTo !== 'undefined' && chat && chat.length > 0) {
chatBotMessagesRef.current.scrollTo({
top: chatMessagesRef.current.scrollHeight,
behavior: 'smooth'
})
}
// eslint-disable-next-line
}, [chat, typing])
return (
<>
<ChatBotHeader />
<div className='chatbot' ref={chatBotMessagesRef}>
{chat && chat.map((message, index) => {
return <ChatBotBoard answers={message.answers} key={index} currentIndex={index + …Run Code Online (Sandbox Code Playgroud) reactjs ×5
jestjs ×4
dom ×1
javascript ×1
react-hooks ×1
react-router ×1
react-state ×1
typescript ×1
unit-testing ×1