且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TestBed.get和new Service(... dependencies)有什么区别

更新时间:2023-11-12 14:42:10

当您调用 TestBed.configureTestingModule({provider:[SomeService]}); 时,这将设置一个可以使用的NgModule在随后的测试中.如果调用 TestBed.get(SomeService),则会从注入器中检索 SomeService ,并在需要时实例化它.如果已实例化,则注入器将注入对其依赖项的引用,并返回该服务的新实例.

When you call TestBed.configureTestingModule({ providers: [SomeService] });, this sets up an NgModule that can be used in subsequent tests. If you call TestBed.get(SomeService), this retrieves SomeService from the injector and instantiates it if needed. If it is instantiated, then the injector injects references to it's dependencies and returns a new instance of the service.

如果您已经实例化了 SomeService ,则TestBed不需要创建它.这意味着它将不会在以后调用构造函数.

If SomeService has already been instantiated, as in your case, then the TestBed does not need to create it. This means that it won't call the constructor a subsequent time.

要回答有关差异的问题,如果您嘲笑所有依赖项并且不需要访问DOM,则基本上它们是相同的.没有TestBed的实例化类的速度明显更快,因为没有为每个测试加载依赖项注入程序的开销.

To answer your question about the difference, basically they are the same if you are mocking all of your dependencies and if you don't need to access the DOM. Instantiating classes without the TestBed is significantly faster because there isn't the overhead of loading the dependency injector for every test.

对于不推荐使用的TestBed.get(),在Angular 8.0.0中,仅弃用了允许任何时间的特定重载(请参见

As for the TestBed.get() being deprecated, in Angular 8.0.0, only the specific overload that allows any time was deprecated (see https://github.com/angular/angular/blob/master/packages/core/testing/src/test_bed.ts#L67). Instead of get(token: any, notFoundValue?: any): any; the signature was changed to get<T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): any; which means that you had to use a class reference or injection token. No strings or other things to reference something in the injector.

在Angular 9.0.0中,将完全弃用TestBed.get()方法,而您需要使用 TestBed.inject .参见 https://github.com/角/角/斑点/母版/软件包/核心/测试/src/test_bed.ts#L65

In Angular 9.0.0, the TestBed.get() method will be fully deprecated and you will need to use TestBed.inject instead. See https://github.com/angular/angular/blob/master/packages/core/testing/src/test_bed.ts#L65