angular guide演示了两种不同的测试方法,一种是通过调用 new Service() 并直接向构造函数提供依赖项,另一种是通过调用 TestBed.get(Service) 使用依赖项注入(inject)。
这两个在我看来在功能上是相同的,除了当我连续调用 TestBed.get() 时它不会在第一次调用后调用构造函数。
angular documentation还提到 TestBed.get() 已弃用(即使指南仍然引用它!)并且我应该使用 Type或 InjectionToken相反,但我看不出这些类中的任何一个如何替代 TestBed.get()。
最佳答案
Deprecated from v9.0.0 use TestBed.inject
get(token: any, notFoundValue?: any): any
看看我们现在如何注入(inject):
describe('MyAmountComponent', () => {
let component: MyAmountComponent;
let fixture: ComponentFixture<MyAmountComponent>;
let productService: ProductService;
let orderService: OrderService;
beforeEach(() => {
TestBed.configureTestingModule({
.....
})
.compileComponents();
productService = TestBed.inject(ProductService);
orderService = TestBed.inject(OrderService);
});
只需添加 so might 就可以帮助某人。
关于angular - TestBed.get 和 new Service(...dependencies) 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56776234/