#Not Able to Resolve Mock Model while writting test cases

6 messages · Page 1 of 1 (latest)

still cloak
#

Here' my user.service.spec.ts

const userModelMock = {
  create: jest.fn(),
};

const newOrgMock = {
  _id: 'org1',
  orgName: 'testorg',
  TFIF: 'tes1344432',
};

const orgModelMock = {
  new: jest.fn(),
  save: jest.fn(),
  findById: jest.fn().mockResolvedValue(newOrgMock),
};

const fileModelMock = {
  new: jest.fn(),
  save: jest.fn(),
};

const newUserMock = {
  _id: '1',
  firstName: 'testuser',
  email: '[email protected]',
  title: 'Mr',
  lastName: 'testuser',
  language: 'en',
  phoneCode: '91',
  accountType: AccountType.COMPANY,
  mobileNumber: 1234567890,
  orgName: 'testorg',
  orgID: newOrgMock._id,
  save: jest.fn().mockResolvedValue(this),
};
#
describe('UsersService', () => {
  let userService: UserService;

  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [
        // TestDatabaseModule,
        MongooseModule.forFeature([
          { name: 'User', schema: UserSchema },
          { name: 'File', schema: FileSchema },
          { name: 'Org', schema: OrgSchema },
        ]),
        forwardRef(() => OrgModule),
        S3Module,
        WallexModule,
      ],
      providers: [
        UserService,
        {
          provide: getModelToken('User'),
          useValue: userModelMock,
        },
        {
          provide: getModelToken('Org'),
          useValue: orgModelMock,
        },
        {
          provide: getModelToken('File'),
          useValue: fileModelMock,
        },
        {
          provide: getConnectionToken(),
          useFactory: async (configService: ConfigService) => {
            const mongod = new MongoMemoryServer();
            const uri = await mongod.getUri();
            return {
              uri: uri,
            };
          },
          inject: [ConfigService],
        },
      ],
    }).compile();

    userService = moduleRef.get<UserService>(UserService);
    userModelMock.create.mockResolvedValue(newUserMock);
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should create a new user and return the created user', async () => {
    const createUserDto: CreateUserDto = {
      firstName: 'testuser',
      email: '[email protected]',
      title: 'Mr',
      lastName: 'testuser',
      language: 'en',
      phoneCode: '91',
      accountType: AccountType.COMPANY,
      mobileNumber: 1234567890,
      orgName: 'testorg',
    };

    const result = await userService.create(createUserDto);

    expect(userModelMock.create).toHaveBeenCalledWith(createUserDto);
    expect(result).toEqual(newUserMock);
  });
});
#

This is app.module.ts where I have defined MongooseModule

    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        uri: configService.get<string>('MONGODB_URI')
        useNewUrlParser: true,
      }),
      inject: [ConfigService],
    }),
#

The error I am encountering while running user.service.spec.ts

  throw new unknown_dependencies_exception_1.UnknownDependenciesException(wrapper.name, dependencyContext, moduleRef, { id: wrapper.id });
                  ^

UnknownDependenciesException [Error]: Nest can't resolve dependencies of the OrgModel (?). Please make sure that the argument DatabaseConnection at index [0] is available in the MongooseModule context.

Potential solutions:
- Is MongooseModule a valid NestJS module?
- If DatabaseConnection is a provider, is it part of the current MongooseModule?
- If DatabaseConnection is exported from a separate @Module, is that module imported within MongooseModule?
  @Module({
    imports: [ /* the Module containing DatabaseConnection */ ]
  })
    
 {
  type: 'OrgModel',
  context: {
    index: 0,
    dependencies: [ 'DatabaseConnection' ],
    name: 'DatabaseConnection'
  },
  metadata: { id: '1cee214b425a38512f1cf' },
  moduleRef: { id: 'baba1377f586e8e78f835' }
}
#

Can someone please guide me on how to mock db connection when,
using MongooseModule.forRoot | forRootAsync

still cloak
#

This is issue is resolved