我正在使用RedwoodJS,它在后台使用 React 和 React 测试库。由于 useLocation() 挂钩,我正在努力测试一个组件(以及树中具有此组件的所有页面组件)。
\n当在我的组件中使用useLocation()钩子时,我需要使用模拟浏览器位置历史记录的路由器来包装我的正在测试的组件以防止错误Error: Uncaught [TypeError: Cannot read property \'pathname\' of undefined]。
然而,当我这样做时,导航组件不再完全呈现,所以我无法测试它......有什么想法吗?
\n//import statements\n\nconst renderListItems = (pathname) => {\n const NavigationItems = [{..},{..},{..}] // example\n\n return NavigationItems.map((item) => {\n const selected = pathname.indexOf(item.path) ? false : true\n return (\n <ListItem\n button\n key={item.text}\n onClick={() => {\n navigate(item.route)\n }}\n selected={selected}\n >\n <ListItemText primary={item.text} />\n </ListItem>\n )\n })\n}\n\nconst Navigation = () => {\n const { pathname } …Run Code Online (Sandbox Code Playgroud) testing reactjs react-router react-testing-library redwoodjs
await waitFor()使我的测试失败,但waitFor()使我的测试成功(无需等待)。
官方医生说
异步方法返回一个 Promise,因此在调用它们时必须始终使用await 或.then(done)。(https://testing-library.com/docs/guide-disappearance)
我不知道如何才能正确测试。我必须使用吗rerender?
it('toggles active status', async () => {
render(<List {...listProps} />);
const targetItem = screen.getByRole('heading', { name: /first/i });
// de-active color is GRAY2, active color is MINT
expect(targetItem).toHaveStyle({ color: GRAY2 });
// click to change the color of targetItem
// it dispatch action that update listProps
// So changing listProps makes <List /> re-rendering
fireEvent.click(targetItem);
await waitFor(() => {
// It throws an error because the …Run Code Online (Sandbox Code Playgroud) 我想要做的是测试单击表标题列是否使用React 测试库first对表的行进行排序。我模拟了一些似乎渲染得很好的数据。
注意:我很确定这与所使用的组件无关,所以我没有费心将其放在这里。
但是,当我使用 React 测试库(应该对行进行排序)触发单击事件时,行不会排序。
似乎没有找到正确的元素。
这是浏览器中的组件树:
describe("Testing fullscring timp table", () => {
let mockData = [];
let columns = [];
let store;
let history;
let mockStore;
let global;
beforeAll(() => {
// column definitions for the Table component
columns = [
{ dataKey: "1", title: "first", dataIndex: 1 },
{ dataKey: "2", title: "second", dataIndex: 2 },
{ dataKey: "3", title: "third", dataIndex: 3 },
{ dataKey: "4", title: "fourth", dataIndex: 4 …Run Code Online (Sandbox Code Playgroud) 我有以下组件
import React, { useState, useEffect } from 'react';
import { FiSearch } from 'react-icons/fi';
import { useProducts } from '../../hooks';
export default function SearchBar() {
const [query, setQuery] = useState('');
const [debounced, setDebounced] = useState('');
useEffect(() => {
const timeout = setTimeout(() => {
setDebounced(query);
}, 300);
return () => {
clearTimeout(timeout);
};
}, [query]);
const handleChange = (e) => {
e.preventDefault();
setQuery(e.target.value);
};
useProducts(debounced);
return (
<div className="search-form">
<FiSearch className="search-form__icon" />
<input
type="text"
className="search-form__input"
placeholder="Search for brands or …Run Code Online (Sandbox Code Playgroud) 我的组件有多个选择器:
import { useSelector } from 'react-redux'
...
const data1 = useSelector(xxxxx)
const data2 = useSelector(yyyyy)
Run Code Online (Sandbox Code Playgroud)
如何正确模拟测试文件中的每个?
import { useSelector } from 'react-redux'
jest.mock('react-redux', () => ({
useSelector: jest.fn()
}))
....
useSelector.mockImplementation(() => ({
dataready: true
}))
Run Code Online (Sandbox Code Playgroud)
在这种情况下它真正嘲笑的是哪个选择器?
我是 NextJS 环境的初学者,我正在从常见的 ReactJS 迁移应用程序。这是对另一个页面链接的简单测试。那么,我应该如何重构我的测试?
*我正在使用 Jest 和测试库。
// My current code in ReactJS
test('Should go to Post page', () => {
const post = mockPostModel()
const history = createMemoryHistory({ initialEntries: ['/'] })
render(
<Router history={history}>
<BlogPost post={post} />
</Router>
)
fireEvent.click(screen.getByTestId('link'))
expect(history.location.pathname).toBe(`/post/${post.title}`)
})
Run Code Online (Sandbox Code Playgroud) 如何在 Next JS 中使用 jest 模拟“next/link”中的 Link 组件,并在单击链接元素后检查重定向路径?
这是带有测试的示例组件:
import Link from "next/link";
export default function Nav() {
return (
<div>
<Link href="/login">
<span>Click here</span>
</Link>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
describe("Nav", () => {
it("redirects correctly", async () => {
render(<Nav />)
fireEvent.click(screen.getByText("Click here"));
// check if redirect to href prop works as expected
});
});
Run Code Online (Sandbox Code Playgroud) 我有一个测试用例,我需要模拟 useRef 才能返回模拟当前值。我尝试了 jest.mock 但它返回一个 HTMLDivElement 。
代码:
const ref = useRef<HTMLDivElement | null>(null);
Run Code Online (Sandbox Code Playgroud)
测试:
jest.mock('react', () => {
const originReact = jest.requireActual('react');
return {
...originReact,
useRef: jest.fn(),
};
});
React.useRef.mockReturnValue({ current: {offsetWith: 100} });
Run Code Online (Sandbox Code Playgroud)
模拟回报
[ { type: 'return', value: { current: [HTMLDivElement] } } ]
Run Code Online (Sandbox Code Playgroud) unit-testing reactjs jestjs react-testing-library react-hooks
似乎无法使用反应测试库获取输入的值,但由于某种原因,可以通过fireEvent. nameInput是一个实际的输入元素
test('verify name validation works', () => {
const { getByPlaceholderText, getByTestId, debug } = render(<Home/>)
const passForm = getByTestId('form')
const nameInput = getByPlaceholderText('Name');
fireEvent.change(nameInput, { target: { value: 'TestName' }});
debug(nameInput.value) // error
})
Run Code Online (Sandbox Code Playgroud)
更新
我必须断言 asHTMLInputElement可以作为 ts 推断它是通用的HTMLElement
expect((nameInput as HTMLInputElement).value)
在我们的 Next.js 应用程序中,我们使用vinissimus/next-translate包进行翻译。我们进行相应的设置:
next.config.js:
const nextTranslate = require('next-translate')
module.exports = nextTranslate()
Run Code Online (Sandbox Code Playgroud)
i18n.js 配置文件:
{
"locales": ["en"],
"defaultLocale": "en",
"pages": {
"*": ["en"],
"/": ["en"],
}
}
Run Code Online (Sandbox Code Playgroud)
通过useTranslation钩子在组件内部使用它:
const App = () => {
const { t, lang } = useTranslation();
return (
<Homepage>
<span>{t(`${lang}:homepage.title.header`)}</span>
</Homepage>
Run Code Online (Sandbox Code Playgroud)
我的问题是如何用反应测试库来测试它?
当我在测试中渲染组件时,翻译不起作用,仅返回密钥。另外,我想通过getByText / findByText并通过来测试它:
{t(`${lang}:homepage.header`)}
Run Code Online (Sandbox Code Playgroud)
如果我在应用程序中没有使用任何i18nProvider而仅使用此i18n.js配置,如何设置某种包装器或配置进行测试?
internationalization reactjs jestjs next.js react-testing-library
reactjs ×9
jestjs ×5
next.js ×3
unit-testing ×3
typescript ×2
javascript ×1
react-hooks ×1
react-router ×1
redwoodjs ×1
testing ×1