Open IanVS opened 6 years ago
Sounds like you're doing integration tests. I prefer to use react-testing-library and use wait. I haven't used enzyme before so i'm not sure it has it, but it probably should since it's an extensive library. Then you can wait for something to happen within your component as opposed to attaching a then to your fetch
let's say you have a fetch in componentDidMount
, the following pattern below allows you to assert after the fetch has been called.
it("test a fetch failure", async () => {
fetch.mockReject(new Error("error message"));
const didMountSpy = jest.spyOn(YourComponent.prototype, "componentDidMount");
const wrapper = shallow(<YourComponent />);
// any assertions here can not guarantee that componentDidMount finishes
expect(wrapper.find("Waiting")).toHaveLength(1);
// ensure componentDidMount returns
await didMountSpy.mock.results[0].value;
// add your assertions for the state of your component after the rejections
expect(wrapper.find("Error")).toHaveLength(1);
} );
if you are calling fetch in another method of your component, attach a spy to that method and call await on it. i think this will get you what you are looking for.
Hi, I'm having trouble finding a way to make assertions after the
fetch
resolves. My case is that I have a component which makes afetch
when a button is clicked, and I am using enzyme to simulate a click on that button. I want to make an assertion about the state of the component after thefetch
resolves/rejects, but I can't figure out how to attach athen
onto the mocked fetch itself. Any suggestions? Does that make sense?Basically, I'm trying to do something like https://github.com/airbnb/enzyme/issues/346#issuecomment-304535773 with this package instead of sinon.