mirror of
https://github.com/callstack/react-native-testing-library.git
synced 2026-09-18 23:09:04 +08:00
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:
@@ -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
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user