Jasmine JavaScript Testing Framework Jasmine Spies and Mocking 1 — Questions and Answers
Question 1: What function creates a spy on an existing object method in Jasmine?
- spyOn(obj, 'method') (Correct answer)
- createSpy(obj, 'method')
- mockMethod(obj, 'method')
- interceptMethod(obj, 'method')
Correct answer: spyOn(obj, 'method')
spyOn(obj, 'method') replaces the named method on obj with a Jasmine spy that tracks calls.
Question 2: Which property returns the number of times a Jasmine spy was called?
- spy.calls.count() (Correct answer)
- spy.callCount
- spy.times()
- spy.invocationCount
Correct answer: spy.calls.count()
spy.calls.count() is the method on the calls object that returns the total invocation count.
Question 3: What does spyOn(obj, 'method').and.returnValue(42) do?
- Makes the spy return 42 instead of calling the real method (Correct answer)
- Calls the real method and then returns 42
- Throws 42 as an error value
- Logs 42 each time the method is called
Correct answer: Makes the spy return 42 instead of calling the real method
returnValue(42) configures the spy to always return 42 without invoking the original implementation.
Question 4: How do you configure a Jasmine spy to invoke the original implementation?
- .and.callThrough() (Correct answer)
- .and.passThrough()
- .and.original()
- .and.delegate()
Correct answer: .and.callThrough()
callThrough() tells the spy to forward the call to the real method while still tracking it.
Question 5: What does jasmine.createSpyObj('MyClass', ['save', 'load']) return?
- A plain object with save and load as spy functions (Correct answer)
- A single spy wrapping MyClass
- An array of two spy functions
- A spy attached to the global window object
Correct answer: A plain object with save and load as spy functions
createSpyObj creates a mock object whose named methods are all individual spies you can configure.
Question 6: Which expression retrieves the arguments from the most recent spy call?
- spy.calls.mostRecent().args (Correct answer)
- spy.lastArgs
- spy.calls.last().arguments
- spy.recentCall.args
Correct answer: spy.calls.mostRecent().args
spy.calls.mostRecent() returns the call object for the latest invocation, and .args holds its argument array.
What function creates a spy on an existing object method in Jasmine?