Jasmine JavaScript Testing Framework Jasmine Matchers and Expectations 1 — Questions and Answers
Question 1: Which Jasmine matcher performs a deep equality check between two objects?
- toEqual() (Correct answer)
- toBe()
- toMatch()
- toContain()
Correct answer: toEqual()
toEqual() recursively compares all properties of objects, while toBe() uses strict reference equality.
Question 2: What comparison operator does toBe() use internally?
- Strict equality (===) (Correct answer)
- Deep equality
- Loose equality (==)
- Object.is() only for primitives
Correct answer: Strict equality (===)
toBe() uses === (strict equality) under the hood, so it checks both value and type for primitives and reference identity for objects.
Question 3: Which Jasmine matcher checks that a value is not undefined?
- toBeDefined() (Correct answer)
- toExist()
- toBePresent()
- toHaveValue()
Correct answer: toBeDefined()
toBeDefined() passes when the actual value is anything other than undefined.
Question 4: What does toContain() verify when used with an array?
- That the array includes the specified element (Correct answer)
- That the array has the specified length
- That the array starts with the specified element
- That the array has no duplicate elements
Correct answer: That the array includes the specified element
toContain() scans the array for an element that strictly equals the expected value using ===.
Question 5: Which matcher verifies that a number is close to an expected value within a decimal precision?
- toBeCloseTo(num, decimalPlaces) (Correct answer)
- toBeNear(num, range)
- toBeWithin(min, max)
- toApproximate(num, tolerance)
Correct answer: toBeCloseTo(num, decimalPlaces)
toBeCloseTo(num, decimalPlaces) checks that |actual - expected| < 10^(-decimalPlaces) / 2.
Question 6: What does toThrow() verify about a function passed to expect()?
- That the function throws any exception when called (Correct answer)
- That the function throws a specific error type
- That the function throws with a specific message
- That the function never completes execution
Correct answer: That the function throws any exception when called
toThrow() with no arguments passes as long as the function throws anything at all; use toThrowError() for specifics.
Which Jasmine matcher performs a deep equality check between two objects?