0
0
Angularframework~10 mins

Why DI makes testing easier in Angular - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to inject a service into a component constructor.

Angular
constructor(private [1]: DataService) {}
Drag options to blanks, or click blank then click option'
AdataService
BDataService
Cservice
Dinjector
Attempts:
3 left
💡 Hint
Common Mistakes
Using the class name instead of a variable name
Using a generic name like 'injector'
2fill in blank
medium

Complete the code to provide a mock service for testing.

Angular
providers: [{ provide: DataService, useClass: [1] }]
Drag options to blanks, or click blank then click option'
ARealDataService
BMockDataService
CHttpClient
DTestBed
Attempts:
3 left
💡 Hint
Common Mistakes
Using the real service instead of a mock
Using unrelated classes like HttpClient
3fill in blank
hard

Fix the error in injecting a service in the test setup.

Angular
beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [[1]]
  });
});
Drag options to blanks, or click blank then click option'
ADataService
BMockDataService
CHttpClient
D{ provide: DataService, useClass: MockDataService }
Attempts:
3 left
💡 Hint
Common Mistakes
Listing only the service class
Using the mock class without provide key
4fill in blank
hard

Fill both blanks to inject and use a mock service in a test.

Angular
let service: DataService;
beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [{ provide: [1], useClass: [2] }]
  });
  service = TestBed.inject(DataService);
});
Drag options to blanks, or click blank then click option'
ADataService
BMockDataService
CHttpClient
DRealDataService
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of provide and useClass
Using unrelated classes
5fill in blank
hard

Fill all three blanks to create a test that uses dependency injection to replace a service and verify a method call.

Angular
describe('MyComponent', () => {
  let service: [1];
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [{ provide: [2], useClass: [3] }]
    });
    service = TestBed.inject(DataService);
  });

  it('should call fetchData', () => {
    spyOn(service, 'fetchData').and.returnValue(of([]));
    service.fetchData();
    expect(service.fetchData).toHaveBeenCalled();
  });
});
Drag options to blanks, or click blank then click option'
ADataService
CMockDataService
DHttpClient
Attempts:
3 left
💡 Hint
Common Mistakes
Using HttpClient instead of mock
Not matching the service type and token