Two Horses
Two Horses

Reputation: 1702

NestJs failes to compile testing module when running tests with Jest

I have a CategoryService that is a provider of CategoriesModule:

@Module({
    imports: [
        MongooseModule.forFeatureAsync([
            {
                name: Category.name,
                imports: [EventEmitterModule],
                inject: [EventEmitter2],
                useFactory: (eventEmitter: EventEmitter2) => {
                    const schema = CategorySchema
                    schema.post('findOneAndDelete', (category: CategoryDocument) => eventEmitter.emit(CollectionEvents.CategoriesDeleted, [category]))
                    return schema
                }
            }
        ])
    ],
  providers: [CategoriesService]
})
export class CategoriesModule {
}

My CategoriesService is:

@Injectable()
export class CategoriesService {
    constructor(@InjectModel(Category.name) private categoryModel: Model<CategoryDocument>) {
    }

    ...
}

Then I have a jest test file of that service categories.service.spec.ts:

describe('CategoriesService', () => {
    let service: CategoriesService

    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            providers: [CategoriesService]
        }).compile()

        service = module.get<CategoriesService>(CategoriesService)
    })

    it('should be defined', () => {
        expect(service).toBeDefined()
    })
})

But when i run the test (using nestJs built in script test) if failes with this error:

Nest can't resolve dependencies of the CategoriesService (?). Please make sure that the argument CategoryModel at index [0] is available in the RootTestModule context.

    Potential solutions:
    - If CategoryModel is a provider, is it part of the current RootTestModule?
    - If CategoryModel is exported from a separate @Module, is that module imported within RootTestModule?
      @Module({
        imports: [ /* the Module containing CategoryModel */ ]
      })

But I don't get it, when running the server using npm start it all runs ok, and here it complains about CategoryModel, why?

Upvotes: 1

Views: 1204

Answers (1)

harshil1507
harshil1507

Reputation: 79

Category model is used in CategoryService and hence is a dependency for CategoryService. You will need to add the model to your spec file so that the dependency is resolved. If you are using mongoose look at this answer it will help you.

Upvotes: 2

Related Questions