Jasmine JavaScript Testing Framework Jasmine JavaScript Knowledge 4 — Questions and Answers
Question 1: Which built-in Jasmine matcher checks that a value is strictly equal using `===`?
- toBe() (Correct answer)
- toEqual()
- toStrictEqual()
- toMatch()
Correct answer: toBe()
toBe() uses strict equality (===), making it ideal for primitives and object reference checks.
Question 2: What is the difference between `toEqual()` and `toBe()` in Jasmine?
- toEqual() does deep equality; toBe() checks reference/strict equality (Correct answer)
- They are identical
- toBe() does deep equality; toEqual() checks reference
- toEqual() only works on arrays
Correct answer: toEqual() does deep equality; toBe() checks reference/strict equality
toEqual() recursively compares object properties, while toBe() checks that both sides are the same object in memory.
Question 3: Which matcher would you use to verify a string contains a specific substring?
- toContain() (Correct answer)
- toInclude()
- toHaveSubstring()
- toMatch() with a plain string
Correct answer: toContain()
toContain() checks whether a string includes the given substring, or an array includes a given element.
Question 4: How do you negate any Jasmine matcher?
- expect(value).not.matcher() (Correct answer)
- expect(value).negate.matcher()
- expect.not(value).matcher()
- notExpect(value).matcher()
Correct answer: expect(value).not.matcher()
Chaining .not before any matcher inverts its assertion, e.g., expect(x).not.toBe(null).
Question 5: Which matcher verifies that a function throws an error when invoked?
- toThrow() (Correct answer)
- toError()
- toThrowError()
- toFail()
Correct answer: toThrow()
toThrow() (or the more specific toThrowError()) asserts that the wrapped function throws when called.
Question 6: What does `jasmine.objectContaining({key: value})` do when used inside a matcher?
- Matches any object that has at least the specified key-value pairs (Correct answer)
- Matches only objects with exactly those properties
- Matches only arrays
- Throws a type error
Correct answer: Matches any object that has at least the specified key-value pairs
jasmine.objectContaining() is an asymmetric matcher that passes if the object has at least the given properties, ignoring extras.
Question 7: Which Jasmine asymmetric matcher is used to check that a value matches a regular expression without using `toMatch()`?
- jasmine.stringMatching() (Correct answer)
- jasmine.regexMatch()
- jasmine.matchRegex()
- jasmine.pattern()
Correct answer: jasmine.stringMatching()
jasmine.stringMatching(regex) is an asymmetric equality tester that can be embedded in nested object matchers.
Which built-in Jasmine matcher checks that a value is strictly equal using `===`?