【问题标题】:How to provide Injected constant to service in nestjs when unit testing单元测试时如何在nestjs中为服务提供注入常量
【发布时间】:2019-03-01 01:30:56
【问题描述】:

我尝试为我的小型应用程序创建单元测试。我想测试一个使用注入配置和其他服务的服务。

@Injectable()
export class AuthService {
        private readonly localUri: string;

        constructor(
            @Inject(CORE_CONFIG_TOKEN) private readonly coreConfig: ICoreConfig,
            @Inject(PROVIDER_CONFIG_TOKEN) private readonly providerConfig: IProviderConfig,
            private readonly _httpService: HttpService,
            private readonly _usersService: UsersService,
        ) {
            this.localUri = `http://${this.coreConfig.domain}:${this.coreConfig.port}`;
        }

        ...


        /**
         * Checks if a given email is already taken
         * @param email
         */
        async isEmailTaken(email: string): Promise<boolean> {
            return (await this._usersService.findUserByEmail(email)) !== undefined;
        }

        ...

我不明白如何测试这项服务。我不知道如何为注入的配置提供正确的 TestModule 提供程序@Inject(CORE_CONFIG_TOKEN) private readonly coreConfig: ICoreConfig

    const testCoreConfig = '{...}'
    const module = await Test.createTestingModule({
      providers: [AuthService, {
           provide: 'CORE_CONFIG_TOKEN',
           useClass: testCoreConfig ,
      }],
    }).compile();

此外,我不确定是否还需要创建其他导入的服务。我只是想检查他们是否被调用。如果是这样,返回模拟数据。我可以这样做,但我坚持使用模块设置。

到目前为止,我发现的所有示例都只有一个存储库提供服务。并且或多或少地检查服务是否存在。但是没有检查实现的逻辑和类之间的连接。

我希望我的问题很清楚 谢谢

【问题讨论】:

    标签: unit-testing dependency-injection nestjs


    【解决方案1】:

    如果您要传递键值对象,我认为您应该使用useValue 属性而不是useClass

    providers: [
        {
            provide: CORE_CONFIG_TOKEN,
            useValue: {
               domain: 'nestjs.com',
               port: 80,
            },
        },
    ],
    

    还有一些关于在nestjs 上为您的模块创建配置提供程序/服务的文档。

    我还创建了一个nestjs-config 模块,您可以使用与此类似的模块。

    @Injectable()
    class TestProvider {
        constructor(private readonly @InjectConfig() config) {
            this.localUri = config.get('local.uri');
        }
    
    @Module({
        imports: [ConfigModule.load('path/to/config/file/*.ts')],
        providers: [TestProvider],
    })
    export AppModule {}
    
    //config file 'config/local.ts'
    export default {
        uri: `https://${process.env.DOMAIN}:/${process.env.PORT}`,
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-22
      • 2014-04-20
      • 2020-12-21
      • 2012-08-31
      • 2021-10-30
      • 2012-12-23
      • 2021-05-29
      • 1970-01-01
      • 2020-11-20
      相关资源
      最近更新 更多