我的组件有:
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:无法读取未定义
的属性'params'
如何解决这个问题或如何在我的测试中设置查询参数?
答案 0 :(得分:8)
似乎在测试之外,Search
组件正确接收match
道具
您可以在测试中浅层渲染时将其作为道具传递:
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);
});
在这种情况下,你不会以一种糟糕的方式更改被测试的组件,你的测试用例只是发现了一个bug,这是好的,应该针对测试,你通过实现默认道具来改进组件,使它更健壮。
答案 1 :(得分:0)
我也遇到了同样的问题,当您通过浅层或安装方法传递组件时,通过在组件中添加匹配道具来解决。这是代码:
test("Add param in component", () => {
const match = {params : { id: 1 } };
const component = shallow(<YourComponent match={match} />);
expect(/*Write your code here */);
});
如您所见,我的ID为id,请替换为您的ID。