unit test 작성 시 아래와 같은 버그가 발생.
Nest cannot create the GModule instance.
The module at index [2] of the GModule "imports" array is undefined.
Potential causes:
- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency
- The module at index [2] is of type "undefined". Check your import statements and the type of the module.
Scope [RootTestModule -> AModule -> -> AModule -> BModule -> AModule -> CModule -> AdminsModule -> BModule -> DModule -> CModule -> EModule -> BModule -> FModule]
현상: HModule의 unit test에서 해당 모듈에서는 사용하지 않는 GModule의 initialize가 실패함.
원인: HModule을 initialize 하기 위해 해당 module에서 import되는 module들을 initalize하는 체인을 따라가다가 GModule까지 가버림. 일종의 다중 circular dependency 같은 현상으로 추정.
*실제 앱 실행에는 영향을 끼치지 않고 createTestingModule
을 통해 module을 initialize 하는 과정에서 발생하는 현상.
해결 방법: unit test에서 module 대신 service만 테스트 하고 테스트 하려는 service에 주입되는 service들은 mocking.
const module = await TestUtils.createTestingModule({
imports: [],//기존에는 여기에 필요한 provider들을 가지고 있는 module을 import했지만 앞으로는 하지 않음.
providers: [
HService,// 실제 테스트 해야하는 Service.
//이 아래는 HService를 instant하는데 필요한 mock provider(service)
{
provide: AService,//기존에는 AService를 포함하는 AModule을 import 했었음. 이제는 Aservice만 mocking해서 주입.
useValue: {},
},
],
}).compile();
결론: test 대상을 제외한 모든 provider(service)들을 mocking 하기 때문에 위와 같은 현상을 방지할 수 있다.
다만 provider(service)를 모든 개별 test case에 맞게 mocking할 수 없기 때문에 case에 맞게 jest.spyOn으로 override 해야할 수 있다.