Node.js 单元测试Nest.js中的模拟注入服务

Node.js 单元测试Nest.js中的模拟注入服务,node.js,jestjs,nestjs,Node.js,Jestjs,Nestjs,我想测试我的服务(定位服务)。在这个位置服务中,我注入了存储库和其他名为GeoLocationService的服务,但在尝试模拟这个GeoLocationService时遇到了问题 这给我带来了一个错误 GeolocationService › should be defined Nest can't resolve dependencies of the GeolocationService (?). Please make sure that the argument HttpSe

我想测试我的服务(定位服务)。在这个位置服务中,我注入了存储库和其他名为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()
  }
....
}

@Injectable()
出口类定位服务{
建造师(
@注入('LOCATION\u REPOSITORY')
私有位置存储库:存储库,
private geolocationService:geolocationService,//这实际上是我想要模仿的
) {}
异步getAllLocations():承诺{
return等待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();
  });
});
description('LocationService',()=>{
let服务:定位服务;
let repo:存储库;
beforeach(异步()=>{
常量模块:TestingModule=等待测试。createTestingModule({
导入:[GeolocationModule],
供应商:[
定位服务,
{
提供:getRepositoryToken(位置),
useClass:存储库,
},
],
}).compile();
服务=模块.get(LocationService);
repo=module.get(getRepositoryToken(Location));
});
它('应该定义',()=>{
expect(service.toBeDefined();
});
});

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

{
提供:地理定位服务,
使用价值:{
方法1:jest.fn(),
方法2:jest.fn(),
}
}