Bird
0
0

Given this Angular test setup, what will be the output of component.getData() if mockService.getData() returns 'test data'?

medium📝 component behavior Q13 of 15
Angular - Services and Dependency Injection
Given this Angular test setup, what will be the output of component.getData() if mockService.getData() returns 'test data'?
const mockService = { getData: () => 'test data' };

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [{ provide: RealService, useValue: mockService }]
  });
  component = TestBed.inject(MyComponent);
});

// In component:
getData() {
  return this.realService.getData();
}
A'real data'
BError: realService not defined
Cundefined
D'test data'
Step-by-Step Solution
Solution:
  1. Step 1: Understand provider override in TestBed

    The test replaces RealService with mockService returning 'test data'.
  2. Step 2: Trace component method call

    component.getData() calls realService.getData(), which is the mock returning 'test data'.
  3. Final Answer:

    'test data' -> Option D
  4. Quick Check:

    Mocked service returns 'test data' = D [OK]
Quick Trick: Mocked provider returns test data, so method returns it [OK]
Common Mistakes:
MISTAKES
  • Assuming real service runs instead of mock
  • Expecting undefined without provider
  • Confusing service injection with component injection

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes