javascript - 如何测试使用 props.history 的按钮 onClick 在 rtl 中的功能?
问题描述
我正在使用反应测试库,我想测试一个按钮:
<button data-testid="btn" onClick={() => props.history.push(`/post/${value}`)} > Search </button>
<input data-testid="input" type="text" value={value} onChange={(e) => handle(e.target.value)} />
我像这样测试它的 onClick 功能:
test('Button should navigate the url when enabled', () => {
render(<Home />);
const input = screen.getByTestId('input');
const btn = screen.getByTestId('btn');
fireEvent.change(input, { target: { value: '12' } });
fireEvent.click(btn);
});
但这给了我一个错误:
TypeError: Cannot read property 'push' of undefined
19 | <button
20 | data-testid="btn"
> 21 | onClick={() => props.history.push(`/post/${value}`)}
| ^
22 | disabled={!value}
23 | type="submit"
24 | >
当我 npm start 时,应用程序本身运行良好,但仅在测试时失败。我该如何解决这个 undefined 的推送?
解决方案
您必须将道具传递给渲染的组件,在这种情况下 - <Home />
:
import history from 'history' // Or a file you made that contains an instance of history
test('Button should navigate the url when enabled', () => {
render(<Home history={history} {...otherProps} />);
const input = screen.getByTestId('input');
const btn = screen.getByTestId('btn');
fireEvent.change(input, { target: { value: '12' } });
fireEvent.click(btn);
});
推荐阅读
- html - 是否可以使用 bootstrap 4 网格以这种特定方式更改我的移动页面布局?
- apache-kafka - Flink kafka - 消息优先级
- r - 要因子的虚拟变量
- javascript - 如何操作 SVG 的 Z-index
- kotlin - 如果 channel.send() 没有接收到任何值,channel 会保持我的协程运行吗?
- python - 无法检索爬取信息
- jquery - 如何在将来使用 column().search() 过滤带有日期的行
- c - 当 a 和 b 都小于 c,但 a * b 溢出时,如何计算 a * b / c?
- android - 在 react native 中添加 facebook 广告后无法构建项目
- react-native - 从本机事件发射器回调后,React 本机 UI 未呈现。甚至回调有状态改变