【问题标题】:Mock Injected Service In Unit Testing Nest.js在单元测试 Nest.js 中模拟注入服务
【发布时间】:2021-04-05 06:08:27
【问题描述】:

我想测试我的服务(定位服务)。在这个位置服务中,我注入了存储库和其他名为 GeoLocationService 的服务,但是当我尝试模拟这个 GeoLocationService 时卡住了。

它给我一个错误

GeolocationService › should be defined

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

这里是提供者的代码

@Injectable()
export class LocationService {
  constructor(
    @Inject('LOCATION_REPOSITORY')
    private locationRepository: Repository<Location>,

    private geolocationService: GeolocationService, // this is actually what I ma trying to mock
  ) {}

  async getAllLocations(): Promise<Object> {
return await this.locationRepository.find()
  }
....
}

这是测试代码

describe('LocationService', () => {
  let service: LocationService;
  let repo: Repository<Location>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [GeolocationModule],
      providers: [
        LocationService,
        {
          provide: getRepositoryToken(Location),
          useClass: Repository,
        },
      ],
    }).compile();

    service = module.get<LocationService>(LocationService);
    repo = module.get<Repository<Location>>(getRepositoryToken(Location));
  });

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

【问题讨论】:

    标签: node.js jestjs nestjs


    【解决方案1】:

    您应该提供GeolocationService 的模拟,而不是添加imports: [GeolocationModule]。这个模拟应该与GeolocationService 具有相同的方法名称,但它们都可以被存根(jest.fn())或者它们可以有一些返回值(jest.fn().mockResolved/ReturnedValue())。通常,自定义提供程序(添加到 providers 数组)如下所示:

    {
      provide: GeolocationService,
      useValue: {
        method1: jest.fn(),
        method2: jest.fn(),
      }
    }
    

    You can find a large sample of mocks in this repository.

    【讨论】:

    • 为什么我们不导入模块?服务不是模块的一部分吗?
    • 当您添加 imports: [SomeModule] 时,如果 SomeModule 有其他导入,您需要注意在测试上下文中也有可用的导入,然后是这些导入的导入,依此类推.只需添加服务,您就可以准确地知道需要提供哪些依赖项,并且可以提供基本的模拟,而无需进一步陷入依赖地狱
    猜你喜欢
    • 1970-01-01
    • 2016-09-05
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    相关资源
    最近更新 更多