我是React-Testing-Library / Jest的新手,它试图编写测试以查看路由导航(使用react-router-dom)是否正确执行。到目前为止,我一直在关注README和本教程的用法。
我的组件之一在局部函数中使用了scrollIntoView,这导致测试失败。
TypeError: this.messagesEnd.scrollIntoView is not a function
45 |
46 | scrollToBottom = () => {
> 47 | this.messagesEnd.scrollIntoView({ behavior: "smooth" });
| ^
48 | }
49 |
50 |
Run Code Online (Sandbox Code Playgroud)
这是我的chatbot组件中的功能:
componentDidUpdate() {
this.scrollToBottom();
}
scrollToBottom = () => {
this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}
Run Code Online (Sandbox Code Playgroud)
这是测试失败的示例:
test('<App> default screen', () => {
const { getByTestId, getByText } = renderWithRouter(<App />)
expect(getByTestId('index'))
const leftClick = {button: 0}
fireEvent.click(getByText('View Chatbot'), leftClick) <-- test …Run Code Online (Sandbox Code Playgroud) javascript reactjs jestjs react-router react-testing-library
我需要一些帮助,以帮助您了解如何使用来测试应用程序React Context。
这是我的示例设置。
context.js
import React from 'react'
export const AppContext = React.createContext()
Run Code Online (Sandbox Code Playgroud)
App.js
import React from 'react'
import MyComponent from './MyComponent'
import {AppContext} from './context'
const App extends React.Component {
state = {
items: []
}
handleItemAdd = newItem => {
const {items} = this.state
items.push(newItem)
this.setState(items)
}
render() {
return (
<AppContext.Provider value={{
addItem: this.handleItemAdd
}}>
<MyComponent />
</AppContext.Provider>
)
}
}
export default App
Run Code Online (Sandbox Code Playgroud)
MyComponent.js
import React from 'react'
import {AppContext} from './context'
const MyComponent …Run Code Online (Sandbox Code Playgroud) unit-testing reactjs jestjs react-context react-testing-library
我正在使用 Jest 和 react-testing-library 测试调用异步函数的组件。当我运行测试时出现错误ReferenceError: waitForElement is not defined
按照这个说明我尝试过:
withoutuseBuiltins在 中的选项.babelrc,包括@babel/polyfill在文件顶部的app.test.jsx,以及@babel/polyfill在 中的条目数组中没有的选项webpack.config.js。ReferenceError: waitForElement is not defined我从测试运行中收到错误,但应用程序编译成功
with useBuiltIns: 'entry',包括@babel/polyfill在文件顶部app.test.jsx,而 without 则@babel/polyfill位于 中的条目数组中webpack.config.js。我得到了Cannot find module 'core-js/modules/es6.array.every' from 'app.test.jsx',应用程序无法编译。
with useBuiltIns: 'entry',不包括@babel/polyfill在文件顶部app.test.jsx,并且WITH@babel/polyfill位于 中的条目数组中webpack.config.js。ReferenceError: waitForElement is not defined我从测试运行中 收到错误,并且应用程序无法编译。
这是案例 1 中的代码:
在 …
我已经建立了一个github项目,以了解如何更好地测试react(v 16.8.0)useEffect挂钩。我进行了一个api调用以在useEffect中获取数据,并将接收到的数据设置为状态组件元素。我的组件将查询作为道具接收,如果查询道具字符串不为空,则进行api调用。我想测试使用无空查询prop进行api调用,并且组件将其状态设置为正确。
我知道测试useEffect面临的问题是,与useEffect相关的效果不会阻止浏览器更新屏幕,因此在useEffect发挥作用之前,测试将结束。我从React文档中了解到,有来自react-test-utils的名为act的API,该API 被认为可以包装渲染组件的代码并对其执行更新。即使我尝试使用它,我的代码仍然会遇到相同的问题。
这是我要测试的组件:
const DisplayData = ({ query, onQueryChange }) => {
const [data, setData] = useState({ hits: [] });
useEffect(() => {
const fetchData = async () => {
const result = await axios.get(
`http://hn.algolia.com/api/v1/search?query=${query}`,
);
setData(result.data);
};
if (!!query) fetchData();
}, [query]);
return (
<ul>
{data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
);
};
Run Code Online (Sandbox Code Playgroud)
这是我为此编写的测试:
it("should show new entries …Run Code Online (Sandbox Code Playgroud) 我通过 css 表将样式应用于按钮。当应用程序启动时,按钮只有一个 .Button 类。单击按钮时,.clicked会添加一个额外的类,然后修改按钮的样式。按钮文本也从“按钮”更改为“单击按钮”。
我希望 RTL 查找这些样式更改(运行应用程序时很明显)。
按钮.css:
.Button {
background-color: blueviolet;
}
.clicked {
transform: scale(8.0);
background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
测试代码:
import React from 'react';
import { cleanup, render, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import App from './App';
describe('clicking on the button', () => {
afterAll(cleanup);
let upDatedButton: HTMLElement;
beforeAll(async () => {
const { getByText, findByText } = render(<App />);
const button = getByText('button');
fireEvent(
button,
new MouseEvent('click', {
bubbles: true,
cancelable: true
})
) …Run Code Online (Sandbox Code Playgroud) 我有一个 React 组件,它允许用户向远程服务提交可能长时间运行的查询。当查询运行时,该组件会显示取消按钮。我想测试此按钮是否按预期显示,其单击处理程序是否取消之前的 API 请求,等等。
由于该按钮仅在异步 API 调用处于活动状态时才出现,因此我为此目的编写的测试在异步 API 本身的模拟实现中对按钮进行了断言。它们不是超级优雅,但我确认当我删除部分生产代码时它们确实会像我预期的那样变成红色。
在将 @testing-library/react 从 8.0.1 升级到 9.3.2 时,尽管测试仍然通过,但我现在多次收到以下警告:
console.error node_modules/@testing-library/react/dist/act-compat.js:52
Warning: You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one.
Run Code Online (Sandbox Code Playgroud)
我已在以下 CodeSandbox 中重现了该问题(请务必选择右侧的“测试”选项卡,然后查看右下角的“控制台”消息)。
关于这个GitHub 问题的最后评论说,act()只要我使用 React 测试库助手和函数(我就是这样),我就不需要担心。我缺少什么?
我正在尝试使用 React 应用程序测试工作流。当所有字段都填满工作流程步骤时,用户可以单击“下一步”按钮。此操作在减速器中注册状态并更改 URL 以转到下一个工作流程步骤。
根据 RTL 文档,我使用此功能将测试中的组件包装在商店提供程序和连接的路由器中:
export const renderWithRedux = (ui: JSX.Element, initialState: any = {}, route: string = "/") => {
// @ts-ignore
const root = reducer({}, { type: "@@INIT" })
const state = mergeDeepRight(root, initialState)
const store = createStoreWithMiddleWare(reducer, state)
const history = createMemoryHistory({ initialEntries: [route]})
const Wrapper = ({ children }: any) => (
<Provider store={store}>
<ConnectedRouter history={history}>{children}</ConnectedRouter>
</Provider>
)
return {
...render(ui, { wrapper: Wrapper }),
// adding `store` to the returned utilities …Run Code Online (Sandbox Code Playgroud) reactjs redux react-redux react-testing-library connected-react-router
许多React 测试库示例展示了如何使用getByText查询查找和单击按钮,如下所示:
fireEvent.click(getByText("Create"))
Run Code Online (Sandbox Code Playgroud)
或者
userEvent.click(getByText("Create"))
Run Code Online (Sandbox Code Playgroud)
但是,按钮没有文本而只有 SVG 图标是很常见的,例如 Material UI 的图标按钮或浮动操作按钮。有没有推荐的方法来查询和单击这些按钮?对于上下文,我使用的是配套用户事件库提供的更高级别的事件。
我想访问带有“icon”类的第一个元素。
DOM 看起来是这样的:
<div class="parent">
<div data-testid="add">
<div class="info"></div>
<div class="action">
<div class="icon"/> // <== I want to access this
</div>
</div>
</div>
<div class="parent">
<div data-testid="add">
<div class="info"></div>
<div class="action">
<div class="icon"/>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
如何获得第一个带有“icon”类的div?
我努力了:
const element = queryAllByTestId('add')[0].querySelector(
'div'
)[1];
Run Code Online (Sandbox Code Playgroud)
这使得元素未定义。
我正在测试一个包含 Material Ui TextField 组件的组件(我们称之为 MyComponent):
<TextField
name="code"
aria-label="code"
onKeyPress={keyPressHandler(codeRegExp)}
value={values.code}
placeholder={codePlaceholder}
onChange={handleChange}
InputProps={{
classes: {
input: classes.code,
},
}}
onBlur={handleBlur}
helperText={
touchedValues.code && errorValues.code ? errorValues.code : ''
}
FormHelperTextProps={{classes: {root: classes.errorMessage}}}
/>
Run Code Online (Sandbox Code Playgroud)
我为此编写了测试:
test('Checking the initial rendering of the component', () => {
const initialState = {
refs: {
choice: '',
creationDate: '',
},
};
render(<MyComponent />, {initialState});
expect(screen.getByRole('textbox', {name: /code/i})).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
测试失败,我收到此错误:
TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name `/code/i`
Here …Run Code Online (Sandbox Code Playgroud) reactjs ×8
jestjs ×4
javascript ×2
babeljs ×1
css ×1
material-ui ×1
react-hooks ×1
react-redux ×1
react-router ×1
redux ×1
unit-testing ×1