Jasmine JavaScript Testing Framework Jasmine JavaScript for Beginner's 3 — Questions and Answers
Question 1: What is a Jasmine spy object created with `jasmine.createSpyObj`?
- A spy that wraps an existing class
- A mock object with multiple named spy methods (Correct answer)
- A spy that records return values only
- A test double that throws errors by default
Correct answer: A mock object with multiple named spy methods
`jasmine.createSpyObj('name', ['method1','method2'])` returns an object whose properties are all pre-built spy functions.
Question 2: Which `calls` property tells you the total number of times a spy was invoked?
- spy.calls.total()
- spy.calls.count() (Correct answer)
- spy.calls.length
- spy.invocationCount
Correct answer: spy.calls.count()
`spy.calls.count()` returns the integer number of times the spy has been called.
Question 3: What does `spy.and.returnValue(42)` do?
- Asserts the spy returns 42
- Makes the spy always return 42 when called (Correct answer)
- Stores 42 as a call argument
- Throws an error if the spy doesn't return 42
Correct answer: Makes the spy always return 42 when called
`and.returnValue` configures the spy to return the specified value every time it is invoked.
Question 4: What does the `afterAll` hook do in Jasmine?
- Runs after each individual spec
- Runs once after all specs in the describe block finish (Correct answer)
- Resets all spies automatically
- Fails any remaining specs
Correct answer: Runs once after all specs in the describe block finish
`afterAll` runs a teardown function exactly once after the last spec in the enclosing describe block has completed.
Question 5: How does Jasmine handle asynchronous specs that use `done`?
- The spec fails immediately if async code runs
- Jasmine waits until `done()` is called before marking the spec complete (Correct answer)
- Jasmine ignores async callbacks by default
- You must return a Promise; `done` is deprecated
Correct answer: Jasmine waits until `done()` is called before marking the spec complete
When a spec function declares `done` as a parameter, Jasmine waits for `done()` to be called before finishing the spec.
Question 6: Which matcher would you use to assert an array contains a specific item?
- toInclude()
- toContain() (Correct answer)
- toHave()
- toMatchItem()
Correct answer: toContain()
`toContain` checks whether an array (or string) includes the expected element.
Question 7: What is the effect of calling `spy.calls.reset()` during a test?
- Removes the spy from the object
- Clears all recorded call information for the spy (Correct answer)
- Restores the original function
- Throws a TypeError
Correct answer: Clears all recorded call information for the spy
`calls.reset()` clears the spy's call history, allowing you to re-verify behavior in subsequent test steps.
What is a Jasmine spy object created with `jasmine.createSpyObj`?