Add test for async event dispatching (#15300)
Verified that a variant of this test fails as follows when the `context.withAsyncDispatching` function is excluded (i.e., reproduces the issue). Expected value to equal: ["press", "longpress", "longpresschange"] Received: ["press", "longpress", "longpress", "longpresschange"]
Nicolas Gallagher committed
Apr 3, 2019 at 02:43 UTC
fc6a9f1a1ebb5585c543126d397cc945a95f3196
1 file changed
+63
packages/react-dom/src/events/__tests__/DOMEventResponderSystem-test.internal.js
+63
@@ -256,4 +256,67 @@ describe('DOMEventResponderSystem', () => {
256
257
expect(eventLog).toEqual(['magic event fired', 'magicclick']);
258
});
259
+
260
+ it('async event dispatching works', () => {
261
+ let eventLog = [];
262
+ const buttonRef = React.createRef();
263
+
264
+ const LongPressEventComponent = createReactEventComponent(
265
+ ['click'],
266
+ (context, props) => {
267
+ const pressEvent = {
268
+ listener: props.onPress,
269
+ target: context.eventTarget,
270
+ type: 'press',
271
+ };
272
+ context.dispatchEvent(pressEvent, {discrete: true});
273
+
274
+ setTimeout(
275
+ () =>
276
+ context.withAsyncDispatching(() => {
277
+ if (props.onLongPress) {
278
+ const longPressEvent = {
279
+ listener: props.onLongPress,
280
+ target: context.eventTarget,
281
+ type: 'longpress',
282
+ };
283
+ context.dispatchEvent(longPressEvent, {discrete: true});
284
+ }
285
+
286
+ if (props.onLongPressChange) {
287
+ const longPressChangeEvent = {
288
+ listener: props.onLongPressChange,
289
+ target: context.eventTarget,
290
+ type: 'longpresschange',
291
+ };
292
+ context.dispatchEvent(longPressChangeEvent, {discrete: true});
293
+ }
294
+ }),
295
+ 500,
296
+ );
297
+ },
298
+ );
299
+
300
+ function log(msg) {
301
+ eventLog.push(msg);
302
+ }
303
+
304
+ const Test = () => (
305
+ <LongPressEventComponent
306
+ onPress={() => log('press')}
307
+ onLongPress={() => log('longpress')}
308
+ onLongPressChange={() => log('longpresschange')}>
309
+ <button ref={buttonRef}>Click me!</button>
310
+ </LongPressEventComponent>
311
+ );
312
+
313
+ ReactDOM.render(<Test />, container);
314
+
315
+ // Clicking the button should trigger the event responder handleEvent()
316
+ let buttonElement = buttonRef.current;
317
+ dispatchClickEvent(buttonElement);
318
+ jest.runAllTimers();
319
+
320
+ expect(eventLog).toEqual(['press', 'longpress', 'longpresschange']);
321
+ });
322
});