【问题标题】:Nest cannot resolve dependencies of ElasticsearchServiceNest 无法解析 ElasticsearchService 的依赖关系
【发布时间】:2019-12-15 12:03:35
【问题描述】:

我正在尝试使用 ElasticsearchService Nest 服务,无法解析依赖项

这是 package.json 相关的模块版本:

"@nestjs/common": "^5.5.0",
"@nestjs/core": "^5.5.0",
"@nestjs/elasticsearch": "^6.0.1",
"@types/elasticsearch": "^5.0.34",
"elasticsearch": "^16.3.0",

这是一个示例代码:

import { Test, TestingModule } from '@nestjs/testing';
import * as mocha from 'mocha';
import {
  ElasticsearchService,
  ElasticsearchModule,
} from '@nestjs/elasticsearch';
import { Client } from 'elasticsearch';

const clientFactory = {
  provide: Client,
  useFactory: () => {
    return new Client({});
  },
};

mocha.describe('Test Suite', () => {
  let module: TestingModule;
  let elasticsearch: ElasticsearchService;

  before(async () => {
    module = await Test.createTestingModule({
      imports: [ElasticsearchModule],
      providers: [ElasticsearchService, clientFactory],
    }).compile();

    elasticsearch = module.get<ElasticsearchService>(ElasticsearchService);
  });
  it('should be defined', () => {
    console.log('This message does not appears');
  });
});

【问题讨论】:

  • 这是错误:错误:Nest 无法解析 ElasticsearchService (?) 的依赖项。请确保索引 [0] 处的参数在 ElasticsearchModule 上下文中可用。

标签: elasticsearch dependency-injection nestjs


【解决方案1】:

如果你看这里:https://www.npmjs.com/package/@nestjs/elasticsearch ElasticSearchModule 似乎不是真的准备使用的模块,它更像是一个工厂,你需要调用 ElasticsearchModule.register() 或 @987654324 @ 将返回一个 NestJS 模块。

module = await Test.createTestingModule({
  imports: [ElasticsearchModule.register(...)],
  providers: [ElasticsearchService, clientFactory],
}).compile();

之前没有用过这个模块,这只是一个最好的猜测,祝你好运!

【讨论】:

    【解决方案2】:

    除非这是一个 e2e 测试,否则您不应导入 Module 文件,因为您正在使用 Nest 的辅助函数创建 TestModule。这可能会导致您错误地覆盖 ElasticSearchService 并且不允许 Nest 注入正确的值。

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2018-11-21
      • 2020-03-12
      • 2020-07-03
      • 2021-04-28
      • 2020-03-07
      • 2020-12-14
      • 2020-12-13
      • 2019-12-09
      相关资源
      最近更新 更多