I have the following context provider component (I am using the context api)
Example code:
export class AppProvider extends Component {
contructor (props) {
super(props);
}
fetchOrder () {
// http request
return Promise.all(promises).then(result => console.log(result));
}
updateOrder (id) {
// ...
this.fetchOrder(id).then(result => this.setState(result));
}
render () {
return (
<emailContext.Provider
value={{
state: this.state,
updateOrder: this.updateOrder
}}
>
{this.props.children}
</emailContext.Provider>
);
}
}
I am writing a test for updateOrder
but I need to mock the fetchOrder
http request being called by updateOrder
.
I thouht I could just mock it like so: jest.spyOn(AppProvider, 'fetchOrder').mockResolvedValue('fake value');
but this gives: Cannot spy the fetchOrder property because it is not a function; undefined given instead
Cannot spy the fetchOrder property because it is not a function; undefined given instead
I get the same if I put updateOrder
instead of fetchOrder
.
Why is this happening? And if this is not the way to do this, how will I intercept that request in my test?
the fetchOrder
is not a property on AppProvider
, but its a property ( a method property) on its instances. You have to mock the method on the instance, and while this is will work it is better to mock the endpoint itself using request interceptors. This will make you test the instance from the outside world without having to be completely coupled with its implementation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.