wen*_*zel 2 unit-testing dependency-injection nestjs
我尝试为我的小型应用程序创建单元测试。我想测试使用注入配置和其他服务的服务。
@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;
}
...
Run Code Online (Sandbox Code Playgroud)
我不明白如何测试这项服务。我不知道如何为注入的配置提供正确的 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();
Run Code Online (Sandbox Code Playgroud)
我也不确定是否还需要创建其他导入的服务。我只是想检查一下他们是否被叫到。如果是,则返回模拟数据。我可以做到这一点,但我坚持模块设置。
到目前为止,我发现的所有示例都仅使用一个存储库提供服务。并且或多或少地检查服务是否存在。但没有检查实现的逻辑和类之间的连接。
我希望我的问题很清楚谢谢
我认为您应该使用该useValue属性,而不是useClass传递键值对象?
providers: [
{
provide: CORE_CONFIG_TOKEN,
useValue: {
domain: 'nestjs.com',
port: 80,
},
},
],
Run Code Online (Sandbox Code Playgroud)
还有一些关于在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}`,
}
Run Code Online (Sandbox Code Playgroud)