Jasmine JavaScript Testing Framework — Questions and Answers
Question 1: Which Jasmine function is used to specify a test suite?
- `describe()` (Correct answer)
- `test()`
- `suite()`
- `it()`
Correct answer: `describe()`
In Jasmine, the `describe()` function is used to define a test suite, which is a collection of related test specifications. It takes a string description and a function containing the test specs, organizing tests into logical groups for better readability and structure.
Question 2: How do you assert that a Jasmine spy was never called?
- expect(spy).neverCalled()
- spy.calls.none()
- expect(spy).not.toHaveBeenCalled() (Correct answer)
- expect(spy).toNotHaveBeenCalled()
Correct answer: expect(spy).not.toHaveBeenCalled()
Prefixing the toHaveBeenCalled() matcher with .not negates it, asserting zero invocations.
Question 3: How do you use async/await syntax in a Jasmine it() block?
- Wrap the function in jasmine.async()
- Return jasmine.awaitAll() at the end
- Declare the function as async and use await inside (Correct answer)
- Pass done and call it after each await
Correct answer: Declare the function as async and use await inside
Jasmine supports native async functions; simply declare the callback as async and use await normally.
Question 4: What does jasmine.addAsyncMatchers() enable compared to jasmine.addMatchers()?
- Registers matchers that can be chained
- Registers matchers for use in async/await specs only
- Registers matchers whose compare function returns a Promise (Correct answer)
- Registers matchers that auto-retry on failure
Correct answer: Registers matchers whose compare function returns a Promise
jasmine.addAsyncMatchers() registers matchers whose compare function can return a Promise, allowing asynchronous checks inside expectAsync() calls.
Question 5: How can you create a Jasmine spy for a standalone function (not a method)?
- jasmine.createSpyObj(['functionName'])
- jasmine.createSpy('name') (Correct answer)
- new jasmine.Spy('name')
- spyOn(window, 'functionName')
Correct answer: jasmine.createSpy('name')
`jasmine.createSpy()` creates a bare spy function not attached to any object.
Question 6: Which Jasmine matcher asserts that a number exceeds another number?
- toSurpass(n)
- toBeGreaterThan(n) (Correct answer)
- toExceed(n)
- toBeAbove(n)
Correct answer: toBeGreaterThan(n)
toBeGreaterThan(n) passes when the actual value is strictly greater than n using the > operator.
Question 7: What happens when you call spyOn on a property that does not exist on the object?
- It silently creates the property as a spy
- It logs a warning to the console
- Jasmine throws an error (Correct answer)
- It ignores the call and continues
Correct answer: Jasmine throws an error
Jasmine requires the property to exist on the object before you can spy on it, and throws if it doesn't.
Question 8: What does chaining .not before a Jasmine matcher do?
- Negates the matcher so the test passes when the condition is false (Correct answer)
- Creates a spy that inverts the matched return value
- Skips the assertion without recording a result
- Logs a warning if the condition would have passed
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.
Question 9: Which matcher verifies that a number is close to an expected value within a decimal precision?
- toBeNear(num, range)
- toBeWithin(min, max)
- toBeCloseTo(num, decimalPlaces) (Correct answer)
- toApproximate(num, tolerance)
Correct answer: toBeCloseTo(num, decimalPlaces)
toBeCloseTo(num, decimalPlaces) checks that |actual - expected| < 10^(-decimalPlaces) / 2.
Question 10: What does `spy.calls.mostRecent()` return?
- Only the arguments of the last call
- An object with `object` and `args` properties for the last call (Correct answer)
- The number of the most recent call
- The return value of the last call
Correct answer: An object with `object` and `args` properties for the last call
`calls.mostRecent()` returns a call object containing `object` (context), `args`, and `returnValue` for the latest invocation.
Question 11: How do you set a custom timeout for a single it() block in Jasmine?
- Pass the timeout as a third argument: it('desc', fn, timeout) (Correct answer)
- Use it('desc', {timeout: ms}, fn)
- Call jasmine.setTimeout(timeout) inside the block
- Use it.timeout('desc', fn, timeout)
Correct answer: Pass the timeout as a third argument: it('desc', fn, timeout)
Jasmine's it() accepts an optional third argument (timeout in ms) that overrides the default for that spec only.
Question 12: How do you handle async testing with Promises in Jasmine?
- Call done() inside the Promise .then()
- Use jasmine.whenResolved() on the Promise
- Wrap the Promise with jasmine.promise()
- Return the Promise from the it() block (Correct answer)
Correct answer: Return the Promise from the it() block
When it() returns a Promise, Jasmine awaits its resolution or rejection to determine pass or fail.
Question 13: What argument types does jasmine.stringMatching() accept?
- A string or a RegExp (Correct answer)
- A string and a flags object
- Only a RegExp
- Only a string
Correct answer: A string or a RegExp
jasmine.stringMatching() accepts either a string (checks for substring match) or a RegExp (checks against the pattern), making it a flexible asymmetric matcher.
Question 14: How do you activate Jasmine's mock clock before a test?
- jasmine.useFakeTimers()
- jasmine.clock().mock()
- jasmine.clock().install() (Correct answer)
- jasmine.clock().start()
Correct answer: jasmine.clock().install()
install() activates the mock clock, replacing the browser/Node timer functions with Jasmine's controlled versions.
Question 15: Which approach correctly checks that a spy was called exactly two times?
- expect(spy.calls.count()).toBe(2)
- expect(spy).toHaveBeenCalledTimes(2)
- expect(spy).calledTwice()
- Both A and B are valid (Correct answer)
Correct answer: Both A and B are valid
Jasmine supports both the toHaveBeenCalledTimes matcher and manually asserting spy.calls.count() with toBe.
Question 16: What does spy.calls.allArgs() return?
- An array of argument arrays, one per call (Correct answer)
- The arguments from the first call only
- A flattened array of all individual arguments
- The count of arguments passed across all calls
Correct answer: An array of argument arrays, one per call
allArgs() returns [[arg1, arg2], [arg1, arg2], ...] — one inner array per recorded invocation.
Question 17: What does `jasmine.stringMatching()` accept as its argument?
- Only a RegExp object
- A string or regular expression to match against (Correct answer)
- A function that returns a boolean
- Only an exact string for strict equality
Correct answer: A string or regular expression to match against
`jasmine.stringMatching()` accepts either a substring or a RegExp and checks the actual value against it.
Question 18: Which of the following is NOT a valid technique for writing async Jasmine tests?
- Using async/await in the spec
- Returning a Promise from the spec
- Wrapping the spec in jasmine.async() (Correct answer)
- Using a done callback parameter
Correct answer: Wrapping the spec in jasmine.async()
jasmine.async() is not a real Jasmine API; the three valid patterns are done callbacks, returned Promises, and async/await.
Question 19: Which matcher checks that a spy was called exactly once?
- toHaveBeenCalledTimes(1) (Correct answer)
- toHaveBeenCalledSingle()
- toHaveBeenCalledCount(1)
- toHaveBeenCalledOnce()
Correct answer: toHaveBeenCalledTimes(1)
toHaveBeenCalledTimes(n) asserts the spy was invoked exactly n times.
Question 20: What is the purpose of jasmine.getEnv().clearReporters()?
- Removes all currently registered reporters from the environment (Correct answer)
- Disables only the default ConsoleReporter
- Clears the output buffer of the active reporter
- Resets reporter statistics without removing reporters
Correct answer: Removes all currently registered reporters from the environment
clearReporters() removes every registered reporter, which is useful when you want to install only a custom reporter without the default output.
Question 21: What must a custom matcher factory function return?
- An object with a compare function (Correct answer)
- A string describing the matcher
- A Promise
- A boolean value
Correct answer: An object with a compare function
A custom matcher factory returns an object that must include a compare function, which Jasmine calls with the actual and expected values.
Question 22: 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 arrays
- Matches only objects with exactly those properties
- 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 23: What must you do after each test that installed the Jasmine clock mock?
- Call jasmine.clock().restore()
- Call jasmine.clock().uninstall() (Correct answer)
- Call jasmine.clock().stop()
- Call jasmine.clock().reset()
Correct answer: Call jasmine.clock().uninstall()
uninstall() removes the mock clock and restores the real timer functions, preventing leakage into subsequent tests.
Question 24: What does jasmine.clock().mockDate(new Date('2025-01-01')) do?
- Schedules a callback to fire on January 1, 2025
- Returns a fixed timestamp for use in assertions
- Creates a Date spy that returns the given date
- Sets the mocked current date to January 1, 2025 (Correct answer)
Correct answer: Sets the mocked current date to January 1, 2025
mockDate() overrides new Date() and Date.now() so they return the specified date during the test.
Question 25: How do you run only a specific `describe` block in Jasmine while skipping all others?
- Change `describe` to `fdescribe` (Correct answer)
- Change `describe` to `xdescribe`
- Use `jasmine.focus('suiteName')`
- Add `.only` to the describe call
Correct answer: Change `describe` to `fdescribe`
`fdescribe` (focused describe) causes Jasmine to run only that suite and skip all unfocused specs.
Question 26: Which Jasmine method would you use to verify that a value satisfies a custom asymmetric matcher when it is used as an expected argument inside toHaveBeenCalledWith()?
- Call jasmine.expect() with the asymmetric matcher
- Register the matcher with jasmine.addSpyMatcher()
- Pass the asymmetric matcher instance directly as the expected argument to toHaveBeenCalledWith() (Correct answer)
- Wrap it with jasmine.matcherFor()
Correct answer: Pass the asymmetric matcher instance directly as the expected argument to toHaveBeenCalledWith()
Asymmetric matchers (including custom ones with asymmetricMatch) can be passed directly as expected values inside toHaveBeenCalledWith(), and Jasmine will call asymmetricMatch() for comparison.
Question 27: What does done.fail('reason') do inside a Jasmine async test?
- Immediately fails the test with the provided reason (Correct answer)
- Stops execution without recording a failure
- Causes Jasmine to retry the test
- Logs the reason and continues running
Correct answer: Immediately fails the test with the provided reason
done.fail() is the mechanism for failing an async test from within a callback when an unexpected condition is detected.
Question 28: How do you configure a Jasmine spy to invoke the original implementation?
- .and.passThrough()
- .and.original()
- .and.delegate()
- .and.callThrough() (Correct answer)
Correct answer: .and.callThrough()
callThrough() tells the spy to forward the call to the real method while still tracking it.
Question 29: How does Jasmine handle asynchronous specs that use `done`?
- You must return a Promise; `done` is deprecated
- The spec fails immediately if async code runs
- Jasmine ignores async callbacks by default
- Jasmine waits until `done()` is called before marking the spec complete (Correct answer)
Correct answer: Jasmine waits until `done()` is called before marking the spec complete
When a spec function declares `done` as a parameter, Jasmine waits for `done()` to be called before finishing the spec.
Question 30: Which of the following commands controls the Jasmine Clock, which you can use to control how much time passes during your tests?
- Jasmine.Clock() (Correct answer)
- toBeClock ()
- Clock ()
Correct answer: Jasmine.Clock()
`jasmine.clock()` is the object used to control Jasmine's mock clock functionality. It allows developers to manage and advance time within tests, which is essential for testing asynchronous code that relies on `setTimeout`, `setInterval`, or `Date` objects. By controlling the clock, tests can run much faster and more predictably.
Question 31: After installing the Jasmine clock mock, how do you advance time by 1000ms?
- jasmine.clock().tick(1000) (Correct answer)
- jasmine.clock().advance(1000)
- jasmine.clock().skip(1000)
- jasmine.clock().run(1000)
Correct answer: jasmine.clock().tick(1000)
tick(ms) synchronously advances the mocked clock by the given milliseconds, triggering any due timers.
Question 32: How can you verify that a spy was called with specific arguments?
- expect(spy.args).toContain(arg)
- expect(spy).toHaveBeenCalledWith(arg) (Correct answer)
- spy.toHaveBeenCalledWith(arg)
- spy.calls.verify(arg)
Correct answer: expect(spy).toHaveBeenCalledWith(arg)
The `toHaveBeenCalledWith` matcher is used on the spy wrapped in `expect()` to assert specific call arguments.
Question 33: How do you add a custom matcher available in all specs of a suite?
- jasmine.addMatchers({matcherName: factory}) (Correct answer)
- jasmine.customMatcher(name, fn)
- jasmine.extend({matcherName: fn})
- jasmine.createMatcher(name, fn)
Correct answer: jasmine.addMatchers({matcherName: factory})
addMatchers() in beforeEach() registers custom matchers whose factory returns compare and negativeCompare methods.
Question 34: What does calling `pending()` inside a Jasmine spec do?
- Fails the spec
- Skips subsequent describes only
- Logs a warning and continues
- Marks the spec as pending regardless of other assertions (Correct answer)
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 35: To see if any variables were previously undefined, ___ check.
- toUndefined()
- toBeUndefined () (Correct answer)
- toBeNotDefined ()
Correct answer: toBeUndefined ()
The `toBeUndefined()` matcher in Jasmine is used to assert that a variable or property currently holds the value `undefined`. This is distinct from `null` or other falsy values and is specifically useful for verifying that a variable has not been assigned a value or that a property does not exist on an object.
Question 36: How does Jasmine report a spec created with xit() or by calling pending() inside it()?
- As a success with an informational note
- As completely skipped with no entry in results
- As 'pending' in the results output (Correct answer)
- As a failure with a pending message
Correct answer: As 'pending' in the results output
Jasmine tracks pending specs separately and reports them as 'pending' so developers know they exist but haven't been implemented.
Question 37: Which expression retrieves the arguments from the most recent spy call?
- spy.recentCall.args
- spy.lastArgs
- spy.calls.mostRecent().args (Correct answer)
- spy.calls.last().arguments
Correct answer: spy.calls.mostRecent().args
spy.calls.mostRecent() returns the call object for the latest invocation, and .args holds its argument array.
Question 38: What is the recommended way to test a rejected Promise in Jasmine?
- Use expectAsync(promise).toBeRejected()
- Both A and B are valid approaches (Correct answer)
- Return the Promise with a .catch that calls done.fail()
- Use jasmine.rejectPromise(promise)
Correct answer: Both A and B are valid approaches
Both returning a Promise with .catch/done.fail and using the expectAsync async matcher are valid Jasmine patterns.
Question 39: Which property on a Jasmine call object holds the value the spy returned?
- .returnValue (Correct answer)
- .returned
- .value
- .result
Correct answer: .returnValue
Each call object in spy.calls has a returnValue property storing whatever that invocation returned.
Question 40: In the custom matcher compare function signature compare(actual, expected), what does 'actual' represent?
- The Jasmine environment object
- The value passed to the matcher call
- The test description string
- The value passed to expect() (Correct answer)
Correct answer: The value passed to expect()
The 'actual' parameter in the compare function receives whatever value was passed into expect(), while 'expected' receives arguments from the matcher call itself.
Question 41: How should the message property be structured in a custom matcher result object to provide context-sensitive failure output?
- As a template literal with embedded expressions
- As a function that returns a string, so Jasmine evaluates it only when needed (Correct answer)
- As a static string set at matcher registration time
- As an array of possible messages
Correct answer: As a function that returns a string, so Jasmine evaluates it only when needed
The message property should be a function returning a string, allowing Jasmine to lazily evaluate it only when the spec fails and avoiding unnecessary string construction.
Question 42: When you define a custom matcher with jasmine.addMatchers() inside a beforeEach, in which scope are those matchers available?
- Only in the first it block
- Only within the describe block that contains the beforeEach (Correct answer)
- Globally across all specs in the file
- Only in the afterEach of the same describe
Correct answer: Only within the describe block that contains the beforeEach
Custom matchers registered in a beforeEach are scoped to the describe block containing that beforeEach; they are not inherited by outer or sibling suites.
Question 43: What function creates a spy on an existing object method in Jasmine?
- interceptMethod(obj, 'method')
- createSpy(obj, 'method')
- spyOn(obj, 'method') (Correct answer)
- mockMethod(obj, 'method')
Correct answer: spyOn(obj, 'method')
spyOn(obj, 'method') replaces the named method on obj with a Jasmine spy that tracks calls.
Question 44: What comparison operator does toBe() use internally?
- Loose equality (==)
- Object.is() only for primitives
- Deep equality
- Strict equality (===) (Correct answer)
Correct answer: Strict equality (===)
toBe() uses === (strict equality) under the hood, so it checks both value and type for primitives and reference identity for objects.
Question 45: What does the helpers option in jasmine.json specify?
- Utility functions exported to all specs automatically
- Override values that augment the main jasmine.json
- Glob patterns for files loaded before any spec files run (Correct answer)
- Fixture data files loaded for each spec
Correct answer: Glob patterns for files loaded before any spec files run
helpers are loaded after the Jasmine framework but before spec files, making them ideal for setting up custom matchers or global configuration.
Question 46: How do you reset all recorded call data for a Jasmine spy?
- spy.calls.reset() (Correct answer)
- spy.reset()
- spy.clearCalls()
- spy.calls.clear()
Correct answer: spy.calls.reset()
spy.calls.reset() clears the internal call log so count, args, and other tracking data start fresh.
Question 47: What does toContain() verify when used with an array?
- That the array has the specified length
- That the array has no duplicate elements
- That the array includes the specified element (Correct answer)
- That the array starts with the specified element
Correct answer: That the array includes the specified element
toContain() scans the array for an element that strictly equals the expected value using ===.
Question 48: Which spy configuration method executes a custom function when the spy is called?
- .and.run(fn)
- .and.callFake(fn) (Correct answer)
- .and.execute(fn)
- .and.invoke(fn)
Correct answer: .and.callFake(fn)
callFake(fn) replaces the spy's implementation with the provided function, which runs on each invocation.
Question 49: What does .and.throwError('msg') do when configured on a Jasmine spy?
- Makes the spy throw an Error with that message when called (Correct answer)
- Marks the spy as expected to throw
- Catches errors thrown inside the real method
- Logs the message to the console on each call
Correct answer: Makes the spy throw an Error with that message when called
throwError('msg') configures the spy to throw a new Error with the given message every time it is invoked.
Question 50: What does jasmine.createSpy('myMethod') create?
- A standalone spy function not attached to any object (Correct answer)
- A spy placed on the global window object
- A configured HTTP request interceptor
- A spy that intercepts all method calls in the suite
Correct answer: A standalone spy function not attached to any object
createSpy produces an independent spy function you can pass as a callback or stub without needing a host object.
Question 51: Which property returns the number of times a Jasmine spy was called?
- spy.callCount
- spy.invocationCount
- spy.times()
- spy.calls.count() (Correct answer)
Correct answer: spy.calls.count()
spy.calls.count() is the method on the calls object that returns the total invocation count.
Jasmine JavaScript Testing Framework
A skills assessment covering the Jasmine BDD testing framework for JavaScript, including test suites, matchers, spies, mocking, and asynchronous testing patterns. Tests practical knowledge of writing and organizing unit tests with Jasmine.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds