Jasmine JavaScript Testing Framework Jasmine Matchers and Expectations 2 — Questions and Answers
Question 1: Which Jasmine matcher checks that a string or value matches a regular expression?
- toMatch(regex) (Correct answer)
- toContain(regex)
- toBe(regex)
- toEqual(regex)
Correct answer: toMatch(regex)
toMatch() accepts a RegExp or string pattern and tests the actual value against it.
Question 2: What does toBeNull() specifically check?
- That the value is strictly null (Correct answer)
- That the value is null or undefined
- That the value is any falsy value
- That the value is an empty object
Correct answer: That the value is strictly null
toBeNull() uses === null, so it passes only for null and not for undefined or other falsy values.
Question 3: Which Jasmine matcher asserts that a number exceeds another number?
- toBeGreaterThan(n) (Correct answer)
- toBeAbove(n)
- toExceed(n)
- toSurpass(n)
Correct answer: toBeGreaterThan(n)
toBeGreaterThan(n) passes when the actual value is strictly greater than n using the > operator.
Question 4: What role does jasmine.objectContaining({key: value}) play in an expectation?
- Partially matches an object that has at least those key-value pairs (Correct answer)
- Exactly matches only an object with exactly those properties
- Checks whether the object has more properties than listed
- Creates a spy that intercepts the listed properties
Correct answer: Partially matches an object that has at least those key-value pairs
objectContaining is an asymmetric matcher that passes if the actual object includes the listed properties, ignoring extras.
Question 5: Which matcher verifies that a function throws an error whose message matches the given string or regex?
- toThrowError(messageOrRegex) (Correct answer)
- toThrowWith(messageOrRegex)
- toThrowMatching(messageOrRegex)
- toThrowMsg(messageOrRegex)
Correct answer: toThrowError(messageOrRegex)
toThrowError() can accept a string or regex to match against the thrown error's message property.
Question 6: What does chaining .not before a Jasmine matcher do?
- Negates the matcher so the test passes when the condition is false (Correct answer)
- Skips the assertion without recording a result
- Logs a warning if the condition would have passed
- Creates a spy that inverts the matched return value
Correct answer: Negates the matcher so the test passes when the condition is false
.not inverts the expected outcome of the matcher, so the spec passes when the matcher would otherwise fail.
Which Jasmine matcher checks that a string or value matches a regular expression?