forked from Kukkimonsuta/inversify-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhooks.tsx
296 lines (247 loc) · 8.99 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
import 'reflect-metadata';
import { Container, injectable, interfaces, unmanaged } from 'inversify';
import * as React from 'react';
import { useState } from 'react';
import * as renderer from 'react-test-renderer';
import { assert, IsExact } from 'conditional-type-checks';
import * as hooksModule from '../src/hooks'; // for jest.spyOn
import {
Provider,
useAllInjections,
useContainer,
useInjection,
useOptionalInjection,
} 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 aTag = 'a-tag';
const bTag = 'b-tag';
const multiId = Symbol('multi-id');
class OptionalService {
readonly label = 'OptionalService' as const;
}
const RootComponent: React.FC = ({ children }) => {
const [container] = useState(() => {
const c = new Container();
c.bind(Foo).toSelf();
c.bind(Bar).toDynamicValue(() => new Bar('a')).whenTargetNamed(aTag);
c.bind(Bar).toDynamicValue(() => new Bar('a')).whenTargetTagged(aTag, 'a');
c.bind(Bar).toDynamicValue(() => new Bar('b')).whenTargetNamed(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: any = renderer.create(
<Provider container={container}>
<ChildComponent/>
</Provider>
).toJSON();
expect(hookSpy).toHaveBeenCalledTimes(1);
expect(hookSpy).lastReturnedWith(container);
expect(tree.type).toBe('div');
expect(tree.children[0]).toEqual(`${container.id}`);
});
test('throws when no context found (missing Provider)', () => {
expect(() => {
renderer.create(<ChildComponent/>)
}).toThrowError('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: any = renderer.create(
<RootComponent>
<ChildComponent />
</RootComponent>
).toJSON();
expect(tree.type).toBe('div');
expect(tree.children[0].type).toBe('div');
expect(tree.children[0].children).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: any = renderer.create(
<Provider container={container}>
<ChildComponent/>
</Provider>
).toJSON();
expect(tree.type).toBe('div');
expect(tree.children).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: any = renderer.create(
<Provider container={container}>
<ChildComponent/>
</Provider>
).toJSON();
expect(tree.type).toBe('div');
expect(tree.children).toEqual(['foo']);
});
});
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: any = renderer.create(
<RootComponent>
<ChildComponent/>
</RootComponent>
).toJSON();
expect(hookSpy).toHaveBeenCalledTimes(1);
expect(hookSpy).toHaveReturnedWith(undefined);
expect(tree.children).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: any = renderer.create(
<RootComponent>
<ChildComponent/>
</RootComponent>
).toJSON();
expect(hookSpy).toHaveBeenCalledTimes(1);
expect(hookSpy).toHaveReturnedWith(defaultThing);
expect(tree.children).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: any = renderer.create(
<RootComponent>
<ChildComponent/>
</RootComponent>
).toJSON();
expect(hookSpy).toHaveBeenCalledTimes(1);
expect(tree.children).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: any = renderer.create(
<RootComponent>
<ChildComponent/>
</RootComponent>
).toJSON();
expect(hookSpy).toHaveBeenCalledTimes(1);
expect(tree.children).toEqual(['x,y,z']);
});
});