Bird
0
0

You want to test a component that calls a service method returning an Observable. How do you mock the service method to emit a value 'test' synchronously?

hard📝 Application Q8 of 15
Angular - Testing
You want to test a component that calls a service method returning an Observable. How do you mock the service method to emit a value 'test' synchronously?
AUse useClass with a class that returns Promise.resolve('test')
BUse useValue with a method returning 'test' string directly
CUse jasmine.createSpyObj and returnValue(of('test')) for the method
DUse HttpClientTestingModule to mock the service method
Step-by-Step Solution
Solution:
  1. Step 1: Identify Observable return type

    The service method returns an Observable, so the mock must return an Observable too.
  2. Step 2: Use jasmine spy with returnValue

    Use jasmine.createSpyObj to create a spy method and return of('test') to emit synchronously.
  3. Final Answer:

    Use jasmine.createSpyObj and returnValue(of('test')) for the method -> Option C
  4. Quick Check:

    Mock Observable with of() in spy [OK]
Quick Trick: Mock Observable methods with of() in jasmine spies [OK]
Common Mistakes:
  • Returning Promise instead of Observable
  • Returning raw string instead of Observable
  • Using HttpClientTestingModule for non-HTTP mocks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes