The angular guide demonstrates two different ways of testing, one by calling new Service() and providing the dependencies to the constructor directly, and the second using dependency injection by calling TestBed.get(Service).
Both of these seem functionally identical to me, except when I call TestBed.get() consecutively it does not call the constructor after the first call.
The angular documentation also mentions that TestBed.get() is deprecated (even though the guide still references it!) and that I should use Type or InjectionToken instead, but I do not see how either of these classes could replace TestBed.get().
Deprecated from v9.0.0 use TestBed.inject
get(token: any, notFoundValue?: any): any
See how can we inject now:
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);
});
Just adding so might can help someone.
get is deprecated: from v9.0.0 use TestBed.inject (deprecation)
let valueServiceSpy: jasmine.SpyObj<ValueService>;
beforeEach(() => {
const spy = jasmine.createSpyObj('ValueService', ['getValue']);
TestBed.configureTestingModule({
providers: [
{ provide: ValueService, useValue: spy }
]
});
// This is new way to inject Spied Service
valueServiceSpy = TestBed.inject(ValueService) as jasmine.SpyObj<ValueService>;
});
and then in tests
it('#getValue should return stubbed value from a spy', () => {
valueServiceSpy.getValue.and.returnValue(yourValue);
...
});
Official Doc: https://v9.angular.io/guide/testing#angular-testbed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With