Nest.js testing cannot override Provider


I have a problem with overriding provider in nest.js application for testing.
My stats.controller.spec.ts:

import { StatsService } from './services/stats.service';
import { StatsController } from './stats.controller';

describe('StatsController', () => {
  let controller: StatsController;

  const mockStatsService = {};

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [StatsController],
      providers: [StatsService],
    })
      .overrideProvider(StatsService)
      .useValue(mockStatsService)
      .compile();

    controller = module.get<StatsController>(StatsController);
  });

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

My stats.controller.ts:

import { Controller, Get } from '@nestjs/common';
import { StatsService } from './services/stats.service';

@Controller('stats')
export class StatsController {
  constructor(private statsService: StatsService) {}

  @Get('weekly')
  getWeeklyStats() {
    return this.statsService.getWeeklyStats();
  }

  @Get('monthly')
  getMonthlyStats() {
    return this.statsService.getMonthlyStats();
  }
}

And my stats.service.ts:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Trip } from 'src/trips/trip.entity';
import { from, map } from 'rxjs';
import { DatesService } from 'src/shared/services/dates.service';

@Injectable()
export class StatsService {
  constructor(
    @InjectRepository(Trip) private tripRepository: Repository<Trip>,
    private datesServices: DatesService,
  ) {}
 //some code here
}

And after running test I get following errors:
Cannot find module ‘src/trips/trip.entity’ from ‘stats/services/stats.service.ts’
I would really appreciate some help.

Source: JavaSript – Stack Overflow

November 28, 2021
Category : News
Tags: javascript | jestjs | nestjs | node.js | testing

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.