vendredi 15 février 2019

Waiting for two separate promises to resolve so state is updated

So I'm testing a react component button click that changes a state. When rendering the component I need a promise to resolve so the button is rendered and thus clickable. I accomplish this by placing the button click inside of a setTimeout as the component states get updated. However after clicking the button a component state needs to be updated due to a promise being resolved. I'll give an example below

class App extends component {
     constructor(props){
     this.state ={
         hasError = false;
         loading = true;
 }

funcWithAPIcallForButtonRender{
  .
  .
  .
}

someFunc{
   this.middleWareCalltoAPI.then{
      this.state.hasError = false;
   }
}

Now here is what my test looks like

test("Save user permissions", done => {
  mock.onGet("anAPI.php").reply(200, mockData); //THIS IS NEEDED TO RENDER THE BUTTON
  const wrapper = shallow(<App />);

  setTimeout(() => {
    wrapper.find("Button").simulate("click"); //THIS CLICK SHOULD CHANGE hasError to true
    expect(wrapper.state.hasError).toEqual(true) //THIS FAILS
    done();
  }, 0);
});

I've tried nesting setTimeouts so the promise from the click can resolve but that doesn't seem to work. I tried to pare down my code as much as possible so it's readable. Let me know if you need me to provide more context.

Aucun commentaire:

Enregistrer un commentaire