-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathhooks.tsx
368 lines (300 loc) · 11.2 KB
/
hooks.tsx
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
import 'reflect-metadata';
import { Container, injectable, interfaces, unmanaged } from 'inversify';
import * as React from 'react';
import { useState } from 'react';
import { assert, IsExact } from 'conditional-type-checks';
import { render } from '@testing-library/react';
import * as hooksModule from '../src/hooks'; // for jest.spyOn
import {
Provider,
useAllInjections,
useContainer,
useInjection,
useOptionalInjection,
useNamedInjection,
useTaggedInjection,
} from '../src';
// We want to test types around hooks with signature overloads (as it's more complex),
// but don't actually execute them,
// so we wrap test code into a dummy function just for TypeScript compiler
function staticTypecheckOnly(_fn: () => void) {
return () => {};
}
function throwErr(msg: string): never {
throw new Error(msg);
}
@injectable()
class Foo {
readonly name = 'foo';
}
@injectable()
class Bar {
readonly name: string;
constructor(@unmanaged() tag: string) {
this.name = 'bar-' + tag;
}
}
const aName = 'a-name';
const bName = 'b-name';
const rootTag = 'tag';
const aTag = 'a-tag';
const bTag = 'b-tag';
const multiId = Symbol('multi-id');
class OptionalService {
readonly label = 'OptionalService' as const;
}
interface RootComponentProps {
children?: React.ReactNode;
}
const RootComponent: React.FC<RootComponentProps> = ({ children }) => {
const [container] = useState(() => {
const c = new Container();
c.bind(Foo).toSelf();
c.bind(Bar).toDynamicValue(() => new Bar('aNamed')).whenTargetNamed(aName);
c.bind(Bar).toDynamicValue(() => new Bar('bNamed')).whenTargetNamed(bName);
c.bind(Bar).toDynamicValue(() => new Bar('aTagged')).whenTargetTagged(rootTag, aTag);
c.bind(Bar).toDynamicValue(() => new Bar('bTagged')).whenTargetTagged(rootTag, bTag);
c.bind(multiId).toConstantValue('x');
c.bind(multiId).toConstantValue('y');
c.bind(multiId).toConstantValue('z');
return c;
});
return (
<Provider container={container}>
<div>{children}</div>
</Provider>
);
};
describe('useContainer hook', () => {
const hookSpy = jest.spyOn(hooksModule, 'useContainer');
const ChildComponent = () => {
const resolvedContainer = useContainer();
return <div>{resolvedContainer.id}</div>;
};
afterEach(() => {
hookSpy.mockClear();
});
// hook with overloads, so we test types
test('types', staticTypecheckOnly(() => {
const container = useContainer();
assert<IsExact<typeof container, interfaces.Container>>(true);
const valueResolvedFromContainer = useContainer(c => {
assert<IsExact<typeof c, interfaces.Container>>(true);
return c.resolve(Foo);
});
assert<IsExact<typeof valueResolvedFromContainer, Foo>>(true);
}));
test('resolves container from context', () => {
const container = new Container();
const tree = render(
<Provider container={container}>
<ChildComponent/>
</Provider>
);
const fragment = tree.asFragment();
expect(hookSpy).toHaveBeenCalledTimes(1);
expect(hookSpy).toHaveLastReturnedWith(container);
expect(fragment.children[0].nodeName).toBe('DIV');
expect(fragment.children[0].textContent).toEqual(`${container.id}`);
});
test('throws when no context found (missing Provider)', () => {
expect(() => {
render(<ChildComponent/>);
}).toThrow('Cannot find Inversify container on React Context. `Provider` component is missing in component tree.');
// unfortunately currently it produces console.error, but it's only question of aesthetics
// @see https://github.com/facebook/react/issues/15520
expect(hookSpy).toHaveBeenCalled(); // looks like React v17 actually calls it 2 times, so we can't expect specific amount
expect(hookSpy).toHaveReturnedTimes(0);
});
});
describe('useInjection hook', () => {
test('resolves using service identifier (newable)', () => {
const ChildComponent = () => {
const foo = useInjection(Foo);
return <div>{foo.name}</div>;
};
const tree = render(
<RootComponent>
<ChildComponent />
</RootComponent>
);
const fragment = tree.asFragment();
expect(fragment.children[0].nodeName).toBe('DIV');
expect(fragment.children[0].children[0].nodeName).toBe('DIV');
expect(fragment.children[0].children[0].textContent).toEqual('foo');
});
test('resolves using service identifier (string)', () => {
const container = new Container();
container.bind('FooFoo').to(Foo);
const ChildComponent = () => {
const foo = useInjection<Foo>('FooFoo');
return <div>{foo.name}</div>;
};
const tree = render(
<Provider container={container}>
<ChildComponent/>
</Provider>
);
const fragment = tree.asFragment();
expect(fragment.children[0].nodeName).toBe('DIV');
expect(fragment.children[0].textContent).toEqual('foo');
});
test('resolves using service identifier (symbol)', () => {
// NB! declaring symbol as explicit ServiceIdentifier of specific type,
// which gives extra safety through type inference (both when binding and resolving)
const identifier = Symbol('Foo') as interfaces.ServiceIdentifier<Foo>;
const container = new Container();
container.bind(identifier).to(Foo);
const ChildComponent = () => {
const foo = useInjection(identifier);
return <div>{foo.name}</div>;
};
const tree = render(
<Provider container={container}>
<ChildComponent/>
</Provider>
);
const fragment = tree.asFragment();
expect(fragment.children[0].nodeName).toBe('DIV');
expect(fragment.children[0].textContent).toEqual('foo');
});
});
describe('useNamedInjection hook', () => {
test('resolves using service identifier and name constraint', () => {
const ChildComponent = () => {
const aBar = useNamedInjection(Bar, aName);
const bBar = useNamedInjection(Bar, bName);
return <div>{aBar.name},{bBar.name}</div>;
};
const tree = render(
<RootComponent>
<ChildComponent />
</RootComponent>
);
const fragment = tree.asFragment();
expect(fragment.children[0].nodeName).toBe('DIV');
expect(fragment.children[0].children[0].nodeName).toBe('DIV');
expect(fragment.children[0].children[0].textContent).toEqual("bar-aNamed,bar-bNamed");
});
});
describe('useTaggedInjection hook', () => {
test('resolves using service identifier and tag constraint', () => {
const ChildComponent = () => {
const aBar = useTaggedInjection(Bar, rootTag, aTag);
const bBar = useTaggedInjection(Bar, rootTag, bTag);
return <div>{aBar.name},{bBar.name}</div>;
};
const tree = render(
<RootComponent>
<ChildComponent />
</RootComponent>
);
const fragment = tree.asFragment();
expect(fragment.children[0].nodeName).toBe('DIV');
expect(fragment.children[0].children[0].nodeName).toBe('DIV');
expect(fragment.children[0].children[0].textContent).toEqual("bar-aTagged,bar-bTagged");
});
});
describe('useOptionalInjection hook', () => {
const hookSpy = jest.spyOn(hooksModule, 'useOptionalInjection');
afterEach(() => {
hookSpy.mockClear();
});
// hook with overloads, so we test types
test('types', staticTypecheckOnly(() => {
const opt = useOptionalInjection(Foo);
assert<IsExact<typeof opt, Foo | undefined>>(true);
const optWithDefault = useOptionalInjection(Foo, () => 'default' as const);
assert<IsExact<typeof optWithDefault, Foo | 'default'>>(true);
}));
test('returns undefined for missing injection/binding', () => {
const ChildComponent = () => {
const optionalThing = useOptionalInjection(OptionalService);
return (
<>
{optionalThing === undefined ? 'missing' : throwErr('unexpected')}
</>
);
};
const tree = render(
<RootComponent>
<ChildComponent/>
</RootComponent>
);
const fragment = tree.asFragment();
expect(hookSpy).toHaveBeenCalledTimes(1);
expect(hookSpy).toHaveReturnedWith(undefined);
expect(fragment.children[0].textContent).toEqual('missing');
});
test('resolves using fallback to default value', () => {
const defaultThing = {
label: 'myDefault',
isMyDefault: true,
} as const;
const ChildComponent = () => {
const defaultFromOptional = useOptionalInjection(OptionalService, () => defaultThing);
if (defaultFromOptional instanceof OptionalService) {
throwErr('unexpected');
} else {
assert<IsExact<typeof defaultFromOptional, typeof defaultThing>>(true);
expect(defaultFromOptional).toBe(defaultThing);
}
return (
<>
{defaultFromOptional.label}
</>
);
};
const tree = render(
<RootComponent>
<ChildComponent/>
</RootComponent>
);
const fragment = tree.asFragment();
expect(hookSpy).toHaveBeenCalledTimes(1);
expect(hookSpy).toHaveReturnedWith(defaultThing);
expect(fragment.children[0].textContent).toEqual(defaultThing.label);
});
test('resolves if injection/binding exists', () => {
const ChildComponent = () => {
const foo = useOptionalInjection(Foo);
return (
<>
{foo !== undefined ? foo.name : throwErr('Cannot resolve injection for Foo')}
</>
);
};
const tree = render(
<RootComponent>
<ChildComponent/>
</RootComponent>
);
const fragment = tree.asFragment();
expect(hookSpy).toHaveBeenCalledTimes(1);
expect(fragment.children[0].textContent).toEqual('foo');
});
});
describe('useAllInjections hook', () => {
const hookSpy = jest.spyOn(hooksModule, 'useAllInjections');
afterEach(() => {
hookSpy.mockClear();
});
test('resolves all injections', () => {
const ChildComponent = () => {
const stuff = useAllInjections(multiId);
return (
<>
{stuff.join(',')}
</>
);
};
const tree = render(
<RootComponent>
<ChildComponent/>
</RootComponent>
);
const fragment = tree.asFragment();
expect(hookSpy).toHaveBeenCalledTimes(1);
expect(fragment.children[0].textContent).toEqual('x,y,z');
});
});