Testing Service with Mongoose in NestJS

5.4k views Asked by At

I am trying to test my LoggingService in NestJS and while I cannot see anything that is wrong with the test the error I am getting is Error: Cannot spy the save property because it is not a function; undefined given instead

The function being tested (trimmed for brevity):

@Injectable()
export class LoggingService {
  constructor(
    @InjectModel(LOGGING_AUTH_MODEL) private readonly loggingAuthModel: Model<IOpenApiAuthLogDocument>,
    @InjectModel(LOGGING_EVENT_MODEL) private readonly loggingEventModel: Model<IOpenApiEventLogDocument>,
  ) {
  }
  
  async authLogging(req: Request, requestId: unknown, apiKey: string, statusCode: number, internalMsg: string) {
    
    const authLog: IOpenApiAuthLog = {
///
    }
    
    await new this.loggingAuthModel(authLog).save();
  }
}

This is pretty much my first NestJS test and as best I can tell this is the correct way to test it, considering the error is right at the end it seems about right.

describe('LoggingService', () => {
  let service: LoggingService;
  let mockLoggingAuthModel: IOpenApiAuthLogDocument;
  let request;
  
  beforeEach(async () => {
    request = new JestRequest();
    
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        LoggingService,
        {
          provide: getModelToken(LOGGING_AUTH_MODEL),
          useValue: MockLoggingAuthModel,
        },
        {
          provide: getModelToken(LOGGING_EVENT_MODEL),
          useValue: MockLoggingEventModel,
        },
      ],
    }).compile();
    
    service = module.get(LoggingService);
    mockLoggingAuthModel = module.get(getModelToken(LOGGING_AUTH_MODEL));
  });
  
  it('should be defined', () => {
    expect(service).toBeDefined();
  });
  
  it('authLogging', async () => {
    const reqId = 'mock-request-id';
    const mockApiKey = 'mock-api-key';
    const mockStatusCode = 200;
    const mockInternalMessage = 'mock-message';
    
    await service.authLogging(request, reqId, mockApiKey, mockStatusCode, mockInternalMessage);
    
    const authSpy = jest.spyOn(mockLoggingAuthModel, 'save');
    expect(authSpy).toBeCalled();
  });
});

The mock Model:

class MockLoggingAuthModel {
  constructor() {
  }
  
  public async save(): Promise<void> {
  }
}
2

There are 2 answers

0
RemeJuan On BEST ANSWER

After much more googling I managed to find this testing examples Repo: https://github.com/jmcdo29/testing-nestjs which includes samples on Mongo and also suggest that using the this.model(data) complicates testing and one should rather use `this.model.create(data).

After making that change the tests are working as expected.

3
Baboo On

The issue comes from the fact that you pass a class to the TestingModule while telling it that it's a value.

Use useClass to create the TestingModule:

beforeEach(async () => {
  request = new JestRequest();
  
  const module: TestingModule = await Test.createTestingModule({
    providers: [
      LoggingService,
      {
        provide: getModelToken(LOGGING_AUTH_MODEL),
        // Use useClass
        useClass: mockLoggingAuthModel,
      },
      {
        provide: getModelToken(LOGGING_EVENT_MODEL),
        // Use useClass
        useClass: MockLoggingEventModel,
      },
    ],
  }).compile();
  
  service = module.get(LoggingService);
  mockLoggingAuthModel = module.get(getModelToken(LOGGING_AUTH_MODEL));
});