Skip to content

Commit 83a5bc0

Browse files
authored
doc: Nestで循環依存がある場合のCONTRIBUTING.mdに書く (#13522)
* doc: Nestモジュールテストの例をCONTRIBUTING.mdに書く * rm normal test * forwardRef
1 parent 13f5faf commit 83a5bc0

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

CONTRIBUTING.md

+92
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,98 @@ export const handlers = [
316316

317317
Don't forget to re-run the `.storybook/generate.js` script after adding, editing, or removing the above files.
318318

319+
## Nest
320+
321+
### Nest Service Circular dependency / Nestでサービスの循環参照でエラーが起きた場合
322+
323+
#### forwardRef
324+
まずは簡単に`forwardRef`を試してみる
325+
326+
```typescript
327+
export class FooService {
328+
constructor(
329+
@Inject(forwardRef(() => BarService))
330+
private barService: BarService
331+
) {
332+
}
333+
}
334+
```
335+
336+
#### OnModuleInit
337+
できなければ`OnModuleInit`を使う
338+
339+
```typescript
340+
import { Injectable, OnModuleInit } from '@nestjs/common';
341+
import { ModuleRef } from '@nestjs/core';
342+
import { BarService } from '@/core/BarService';
343+
344+
@Injectable()
345+
export class FooService implements OnModuleInit {
346+
private barService: BarService // constructorから移動してくる
347+
348+
constructor(
349+
private moduleRef: ModuleRef,
350+
) {
351+
}
352+
353+
async onModuleInit() {
354+
this.barService = this.moduleRef.get(BarService.name);
355+
}
356+
357+
public async niceMethod() {
358+
return await this.barService.incredibleMethod({ hoge: 'fuga' });
359+
}
360+
}
361+
```
362+
363+
##### Service Unit Test
364+
テストで`onModuleInit`を呼び出す必要がある
365+
366+
```typescript
367+
// import ...
368+
369+
describe('test', () => {
370+
let app: TestingModule;
371+
let fooService: FooService; // for test case
372+
let barService: BarService; // for test case
373+
374+
beforeEach(async () => {
375+
app = await Test.createTestingModule({
376+
imports: ...,
377+
providers: [
378+
FooService,
379+
{ // mockする (mockは必須ではないかもしれない)
380+
provide: BarService,
381+
useFactory: () => ({
382+
incredibleMethod: jest.fn(),
383+
}),
384+
},
385+
{ // Provideにする
386+
provide: BarService.name,
387+
useExisting: BarService,
388+
},
389+
],
390+
})
391+
.useMocker(...
392+
.compile();
393+
394+
fooService = app.get<FooService>(FooService);
395+
barService = app.get<BarService>(BarService) as jest.Mocked<BarService>;
396+
397+
// onModuleInitを実行する
398+
await fooService.onModuleInit();
399+
});
400+
401+
test('nice', () => {
402+
await fooService.niceMethod();
403+
404+
expect(barService.incredibleMethod).toHaveBeenCalled();
405+
expect(barService.incredibleMethod.mock.lastCall![0])
406+
.toEqual({ hoge: 'fuga' });
407+
});
408+
})
409+
```
410+
319411
## Notes
320412
321413
### Misskeyのドメイン固有の概念は`Mi`をprefixする

0 commit comments

Comments
 (0)