summaryrefslogtreecommitdiff
path: root/preact/test-utils/test/shared/act.test.js
blob: 7769b5b6257ba8526f84dd0bbca7d964ef308247 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
import { options, createElement, render } from 'preact';
import { useEffect, useReducer, useState } from 'preact/hooks';
import { act } from 'preact/test-utils';
import { setupScratch, teardown } from '../../../test/_util/helpers';

/** @jsx createElement */

// IE11 doesn't support `new Event()`
function createEvent(name) {
	if (typeof Event == 'function') return new Event(name);

	const event = document.createEvent('Event');
	event.initEvent(name, true, true);
	return event;
}

describe('act', () => {
	/** @type {HTMLDivElement} */
	let scratch;

	beforeEach(() => {
		scratch = setupScratch();
	});

	afterEach(() => {
		teardown(scratch);
		options.debounceRendering = undefined;
	});

	it('should reset options after act finishes', () => {
		expect(options.requestAnimationFrame).to.equal(undefined);
		act(() => null);
		expect(options.requestAnimationFrame).to.equal(undefined);
	});

	it('should flush pending effects', () => {
		let spy = sinon.spy();
		function StateContainer() {
			useEffect(spy);
			return <div />;
		}
		act(() => render(<StateContainer />, scratch));
		expect(spy).to.be.calledOnce;
	});

	it('should flush pending and initial effects', () => {
		const spy = sinon.spy();
		function StateContainer() {
			const [count, setCount] = useState(0);
			useEffect(() => spy(), [count]);
			return (
				<div>
					<p>Count: {count}</p>
					<button onClick={() => setCount(c => c + 11)} />
				</div>
			);
		}

		act(() => render(<StateContainer />, scratch));
		expect(spy).to.be.calledOnce;
		expect(scratch.textContent).to.include('Count: 0');
		act(() => {
			const button = scratch.querySelector('button');
			button.click();
			expect(spy).to.be.calledOnce;
			expect(scratch.textContent).to.include('Count: 0');
		});
		expect(spy).to.be.calledTwice;
		expect(scratch.textContent).to.include('Count: 1');
	});

	it('should flush series of hooks', () => {
		const spy = sinon.spy();
		const spy2 = sinon.spy();
		function StateContainer() {
			const [count, setCount] = useState(0);
			useEffect(() => {
				spy();
				if (count === 1) {
					setCount(() => 2);
				}
			}, [count]);
			useEffect(() => {
				if (count === 2) {
					spy2();
					setCount(() => 4);
					return () => setCount(() => 3);
				}
			}, [count]);
			return (
				<div>
					<p>Count: {count}</p>
					<button onClick={() => setCount(c => c + 1)} />
				</div>
			);
		}
		act(() => render(<StateContainer />, scratch));
		expect(spy).to.be.calledOnce;
		expect(scratch.textContent).to.include('Count: 0');
		act(() => {
			const button = scratch.querySelector('button');
			button.click();
		});
		expect(spy.callCount).to.equal(5);
		expect(spy2).to.be.calledOnce;
		expect(scratch.textContent).to.include('Count: 3');
	});

	it('should drain the queue of hooks', () => {
		const spy = sinon.spy();
		function StateContainer() {
			const [count, setCount] = useState(0);
			useEffect(() => spy());
			return (
				<div>
					<p>Count: {count}</p>
					<button onClick={() => setCount(c => c + 11)} />
				</div>
			);
		}

		render(<StateContainer />, scratch);
		expect(scratch.textContent).to.include('Count: 0');
		act(() => {
			const button = scratch.querySelector('button');
			button.click();
			expect(scratch.textContent).to.include('Count: 0');
		});
		expect(scratch.textContent).to.include('Count: 1');
	});

	it('should restore options.requestAnimationFrame', () => {
		const spy = sinon.spy();

		options.requestAnimationFrame = spy;
		act(() => null);

		expect(options.requestAnimationFrame).to.equal(spy);
		expect(spy).to.not.be.called;
	});

	it('should restore options.debounceRendering', () => {
		const spy = sinon.spy();

		options.debounceRendering = spy;
		act(() => null);

		expect(options.debounceRendering).to.equal(spy);
		expect(spy).to.not.be.called;
	});

	it('should restore options.debounceRendering when it was undefined before', () => {
		act(() => null);
		expect(options.debounceRendering).to.equal(undefined);
	});

	it('should flush state updates if there are pending state updates before `act` call', () => {
		function CounterButton() {
			const [count, setCount] = useState(0);
			const increment = () => setCount(count => count + 1);
			return <button onClick={increment}>{count}</button>;
		}

		render(<CounterButton />, scratch);
		const button = scratch.querySelector('button');

		// Click button. This will schedule an update which is deferred, as is
		// normal for Preact, since it happens outside an `act` call.
		button.dispatchEvent(createEvent('click'));

		expect(button.textContent).to.equal('0');

		act(() => {
			// Click button a second time. This will schedule a second update.
			button.dispatchEvent(createEvent('click'));
		});
		// All state updates should be applied synchronously after the `act`
		// callback has run but before `act` returns.
		expect(button.textContent).to.equal('2');
	});

	it('should flush effects if there are pending effects before `act` call', () => {
		function Counter() {
			const [count, setCount] = useState(0);
			useEffect(() => {
				setCount(count => count + 1);
			}, []);
			return <div>{count}</div>;
		}

		// Render a component which schedules an effect outside of an `act`
		// call. This will be scheduled to execute after the next paint as usual.
		render(<Counter />, scratch);
		expect(scratch.firstChild.textContent).to.equal('0');

		// Render a component inside an `act` call, this effect should be
		// executed synchronously before `act` returns.
		act(() => {
			render(<div />, scratch);
			render(<Counter />, scratch);
		});
		expect(scratch.firstChild.textContent).to.equal('1');
	});

	it('returns a Promise if invoked with a sync callback', () => {
		const result = act(() => {});
		expect(result.then).to.be.a('function');
		return result;
	});

	it('returns a Promise if invoked with an async callback', () => {
		const result = act(async () => {});
		expect(result.then).to.be.a('function');
		return result;
	});

	it('should await "thenable" result of callback before flushing', async () => {
		const events = [];

		function TestComponent() {
			useEffect(() => {
				events.push('flushed effect');
			}, []);
			events.push('scheduled effect');
			return <div>Test</div>;
		}

		const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

		events.push('began test');
		const acted = act(async () => {
			events.push('began act callback');
			await delay(1);
			render(<TestComponent />, scratch);
			events.push('end act callback');
		});
		events.push('act returned');
		await acted;
		events.push('act result resolved');

		expect(events).to.deep.equal([
			'began test',
			'began act callback',
			'act returned',
			'scheduled effect',
			'end act callback',
			'flushed effect',
			'act result resolved'
		]);
	});

	context('when `act` calls are nested', () => {
		it('should invoke nested sync callback and return a Promise', () => {
			let innerResult;
			const spy = sinon.stub();

			act(() => {
				innerResult = act(spy);
			});

			expect(spy).to.be.calledOnce;
			expect(innerResult.then).to.be.a('function');
		});

		it('should invoke nested async callback and return a Promise', async () => {
			const events = [];

			await act(async () => {
				events.push('began outer act callback');
				await act(async () => {
					events.push('began inner act callback');
					await Promise.resolve();
					events.push('end inner act callback');
				});
				events.push('end outer act callback');
			});
			events.push('act finished');

			expect(events).to.deep.equal([
				'began outer act callback',
				'began inner act callback',
				'end inner act callback',
				'end outer act callback',
				'act finished'
			]);
		});

		it('should only flush effects when outer `act` call returns', () => {
			let counter = 0;

			function Widget() {
				useEffect(() => {
					++counter;
				});
				const [, forceUpdate] = useReducer(x => x + 1, 0);
				return <button onClick={forceUpdate}>test</button>;
			}

			act(() => {
				render(<Widget />, scratch);
				const button = scratch.querySelector('button');
				expect(counter).to.equal(0);

				act(() => {
					button.dispatchEvent(createEvent('click'));
				});

				// Effect triggered by inner `act` call should not have been
				// flushed yet.
				expect(counter).to.equal(0);
			});

			// Effects triggered by inner `act` call should now have been
			// flushed.
			expect(counter).to.equal(2);
		});

		it('should only flush updates when outer `act` call returns', () => {
			function Button() {
				const [count, setCount] = useState(0);
				const increment = () => setCount(count => count + 1);
				return <button onClick={increment}>{count}</button>;
			}

			render(<Button />, scratch);
			const button = scratch.querySelector('button');
			expect(button.textContent).to.equal('0');

			act(() => {
				act(() => {
					button.dispatchEvent(createEvent('click'));
				});

				// Update triggered by inner `act` call should not have been
				// flushed yet.
				expect(button.textContent).to.equal('0');
			});

			// Updates from outer and inner `act` calls should now have been
			// flushed.
			expect(button.textContent).to.equal('1');
		});
	});

	describe('when `act` callback throws an exception', () => {
		function BrokenWidget() {
			throw new Error('BrokenWidget is broken');
		}

		let effectCount;

		function WorkingWidget() {
			const [count, setCount] = useState(0);

			useEffect(() => {
				++effectCount;
			}, []);

			if (count === 0) {
				setCount(1);
			}

			return <div>{count}</div>;
		}

		beforeEach(() => {
			effectCount = 0;
		});

		const renderBroken = () => {
			act(() => {
				render(<BrokenWidget />, scratch);
			});
		};

		const renderWorking = () => {
			act(() => {
				render(<WorkingWidget />, scratch);
			});
		};

		const tryRenderBroken = () => {
			try {
				renderBroken();
			} catch (e) {}
		};

		describe('synchronously', () => {
			it('should rethrow the exception', () => {
				expect(renderBroken).to.throw('BrokenWidget is broken');
			});

			it('should not affect state updates in future renders', () => {
				tryRenderBroken();
				renderWorking();
				expect(scratch.textContent).to.equal('1');
			});

			it('should not affect effects in future renders', () => {
				tryRenderBroken();
				renderWorking();
				expect(effectCount).to.equal(1);
			});
		});

		describe('asynchronously', () => {
			const renderBrokenAsync = async () => {
				await act(async () => {
					render(<BrokenWidget />, scratch);
				});
			};

			it('should rethrow the exception', async () => {
				let err;
				try {
					await renderBrokenAsync();
				} catch (e) {
					err = e;
				}
				expect(err.message).to.equal('BrokenWidget is broken');
			});

			it('should not affect state updates in future renders', async () => {
				try {
					await renderBrokenAsync();
				} catch (e) {}

				renderWorking();
				expect(scratch.textContent).to.equal('1');
			});

			it('should not affect effects in future renders', async () => {
				try {
					await renderBrokenAsync();
				} catch (e) {}

				renderWorking();
				expect(effectCount).to.equal(1);
			});
		});

		describe('in an effect', () => {
			function BrokenEffect() {
				useEffect(() => {
					throw new Error('BrokenEffect effect');
				}, []);
				return null;
			}

			const renderBrokenEffect = () => {
				act(() => {
					render(<BrokenEffect />, scratch);
				});
			};

			it('should rethrow the exception', () => {
				expect(renderBrokenEffect).to.throw('BrokenEffect effect');
			});

			it('should not affect state updates in future renders', () => {
				try {
					renderBrokenEffect();
				} catch (e) {}

				renderWorking();
				expect(scratch.textContent).to.equal('1');
			});

			it('should not affect effects in future renders', () => {
				try {
					renderBrokenEffect();
				} catch (e) {}

				renderWorking();
				expect(effectCount).to.equal(1);
			});
		});
	});
});