[英]What is the difference between testbed.get and inject in Angular 2/Jasmine testing?
I am new to Angular 2 testing.我是 Angular 2 测试的新手。 I am trying to figure out what is the difference in using
testsbed.get()
and just using inject
at the test level.我试图弄清楚使用
testsbed.get()
和只在测试级别使用inject
什么区别。
eg:例如:
beforeEach(() => {
TestBed.configureTestingModule({
providers: [SomeService]
});
const testbed = getTestBed();
someService= testbed.get(SomeService);
});
});
vs对比
it('test service', inject([SomeService], (someService: SomeService) => {
Just to add to the existing answer and if like me you found this question because you are wondering what the difference is between TestBed.get()
and TestBed.inject()
which I know was not quite what the OP originally asked but it is relevant and is very much related.只是为了添加到现有答案,如果像我一样,你发现了这个问题,因为你想知道
TestBed.get()
和TestBed.inject()
之间有什么区别,我知道这与 OP 最初要求的不太一样,但它是相关的并且非常相关。
I thought it was worth posting that according to the latest Angular documentation that TestBed.inject()
is the type safe replacement of TestBed.get()
.我认为这是值得发帖称根据最新的角度说明文件
TestBed.inject()
是类型安全的替换TestBed.get()
From the Angular documentation on TestBed
that can be found here .从可以在此处找到的
TestBed
上的 Angular 文档。
inject
helper function was historically used since AngularJS as an alternative to direct injector calls.自 AngularJS 以来,
inject
辅助函数一直被用作直接注入器调用的替代方法。 In Angular 1, it was necessary to bootstrap a test with ngMock
.在 Angular 1 中,有必要使用
ngMock
引导测试。 It is entirely optional in Angular 2 and higher and is just a suggested way for DI in TestBed tests.它在 Angular 2 及更高版本中完全是可选的,并且只是 TestBed 测试中 DI 的一种建议方式。
It a convenience wrapper for testBed.get
that allows to avoid multiple testBed.get
calls, similarly to: 它是
testBed.get
的便利包装器,可以避免多次testBed.get
调用,类似于:
const [foo, bar] = [Foo, Bar].map(TestBed.get);
Other helper functions can be optionally used in conjunction with inject
, namely async
and fakeAsync
.其他辅助函数可以选择性地与
inject
结合使用,即async
和fakeAsync
。
These use to be equivalent, but in Angular 9 the preferred method was updated.这些用法是等效的,但在 Angular 9 中更新了首选方法。
TestBed.get()
is deprecated in Angular 9+, and TestBed.inject()
is now the preferred type-safe way to inject a dependency. TestBed.get()
在 Angular 9+ 中已被弃用,而TestBed.inject()
现在是注入依赖项的首选类型安全方式。
Read the documentation for clarity: TestBed.get() and TestBed.inject() .为清楚起见,请阅读文档: TestBed.get()和TestBed.inject() 。 The change is one of deprecation.
更改是弃用之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.