Jasmine JavaScript Testing Framework Jasmine Spies and Mocking 2 — Questions and Answers
Question 1: What does .and.throwError('msg') do when configured on a Jasmine spy?
- Makes the spy throw an Error with that message when called (Correct answer)
- Logs the message to the console on each call
- Catches errors thrown inside the real method
- Marks the spy as expected to throw
Correct answer: Makes the spy throw an Error with that message when called
throwError('msg') configures the spy to throw a new Error with the given message every time it is invoked.
Question 2: How do you reset all recorded call data for a Jasmine spy?
- spy.calls.reset() (Correct answer)
- spy.reset()
- spy.clearCalls()
- spy.calls.clear()
Correct answer: spy.calls.reset()
spy.calls.reset() clears the internal call log so count, args, and other tracking data start fresh.
Question 3: What does spy.calls.any() return?
- true if the spy was called at least once (Correct answer)
- The first call object in the log
- The total number of calls made
- true if the spy has pending return values
Correct answer: true if the spy was called at least once
any() is a convenience method that returns true when the spy's call count is greater than zero.
Question 4: Which spy configuration method executes a custom function when the spy is called?
- .and.callFake(fn) (Correct answer)
- .and.execute(fn)
- .and.invoke(fn)
- .and.run(fn)
Correct answer: .and.callFake(fn)
callFake(fn) replaces the spy's implementation with the provided function, which runs on each invocation.
Question 5: What does jasmine.createSpy('myMethod') create?
- A standalone spy function not attached to any object (Correct answer)
- A spy placed on the global window object
- A spy that intercepts all method calls in the suite
- A configured HTTP request interceptor
Correct answer: A standalone spy function not attached to any object
createSpy produces an independent spy function you can pass as a callback or stub without needing a host object.
Question 6: Which Jasmine matcher verifies that a spy was called with specific arguments?
- toHaveBeenCalledWith() (Correct answer)
- toHaveBeenCalledUsing()
- toHaveReceivedArgs()
- toHaveBeenInvokedWith()
Correct answer: toHaveBeenCalledWith()
toHaveBeenCalledWith() checks that at least one invocation of the spy received exactly the given arguments.
What does .and.throwError('msg') do when configured on a Jasmine spy?