给出一个简单的组件:
export default class SearchForm extends Component {
constructor(props) {
super(props)
this.state = { query: '' }
}
onSubmit = (event) => {
event.preventDefault()
history.push(`/results/${this.state.query}`, { query: this.state.query })
}
render() {
return (
<form onSubmit={this.onSubmit}>
<input
type="text"
value={this.state.query}
onChange={event => this.setState({ query: event.target.value })}
/>
<button>Search</button>
</form>
)
}
}
Run Code Online (Sandbox Code Playgroud)
而且测试:
describe('SearchForm Component', () => {
it('should navigate to results/query when submitted', () => {
const wrapper = shallow(<SearchForm />)
...?
})
})
Run Code Online (Sandbox Code Playgroud)
如何验证表单提交是否将用户带到具有正确查询值的下一页?
我试过简单地模拟onSubmit处理程序并至少确认它已被调用,但这会导致安全性错误history.push.
const wrapper …Run Code Online (Sandbox Code Playgroud) 我正在使用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