Jasmine JavaScript Testing Framework Jasmine JavaScript for Beginner's 4 — Questions and Answers
Question 1: What does `spy.and.callThrough()` do?
- Makes the spy throw an error
- Allows the spy to call the original underlying function while still tracking calls (Correct answer)
- Returns undefined for every call
- Prevents the original function from being called
Correct answer: Allows the spy to call the original underlying function while still tracking calls
`callThrough` keeps the spy active for tracking purposes but also delegates to the real implementation.
Question 2: Which Jasmine matcher checks that a number is within a given precision range?
- toBeCloseTo() (Correct answer)
- toApproximate()
- toBeNear()
- toMatchDecimal()
Correct answer: toBeCloseTo()
`toBeCloseTo(expected, precision)` compares floating-point numbers up to a specified number of decimal places.
Question 3: What happens when a Jasmine spec's `expect` assertion fails?
- The entire test file stops executing
- Only that spec is marked as failed; subsequent specs still run (Correct answer)
- Jasmine exits with a fatal error
- The browser reloads automatically
Correct answer: Only that spec is marked as failed; subsequent specs still run
A failed expectation marks the spec as failed but Jasmine continues running remaining specs in the suite.
Question 4: How do you assert that a function throws an error in Jasmine?
- expect(fn()).toThrow()
- expect(fn).toThrow()
- expect(() => fn()).toThrowError()
- Both B and C are correct (Correct answer)
Correct answer: Both B and C are correct
You pass the function reference (not its return value) to `expect`; both `toThrow()` and `toThrowError()` are valid matchers.
Question 5: What is the role of Jasmine's `jasmine.clock()` utility?
- Measures real elapsed time in milliseconds
- Replaces native timer functions to control time in tests (Correct answer)
- Reports slow specs to the console
- Throttles test execution speed
Correct answer: Replaces native timer functions to control time in tests
`jasmine.clock().install()` replaces `setTimeout` and `setInterval` with controllable fakes, letting you tick time manually.
Question 6: Which configuration option sets the timeout for async specs in Jasmine?
- jasmine.DEFAULT_TIMEOUT_INTERVAL (Correct answer)
- jasmine.asyncTimeout
- jasmine.config.timeout
- jasmine.specTimeout
Correct answer: jasmine.DEFAULT_TIMEOUT_INTERVAL
`jasmine.DEFAULT_TIMEOUT_INTERVAL` (default 5000ms) determines how long Jasmine waits for an async spec to complete.
Question 7: What does `toHaveBeenCalled()` verify about a spy?
- The spy returned a truthy value
- The spy was invoked at least once (Correct answer)
- The spy was invoked exactly once
- The spy was invoked with no arguments
Correct answer: The spy was invoked at least once
`toHaveBeenCalled()` passes as long as the spy was called one or more times, regardless of arguments.
What does `spy.and.callThrough()` do?