Skip to content

Commit aedb208

Browse files
petersendiditljharb
authored andcommitted
[enzyme-adapter-react-16] [fix] mount: wrap simulate() in ReactTestUtils.act()
Wraps the mount simulate method in ReactTestUtils.act() to correctly allow component interactions to be tested in a synchronous way Fixes #2084
1 parent 78034b1 commit aedb208

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

packages/enzyme-adapter-react-16/src/ReactSixteenAdapter.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,9 @@ class ReactSixteenAdapter extends EnzymeAdapter {
474474
if (!eventFn) {
475475
throw new TypeError(`ReactWrapper::simulate() event '${event}' does not exist`);
476476
}
477-
eventFn(adapter.nodeToHostNode(node), mock);
477+
wrapAct(() => {
478+
eventFn(adapter.nodeToHostNode(node), mock);
479+
});
478480
},
479481
batchedUpdates(fn) {
480482
return fn();

packages/enzyme-test-suite/test/shared/methods/simulate.jsx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import {
1313

1414
import {
1515
memo,
16+
useEffect,
17+
useState,
1618
} from '../../_helpers/react-compat';
1719

1820
export default function describeSimulate({
@@ -316,5 +318,30 @@ export default function describeSimulate({
316318
expect(handleClick).to.have.property('callCount', 3);
317319
});
318320
});
321+
322+
describeIf(is('>= 16.8'), 'hooks', () => {
323+
// TODO: fix for shallow when useEffect works for shallow
324+
itIf(!isShallow, 'works with `useEffect` simulated events', () => {
325+
const effectSpy = sinon.spy();
326+
function ComponentUsingEffectHook() {
327+
useEffect(effectSpy);
328+
const [counter, setCounter] = useState(0);
329+
330+
return (
331+
<button type="button" onClick={() => setCounter(counter + 1)}>{counter}</button>
332+
);
333+
}
334+
const wrapper = Wrap(<ComponentUsingEffectHook />);
335+
336+
const button = wrapper.find('button');
337+
expect(button.text()).to.equal('0');
338+
expect(effectSpy).to.have.property('callCount', 1);
339+
340+
button.simulate('click');
341+
342+
expect(button.text()).to.equal('1');
343+
expect(effectSpy).to.have.property('callCount', 2);
344+
});
345+
});
319346
});
320347
}

0 commit comments

Comments
 (0)