Jasmine JavaScript Testing Framework Jasmine JavaScript 2 — Questions and Answers
Question 1: Which Jasmine spy method tracks calls but also delegates to the real implementation?
- and.callThrough() (Correct answer)
- and.stub()
- and.returnValue()
- and.callFake()
Correct answer: and.callThrough()
`and.callThrough()` allows the spy to record calls while still invoking the original function.
Question 2: What does `jasmine.objectContaining()` do in a matcher?
- Checks that an object has at least the specified key-value pairs (Correct answer)
- Asserts an object is exactly equal to the expected
- Converts an object to a string for comparison
- Verifies the object is an instance of a class
Correct answer: Checks that an object has at least the specified key-value pairs
`jasmine.objectContaining()` passes when the actual object includes all the listed properties, ignoring extras.
Question 3: How do you assert that a spy was called with specific arguments in Jasmine?
- expect(spy).toHaveBeenCalledWith(args) (Correct answer)
- expect(spy).toHaveBeenCalled(args)
- spy.argsFor(0).toEqual(args)
- spy.callCount(args)
Correct answer: expect(spy).toHaveBeenCalledWith(args)
`toHaveBeenCalledWith()` checks that the spy was called at least once with exactly those arguments.
Question 4: What is the purpose of `beforeAll` in Jasmine?
- Runs setup code once before all specs in a describe block (Correct answer)
- Runs before each individual spec
- Resets spies after all tests
- Declares shared variables across files
Correct answer: Runs setup code once before all specs in a describe block
`beforeAll` executes a single time before any `it` blocks in its enclosing `describe` run.
Question 5: Which matcher would you use to confirm a value is `undefined`?
- toBeUndefined() (Correct answer)
- toBeNull()
- toBeFalsy()
- toEqual(undefined)
Correct answer: toBeUndefined()
`toBeUndefined()` specifically checks that the value is strictly `undefined`.
Question 6: How can you create a Jasmine spy for a standalone function (not a method)?
- jasmine.createSpy('name') (Correct answer)
- spyOn(window, 'functionName')
- jasmine.createSpyObj(['functionName'])
- new jasmine.Spy('name')
Correct answer: jasmine.createSpy('name')
`jasmine.createSpy()` creates a bare spy function not attached to any object.
Question 7: What does `spy.calls.count()` return?
- The number of times the spy was called (Correct answer)
- An array of argument lists for each call
- The return value of the most recent call
- Whether the spy was ever called
Correct answer: The number of times the spy was called
`calls.count()` returns an integer representing how many times the spy was invoked.
Which Jasmine spy method tracks calls but also delegates to the real implementation?