Improvement: Add act to update call to support hooks (#137)

### Summary
Currently `render` and `fireEvent` are wrapped in `act` to support hooks. This pull request wraps the update call in `act` to support testing component updates (e.g. prop changes).

### Test plan
* I have added a test for update in `__tests__/act.test.js`.
* A useEffect hook should run again on `update` calls (if the hook dependency array is satisfied).
This commit is contained in:
Brad
2019-03-25 10:22:34 -04:00
committed by Kacper Wiszczuk
parent ccad8044ea
commit f96d782d26
3 changed files with 18 additions and 2 deletions
+8
View File
@@ -28,6 +28,14 @@ test('render should trigger useEffect', () => {
expect(effectCallback).toHaveBeenCalledTimes(1);
});
test('update should trigger useEffect', () => {
const effectCallback = jest.fn();
const { update } = render(<UseEffect callback={effectCallback} />);
update(<UseEffect callback={effectCallback} />);
expect(effectCallback).toHaveBeenCalledTimes(2);
});
test('fireEvent should trigger useState', () => {
const { getByTestId } = render(<Counter />);
const counter = getByTestId('counter');
+9 -1
View File
@@ -26,7 +26,7 @@ export default function render(
return {
...getByAPI(instance),
...queryByAPI(instance),
update: renderer.update,
update: updateWithAct(renderer),
unmount: renderer.unmount,
toJSON: renderer.toJSON,
debug: debug(instance, renderer),
@@ -46,6 +46,14 @@ function renderWithAct(
return ((renderer: any): ReactTestRenderer);
}
function updateWithAct(renderer: ReactTestRenderer) {
return function(component: React.Element<any>) {
act(() => {
renderer.update(component);
});
};
}
function debug(instance: ReactTestInstance, renderer) {
function debugImpl(message?: string) {
return debugDeep(renderer.toJSON(), message);