gpt4 book ai didi

reactjs - 你如何测试路由器与 jest 和 enzyme 的匹配参数?

转载 作者:搜寻专家 更新时间:2023-10-30 20:34:52 24 4
gpt4 key购买 nike

假设我有以下从 https://www.codeday.top/2017/11/08/56644.html 中获取的组件.这里我使用 match.params 来访问 id。我将如何为此组件编写单元测试以使用 Jest+Enzyme+Typescript+React 测试 h2 元素的存在。

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Route, BrowserRouter as Router, Link, match } from 'react-router-dom';

// define React components for multiple pages
class Home extends React.Component<any, any> {
render() {
return (
<div>
<div>HOME</div>
<div><Link to='/details/id123'>Goto Details</Link></div>
</div>);
}
}

interface DetailParams {
id: string;
}

interface DetailsProps {
required: string;
match?: match<DetailParams>;
}

class Details extends React.Component<DetailsProps, any> {
render() {
const match = this.props.match;
if (match) {
return (
<div>
<h2>Details for {match.params.id}</h2>
<Link to='/'>Goto Home</Link>
</div>
);
} else {
return (
<div>
<div>Error Will Robinson</div>
<Link to='/'>Goto Home</Link>
</div>
)
}
}
}

ReactDOM.render(
<Router>
<div>
<Route exact path="/" component={Home} />
<Route exact path="/details/:id" component={(props) => <Details required="some string" {...props} />} />
</div>
</Router>

, document.getElementById('root')
);

最佳答案

使用containsMatchingElement

const wrapper = shallow(
<Details
required={true}
match={{params: {id: 1}, isExact: true, path: "", url: ""}}
/>
);
expect(wrapper.containsMatchingElement(<h2>Details for 1</h2>)).toBeTruthy();

关于reactjs - 你如何测试路由器与 jest 和 enzyme 的匹配参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48895514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com