-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
useEffect.test.js
84 lines (65 loc) · 2.07 KB
/
useEffect.test.js
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
import { act } from 'preact/test-utils';
import { createElement as h, render } from 'preact';
import { setupScratch, teardown } from '../../../test/_util/helpers';
import { useEffect } from '../../src';
import { useEffectAssertions } from './useEffectAssertions.test';
import { scheduleEffectAssert } from '../_util/useEffectUtil';
/** @jsx h */
describe('useEffect', () => {
/** @type {HTMLDivElement} */
let scratch;
beforeEach(() => {
scratch = setupScratch();
});
afterEach(() => {
teardown(scratch);
});
useEffectAssertions(useEffect, scheduleEffectAssert);
it('calls the effect immediately if another render is about to start', () => {
const cleanupFunction = sinon.spy();
const callback = sinon.spy(() => cleanupFunction);
function Comp() {
useEffect(callback);
return null;
}
render(<Comp />, scratch);
render(<Comp />, scratch);
expect(cleanupFunction).to.be.not.called;
expect(callback).to.be.calledOnce;
render(<Comp />, scratch);
expect(cleanupFunction).to.be.calledOnce;
expect(callback).to.be.calledTwice;
});
it('cancels the effect when the component get unmounted before it had the chance to run it', () => {
const cleanupFunction = sinon.spy();
const callback = sinon.spy(() => cleanupFunction);
function Comp() {
useEffect(callback);
return null;
}
render(<Comp />, scratch);
render(null, scratch);
return scheduleEffectAssert(() => {
expect(cleanupFunction).to.not.be.called;
expect(callback).to.not.be.called;
});
});
it('Should execute effects in the right order', () => {
let executionOrder = [];
const App = ({ i }) => {
executionOrder = [];
useEffect(() => {
executionOrder.push('action1');
return () => executionOrder.push('cleanup1');
}, [i]);
useEffect(() => {
executionOrder.push('action2');
return () => executionOrder.push('cleanup2');
}, [i]);
return <p>Test</p>;
};
act(() => render(<App i={0} />, scratch));
act(() => render(<App i={2} />, scratch));
expect(executionOrder).to.deep.equal(['cleanup1', 'cleanup2', 'action1', 'action2']);
});
});