我有一个React组件:
export default class ItemDetails extends React.Component<Props & RouteComponentProps<{ id: string}>, State> {
public constructor(props: Props & RouteComponentProps<{ id: string}>) {
super(props);
this.state = {
item: {
id: 0,
price: '$0.00'
}
};
}
public async componentWillMount() {
let item = await ItemService.fetch(Number(this.props.match.params.id));
this.setState({item: item});
};
public render() {
let {item} = this.state;
return (
<div className="itemDetails">
<itemDetailsHeader item={item}/>
<itemDetailsBody item={item}/>
</div>
)
}
}
,并且正在尝试测试该组件,以便在该组件呈现时在基础组件中显示来自服务调用的数据。
我的测试抛出一个错误,指出为Cannot read property 'params' of undefined
。这是在this.props.match.params.id
参数上。我的测试如下所示:
let mock: any = jest.fn();
var match: {
isExact: true,
params: { id: '1' },
path: "",
url: ""
}
jest.mock('../../../src/actions/apiHelper', () => {
return {
getItem: () => new Promise(resolve => resolve(
{id: 1, price: '$9.99'}
))
};
});
describe("Item Details", () => {
describe("Header", () => {
it('should display the price of the item', () => {
const wrapper = mount(<ItemDetails match={match} location={mock} history={mock}/>);
expect(wrapper.find(".itemDetails--price").text()).toEqual("$9.99");
});
})
});
如何在测试中设置我的ItemDetails组件,并为RouteComponentProps设置适当的参数,以允许对fetch调用进行存根处理,而不会收到我目前收到的关于未定义的props的错误?