I'm working with create-react-app, jest and enzyme.
I have a class component that loads "detail" data when a table row is clicked, then displays a form in a modal where the details can be edited and saved:
import React, { Component } from "react";
import fetch from "isomorphic-fetch";
import Modal from "./Modal";
export default class RecordViewer extends Component {
constructor(props) {
super(props);
this.state = {
showModal: false,
currentRecord: {}
};
}
open(id) {
fetch(`api/${id}`)
.then(res => res.json())
.then(data => {
this.setState({
...this.state,
currentRecord: data.record,
showModal: true
});
});
}
render() {
<div>
<Modal visible={this.state.showModal} contents={this.state.currentRecord} />
<table>
<tr onClick={()=>this.open(1)}>
<td>Record Overview for Item 1</td>
</tr>
</table>
</div>
}
}
I want to mock the fetch function to determine if it is called or not, but also just to keep the component from trying to hit the API. I want to test the contents passed to the modal, for example.
Passing fetch in as a prop would make this easy but then this component's parent would need to know about it, which doesn't seem to make sense.
Is there a way to mock fetch with this set up?
Perhaps there is a better way to go about testing this altogether?