简体   繁体   中英

Testing Service with Mongoose in NestJS

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 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> {
  }
}

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));
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM