Jasmine JavaScript Testing Framework Jasmine JavaScript Knowledge 2 — Questions and Answers
Question 1: Which Jasmine method is used to create a spy that replaces a real function and tracks calls to it?
- jasmine.createSpy() (Correct answer)
- jasmine.spy()
- jasmine.watch()
- jasmine.mock()
Correct answer: jasmine.createSpy()
jasmine.createSpy() creates a bare spy function that tracks calls without wrapping an existing object method.
Question 2: What does the `spyOn` function return in Jasmine?
- The spy object itself (Correct answer)
- The original function
- A promise
- The return value of the spied function
Correct answer: The spy object itself
spyOn returns the spy object, allowing you to chain matchers like .and.returnValue() or .and.callThrough().
Question 3: Which spy strategy makes the spy delegate to the actual implementation while still tracking calls?
- .and.callThrough() (Correct answer)
- .and.returnValue()
- .and.stub()
- .and.callFake()
Correct answer: .and.callThrough()
.and.callThrough() causes the spy to invoke the original function and record the call.
Question 4: How do you assert that a spy was called with specific arguments in Jasmine?
- expect(spy).toHaveBeenCalledWith(args) (Correct answer)
- expect(spy).calledWith(args)
- expect(spy).toBeCalledWith(args)
- expect(spy).wasCalledWith(args)
Correct answer: expect(spy).toHaveBeenCalledWith(args)
toHaveBeenCalledWith() is the Jasmine matcher that verifies a spy received particular arguments.
Question 5: What does `jasmine.createSpyObj('name', ['method1', 'method2'])` return?
- An object with spy methods for each listed name (Correct answer)
- A single spy function
- A Jasmine suite
- A mock module
Correct answer: An object with spy methods for each listed name
jasmine.createSpyObj creates a mock object where every listed method name becomes an individual spy.
Question 6: Which matcher checks that a spy was called exactly once?
- toHaveBeenCalledTimes(1) (Correct answer)
- toHaveBeenCalledOnce()
- toHaveBeenCalledSingle()
- toHaveBeenCalledCount(1)
Correct answer: toHaveBeenCalledTimes(1)
toHaveBeenCalledTimes(n) asserts the spy was invoked exactly n times.
Question 7: What happens to a spy's tracked calls between specs if `beforeEach` contains `spyOn`?
- The spy is recreated fresh for each spec (Correct answer)
- Calls accumulate across all specs
- The spy is destroyed permanently
- Calls are saved to a global log
Correct answer: The spy is recreated fresh for each spec
Because beforeEach runs before every spec, spyOn creates a new spy each time, resetting call history.
Which Jasmine method is used to create a spy that replaces a real function and tracks calls to it?