Jasmine JavaScript Testing Framework Jasmine Matchers and Expectations 3 — Questions and Answers
Question 1: What does jasmine.arrayContaining([3, 5]) verify about the actual array?
- The actual array contains at least 3 and 5 (possibly more) (Correct answer)
- The actual array equals exactly [3, 5]
- The actual array has a length equal to the number of elements listed
- The actual array starts with 3 and ends with 5
Correct answer: The actual array contains at least 3 and 5 (possibly more)
arrayContaining is an asymmetric matcher that passes when all listed elements appear in the actual array in any order.
Question 2: Which Jasmine matcher checks that a number is less than or equal to another?
- toBeLessThanOrEqualTo(n) (Correct answer)
- toBeAtMost(n)
- toNotExceed(n)
- toBeLessOrEqual(n)
Correct answer: toBeLessThanOrEqualTo(n)
toBeLessThanOrEqualTo(n) uses <= and is the counterpart to toBeGreaterThanOrEqualTo(n).
Question 3: What does toBeInstanceOf(ClassName) verify?
- That the actual value was created with the given constructor (Correct answer)
- That the value has the class's static methods
- That the value's constructor name is a string match
- That the value shares prototype methods with the class
Correct answer: That the actual value was created with the given constructor
toBeInstanceOf() uses the instanceof operator to verify the actual value was constructed by the given class.
Question 4: How do you add a custom matcher available in all specs of a suite?
- jasmine.addMatchers({matcherName: factory}) (Correct answer)
- jasmine.createMatcher(name, fn)
- jasmine.customMatcher(name, fn)
- jasmine.extend({matcherName: fn})
Correct answer: jasmine.addMatchers({matcherName: factory})
addMatchers() in beforeEach() registers custom matchers whose factory returns compare and negativeCompare methods.
Question 5: What does jasmine.stringMatching(regex) do when used as an asymmetric matcher?
- Matches any string that satisfies the regex or contains the substring (Correct answer)
- Matches a string that is identical to the regex source
- Creates a spy on all string method calls
- Converts the regex into a matcher function for arrays
Correct answer: Matches any string that satisfies the regex or contains the substring
stringMatching is an asymmetric matcher that passes when the actual string matches the given regex or contains the given substring.
Question 6: Which Jasmine matcher passes for any JavaScript truthy value?
- toBeTruthy() (Correct answer)
- toBeTrue()
- toBeDefined()
- toBePositive()
Correct answer: toBeTruthy()
toBeTruthy() passes for any value that coerces to true, while toBeTrue() requires the value to be exactly the boolean true.
What does jasmine.arrayContaining([3, 5]) verify about the actual array?