Jasmine JavaScript Testing Framework Jasmine JavaScript Knowledge 5 — Questions and Answers
Question 1: What is the purpose of `beforeAll` in Jasmine?
- Runs setup code once before all specs in a describe block (Correct answer)
- Runs before every individual spec
- Marks all specs as pending
- Defines shared variables only
Correct answer: Runs setup code once before all specs in a describe block
beforeAll executes its callback exactly once before any spec inside the enclosing describe runs.
Question 2: How does `afterAll` differ from `afterEach` in Jasmine?
- afterAll runs once after all specs; afterEach runs after every spec (Correct answer)
- They are interchangeable
- afterEach runs after the suite; afterAll runs after each spec
- afterAll only runs if all specs pass
Correct answer: afterAll runs once after all specs; afterEach runs after every spec
afterAll is a single teardown that fires after the last spec in the suite, while afterEach fires after each individual spec.
Question 3: What does the `xdescribe` function do in Jasmine?
- Disables all specs inside the describe block (Correct answer)
- Skips only the first spec
- Marks the suite as focused
- Throws a syntax error
Correct answer: Disables all specs inside the describe block
xdescribe marks an entire describe block as pending, so all specs inside are skipped without being removed.
Question 4: Which function marks a single spec as focused so only it runs in a suite?
- fit() (Correct answer)
- only()
- focus()
- fspec()
Correct answer: fit()
fit() (focused it) causes Jasmine to run only that spec and skip all non-focused specs in the suite.
Question 5: What does calling `pending()` inside a Jasmine spec do?
- Marks the spec as pending regardless of other assertions (Correct answer)
- Fails the spec
- Skips subsequent describes only
- Logs a warning and continues
Correct answer: Marks the spec as pending regardless of other assertions
Calling pending() anywhere in a spec immediately marks it as pending and stops execution of that spec.
Question 6: When using nested `describe` blocks, in what order do `beforeEach` hooks run?
- Outer beforeEach runs first, then inner beforeEach (Correct answer)
- Inner beforeEach runs first, then outer
- Only the innermost beforeEach runs
- Order is random
Correct answer: Outer beforeEach runs first, then inner beforeEach
Jasmine executes beforeEach hooks from the outermost describe inward before each spec in nested suites.
Question 7: What is the Jasmine `this` context shared between `beforeEach`, `afterEach`, and `it` within the same describe?
- A fresh empty object per spec that all three callbacks share (Correct answer)
- The global window object
- The describe suite object
- Undefined in strict mode
Correct answer: A fresh empty object per spec that all three callbacks share
Jasmine creates a new plain object for each spec and passes it as `this` to beforeEach, it, and afterEach so they can share state.
What is the purpose of `beforeAll` in Jasmine?