我如何测试使用 props.history 的按钮 onClick 在 rtl 中的功能?
How can I test a button onClick which uses props.history for it's function in rtl?
我正在使用 React 测试库,我想测试一个按钮:
<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 时运行良好,但仅在测试时失败。
我该如何解决未定义的推送?
你必须将道具传递给渲染的组件,在这种情况下 - <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);
});
我正在使用 React 测试库,我想测试一个按钮:
<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 时运行良好,但仅在测试时失败。 我该如何解决未定义的推送?
你必须将道具传递给渲染的组件,在这种情况下 - <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);
});