Bird
0
0

You want to mock a service method that returns different values on consecutive calls in Angular tests. Which approach correctly achieves this?

hard📝 Application Q15 of 15
Angular - Testing
You want to mock a service method that returns different values on consecutive calls in Angular tests. Which approach correctly achieves this?
ACreate a mock class with a method using a call count variable to return different values
BUse useValue with a plain object having the method returning a fixed value
CUse useClass with the real service and override the method in the test
DInject the real service and spy on the method without mocking
Step-by-Step Solution
Solution:
  1. Step 1: Understand requirement for different returns

    Returning different values on consecutive calls requires state tracking inside the mock method.
  2. Step 2: Choose correct mocking approach

    A mock class with a call count variable can track calls and return different values accordingly.
  3. Step 3: Evaluate other options

    useValue with fixed return can't vary returns; overriding real service method is complex; spying alone doesn't mock service.
  4. Final Answer:

    Create a mock class with a method using a call count variable to return different values -> Option A
  5. Quick Check:

    Mock class with state tracks calls for varied returns [OK]
Quick Trick: Use mock class with call count to vary method returns [OK]
Common Mistakes:
  • Using fixed return object for varying outputs
  • Overriding real service instead of mocking
  • Relying only on spies without mocks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes