Jasmine JavaScript Testing Framework Jasmine JavaScript for Beginner's 2 — Questions and Answers
Question 1: What does the `beforeAll` function do in a Jasmine test suite?
- Runs once before all specs in a describe block (Correct answer)
- Runs before each individual spec
- Runs after all specs complete
- Defines a new test suite
Correct answer: Runs once before all specs in a describe block
`beforeAll` executes a setup function exactly once before any specs in the describe block run.
Question 2: Which matcher checks that a value is strictly `undefined`?
- toBeNull()
- toBeUndefined() (Correct answer)
- toBeFalsy()
- not.toBeDefined()
Correct answer: toBeUndefined()
`toBeUndefined()` specifically checks that the actual value is `=== undefined`.
Question 3: How do you skip a `describe` block without deleting it?
- skip.describe()
- xdescribe() (Correct answer)
- describe.skip()
- pending.describe()
Correct answer: xdescribe()
Prefixing `describe` with `x` (i.e., `xdescribe`) disables the entire suite without removing code.
Question 4: What is the purpose of `jasmine.createSpy('name')`?
- Creates a full mock object with methods
- Creates a standalone spy function not attached to any object (Correct answer)
- Watches an existing object method
- Asserts that a function was called
Correct answer: Creates a standalone spy function not attached to any object
`jasmine.createSpy` returns a bare spy function useful when no existing object method needs to be tracked.
Question 5: Which Jasmine method makes a spec report as pending with a reason?
- skip('reason')
- xdescribe('reason')
- pending('reason') (Correct answer)
- ignore('reason')
Correct answer: pending('reason')
Calling `pending('reason')` inside a spec marks it as pending and displays the provided reason in the report.
Question 6: What does `toEqual` do differently from `toBe` when comparing objects?
- toEqual checks reference equality; toBe checks deep equality
- toEqual checks deep equality; toBe checks reference equality (Correct answer)
- They are identical for objects
- toEqual ignores undefined properties; toBe does not
Correct answer: toEqual checks deep equality; toBe checks reference equality
`toEqual` performs a deep recursive comparison of object properties, while `toBe` uses strict (`===`) reference equality.
Question 7: How can you verify that a spy was called with specific arguments?
- spy.toHaveBeenCalledWith(arg)
- expect(spy).toHaveBeenCalledWith(arg) (Correct answer)
- spy.calls.verify(arg)
- expect(spy.args).toContain(arg)
Correct answer: expect(spy).toHaveBeenCalledWith(arg)
The `toHaveBeenCalledWith` matcher is used on the spy wrapped in `expect()` to assert specific call arguments.
What does the `beforeAll` function do in a Jasmine test suite?