gpt4 book ai didi

reactjs - 使用 Jest 和 Enzyme 进行测试时设置 URL 参数

转载 作者:行者123 更新时间:2023-12-03 13:40:07 26 4
gpt4 key购买 nike

我的组件有:

 class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm:
typeof this.props.match.params.searchTerm !== "undefined"
? this.props.match.params.searchTerm
: ""
};
}

测试是:

 test("Search should render correct amount of shows", () => {
const component = shallow(<Search shows={preload.shows} />);
expect(component.find(ShowCard).length).toEqual(preload.shows.length);
});

我明白

TypeError: Cannot read property 'params' of undefined

如何解决该问题或如何在测试中设置查询参数?

最佳答案

似乎在测试之外,Search 组件正确接收了 match 属性。
在测试中浅层渲染时,您可以将其作为 Prop 传递:

test("Search should render correct amount of shows", () => {
const match = { params: { searchTerm: 'foo' } }
const component = shallow(<Search shows={preload.shows} match={match}/>);
expect(component.find(ShowCard).length).toEqual(preload.shows.length);
});

在这种情况下,您并没有以不好的方式更改被测组件,您的测试用例只是发现了一个错误,这是好的并且应该针对测试,并且您通过实现默认 Prop 改进了组件,使其更加稳健。

关于reactjs - 使用 Jest 和 Enzyme 进行测试时设置 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48399741/

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