Jest provides a way to mock the features described in their docs
apiGetMethod = jest.fn().mockImplementation(
new Promise((resolve, reject) => {
const userID = parseInt(url.substr('/users/'.length), 10);
process.nextTick(
() => users[userID] ? resolve(users[userID]) : reject({
error: 'User with ' + userID + ' not found.',
});
);
});
);
However, this bullying seems to work only when the function is called directly in the test.
describe('example test', () => {
it('uses the mocked function', () => {
apiGetMethod().then(...);
});
});
If I have a React component defined as such, how can I make fun of it?
import { apiGetMethod } from './api';
class Foo extends React.Component {
state = {
data: []
}
makeRequest = () => {
apiGetMethod().then(result => {
this.setState({data: result});
});
};
componentDidMount() {
this.makeRequest();
}
render() {
return (
<ul>
{ this.state.data.map((data) => <li>{data}</li>) }
</ul>
)
}
}
I have no idea how to do this, so the component Foocalls my mock implementation apiGetMethod()so that I can verify that it displays the data correctly.
(this is a simplified, far-fetched example for understanding how to simulate functions called inside react components)
edit: api.js file for clarity
import 'whatwg-fetch';
export function apiGetMethod() {
return fetch(url, {...});
}