[英]Angular TestBed.inject
I am doing angular unit testing.我正在做 angular 单元测试。 Does TestBed.inject(service) create a new instance of the service?
TestBed.inject(service) 是否创建服务的新实例? I was always under the assumption that TestBed.configureTestingModule() created the service and by inject we just accessed a reference of the created service.
我一直假设 TestBed.configureTestingModule() 创建了服务,并且通过注入我们只是访问了所创建服务的引用。
TestBed.configureTestingModule() helps you configure the providers. TestBed.configureTestingModule() 帮助您配置提供程序。 Configuring the providers means you are letting the Angular dependency injection system know about this dependency which later it can inject in to components when requested through a dependency injection token.
配置提供程序意味着您让 Angular 依赖注入系统知道此依赖关系,稍后它可以在通过依赖注入令牌请求时将其注入组件。 In the below example the dependency and token is ValueService.
在下面的示例中,依赖项和令牌是 ValueService。
TestBed.configureTestingModule({ providers: [ValueService] });
Later, you can use ValueService in your test using TestBed.inject.稍后,您可以使用 TestBed.inject 在您的测试中使用 ValueService。 When you say TestBed.inject Angular dependency injection system checks if there is a provider registered against the token, if yes, then it creates an instance of the service and returns it.
当您说 TestBed.inject Angular 时,依赖注入系统会检查是否有针对令牌注册的提供者,如果是,则它会创建一个服务实例并返回它。 If it doesn't find that token, you will the famous
如果它没有找到该令牌,您将获得著名的
No provider for ValueService error.
没有 ValueService 错误的提供者。
it('should use ValueService', () => {
service = TestBed.inject(ValueService);
expect(service.getValue()).toBe('real value');
});
So it is similar to our application code, where in we first configure the providers and then inject it to our components to grab an instance of that service.所以它类似于我们的应用程序代码,我们首先配置提供程序,然后将其注入我们的组件以获取该服务的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.