react-hooks-testing-library icon indicating copy to clipboard operation
react-hooks-testing-library copied to clipboard

await act makes test fail

Open mayacode opened this issue 7 years ago • 1 comments

  • react-hooks-testing-library version: 0.5.1
  • react-test-renderer version: 16.9.0
  • react version: 16.9.0
  • node version: 12.2.0
  • npm (or yarn) version: 6.9.0

Relevant code or config:

hooks.js

const initialState = {
  requesting: false,
};

export function reducer(state, action = {}) {
  switch (action.type) {
    case DATA_PATCH_REQUEST:
      return { ...initialState, requesting: true };
    default:
      return state;
  }
}

const requestAction = { type: DATA_PATCH_REQUEST };

function useManageDataUpdate() {
  const [state, dispatch] = useReducer(reducer, initialState);
  
  function dataChangeHandler(newValue) {
    patchChanges(newValue);
  }

  function patchChanges(value) {
    dispatch(requestAction);
    // request 
  }

  return { state, dataChangeHandler };
}

hooks.test.js

it('should change requesting to true when dataChangeHandle is called', () => {
  const { result } = renderHook(() => useManageDataUpdate());

  expect(result.current.state.requesting).toEqual(false);

  act(() => {
    result.current.dataChangeHandler('abc');
  });

  expect(result.current.state.requesting).toEqual(true);
});

What you did:

  • updated react to 16.9 changed act() to await act()

ran the test

What happened:

expect(received).toEqual(expected) // deep equality

Expected: true
Received: false

  78 | 
  79 |         console.log('end');
> 80 |         expect(result.current.state.requesting).toEqual(true);
     |                                                 ^
  81 |       });
  82 |     });
  83 |   });

Reproduction:

Problem description:

After updating the react, react-dom and react-test-renderer to 16.9.0 and changed act() which with any async code was producing nasty warning to await act() tests are no more passing. The state which should change stays the same

Suggested solution:

mayacode avatar Aug 09 '19 14:08 mayacode

ok, sorry my bad. Was expecting that tests will work the same :D

mayacode avatar Aug 10 '19 09:08 mayacode