jasmine/jasmine
github.com/jasmine/jasmine ↗ · 415 files · 2.0 MB
A JavaScript Testing Framework Jasmine is a Behavior Driven Development testing framework for JavaScript.
Overview
Jasmine is a JavaScript behavior-driven testing framework for developers writing browser and Node.js tests. This repository publishes jasmine-core 7.0.2: the test declaration APIs, execution engine, matchers, spies, mock clock, and browser HTML reporter. Its distinctive architecture combines environment-independent factories with browser-specific reporting, and tests source implementations using a separately loaded distributable copy of Jasmine.
System map
The package boundary is jasmine-core, with a CommonJS entrypoint and browser distributables generated from source. Core factories separate public Jasmine APIs from private execution machinery, while HTML factories add browser reporting. State belongs to an environment and its suites, specs, and runnable resources; filesystem activity occurs in packaging and development tooling.
- package.json declares jasmine-core 7.0.2, exports only the root CommonJS entrypoint, and limits published content to the license, README, images, lib JavaScript/CSS, and package metadata.
- The Node entrypoint loads the bundled globals, installGlobals, reset, and version, then synchronously discovers browser asset filenames beneath its installed jasmine-core directory.
- requireCore.core constructs separate jasmine and private namespaces and wires Configuration, Env, Runner, TreeRunner, QueueRunner, spies, equality tools, and matcher factories.
- bootJasmine creates the environment and interface; Node exports the booted instance with load errors suppressed, whereas browser loading installs globals immediately.
- Env owns configuration, global-error installation, scoped resources, SuiteBuilder, ReportDispatcher, and Runner; jasmine.getEnv caches the current environment.
- HTML assembly installs private view factories and exposes HtmlReporterV2Urls, HtmlReporterV2, and QueryString as non-writable additions to the Jasmine namespace.
- buildDistribution compiles Sass, embeds image assets, concatenates ordered factory sources, renders version/license templates, and writes four JavaScript distribution targets.
- Repository scripts provide Node tests, parallel tests, browser serving/CI, lint, builds, and standalone archives; browser automation optionally connects to a Sauce Labs Selenium grid.
Feature catalog
The primary user interface is a JavaScript API for declaring suites, executing specifications, and evaluating expectations. Testing tools include synchronous and asynchronous matchers, scoped customization, spies, and simulated time. Browser users receive result navigation, failure details, configuration controls, and duration summaries.
- describe/it define nested suites and specs; xdescribe/xit disable them, and fdescribe/fit focus execution. Hooks include beforeEach, afterEach, beforeAll, and afterAll.
- Registered synchronous matchers cover identity, deep equality, numeric comparisons, truthiness, nullish values, containment, size, DOM classes, spy interactions, regular expressions, and thrown errors.
- expectAsync supports pending/resolved/rejected promise checks; expectation modifiers include not, withContext, and already, and asynchronous matcher results must be awaited or returned.
- Asymmetric helpers provide partial object/array matching and string containment or pattern matching; MatchersUtil invokes an object's asymmetricMatch method for custom asymmetric comparisons.
- Env exposes method/property/all-function spying and spy-object creation; SpyStrategy supports call-through, fake implementations, sequential return values, thrown errors, and resolved/rejected promises.
- The mock clock replaces timeout/interval functions, optionally mocks Date, supports manual tick and autoTick, and offers withMock cleanup through a finally block.
- Configuration controls randomization and seed, stopping on failures, empty-expectation failures, duplicate names, closure cleanup, late rejection detection, and Safari yielding; Env also exposes pending/notApplicable reasons, properties, and debug logs.
- HtmlReporterV2 offers Spec List, Failures, and Performance tabs, rerun links, seed links, progress, and failure messages/stacks; PerformanceView shows mean, a sorted-array median selection, and at most 20 slowest specs.
Data flow
Spec definitions become an in-memory suite tree, then configuration transforms that tree into an execution plan. Expectations and exceptions update runnable-owned execution state, which is converted into reporter events. Browser result state feeds DOM views, while rerun settings cross reloads through URL parameters.
- Global declaration functions delegate to Env, which rejects declarations during execution, derives the caller filename, and returns metadata from SuiteBuilder-created suites/specs.
- SuiteBuilder tracks the current declaration suite and sequential IDs; specFactory_ captures hooks, configuration flags, path generation, timeout, and cloned suite user context into each Spec.
- Runner chooses explicit runnable IDs, focused IDs, or the top suite, then supplies seeded child ordering and specFilter(metadata) exclusion to TreeProcessor.processTree.
- Runnable resources shallow-copy parent customization tables and arrays into child scope; completion removes the error override, restores spies, and deletes that runnable's resources.
- Env.expect binds actual values and scoped matchers to the current runnable; Expector instantiates the matcher, compares arguments, builds a message, and calls Spec.addExpectationResult.
- Spec stores passed/failed expectations, duration, reasons, properties, and debug logs; doneEvent exposes these fields, and ReportDispatcher structured-clones each event separately for each reporter.
- ResultsStateBuilder builds a parent-linked result tree and counters from suite/spec events; HtmlReporterV2 renders summary and performance views at jasmineDone, and failure strings become text nodes.
- Rerun links serialize suite/spec paths into the path query parameter; QueryString URI-encodes parameters, and the next boot reconstructs configuration and prefix-path or substring filtering from window.location.
Behavior traces
The inspected flows cover Node initialization/reset, browser startup/reruns, spec execution/assertions, and distribution creation. Their order is visible in the source, including branching for focus, exclusions, callback versus promise execution, and suite failures. These are static traces rather than observed execution results.
- Node startup: the package entrypoint requires jasmine.js -> bootJasmine calls core -> jasmine.getEnv creates/caches Env -> interface binds API closures -> module exports globals; installGlobals explicitly copies them to a destination.
- Node reset: reset clears private$.currentEnv_ -> creates an environment with suppressed load errors -> rebindEnv updates the existing API closures; the reset fixture checks new environment identity and declaration routing.
- Browser startup: boot gets Env -> HtmlReporterV2Urls parses current settings -> env.configure applies them -> wrapped window.onload invokes the previous handler -> constructs/adds the HTML reporter -> env.execute starts execution.
- Declaration and selection: describe immediately invokes its definition callback under a new declaration suite -> it attaches Spec children -> Env.execute installs error handling -> Runner builds the selected/ordered execution tree and awaits jasmineStarted.
- Spec execution: TreeRunner sets the current spec and initializes resources -> awaits specStarted -> runs inherited befores, the spec, and afters -> executionFinished sets duration/status -> resources are cleared -> specDone is awaited; pending/excluded specs omit user functions.
- Async assertion: expectAsync creates a runnable-bound AsyncExpectation -> wrapAsyncCompare captures a stack and awaits comparison -> Expector.processResult records the result; if another runnable is current, Env additionally records a late-expectation failure on the top suite.
- Failure completion: suite execution uses stop-on-first-error or beforeAll-error skipping -> beforeAll failures generate descendant result events -> Runner reports failed, incomplete for focus/no specs, or passed -> awaits jasmineDone -> Env removes global handlers.
- Standalone artifact flow: buildStandaloneDist creates an OS temporary directory -> buildDistribution writes lib outputs -> EJS renders SpecRunner.html -> ZipArchive adds selected assets/examples -> close resolves completion -> finally removes the temporary directory.
Testing signals
Tests and CI definitions were inspected, not executed; no passing result is asserted. Jasmine self-tests with a compiled runner and a separate source implementation, using both component specs and integration specs. The inspected inventory is bounded: configuration and sampled tests establish intended coverage, not exhaustive coverage or successful CI execution.
- The self-test design loads lib as the executing jasmine and source as jasmineUnderTest/privateUnderTest; the contribution guide explicitly warns against leaking implementation-under-test behavior into the executing copy.
- The inspected Node test script loads core and npmPackage specs, checks that requiring jasmine-core creates no globals before installGlobals, maps overallStatus to exit code, and is followed by lint under npm test; it was not executed.
- Browser configuration includes all spec files except npmPackage and source core/HTML factories, while the Node configuration does not select spec/html; browser-only reporting therefore requires the separate browser checks.
- QueueRunner specs exercise delayed promise completion, rejected promises, and conflicting callback/promise declarations using StubPromise, spies, and a mock clock.
- Integration tests check nested-suite execution, hook order, load-time error reporting, and parallelReset removing previous batches while retaining top-level hooks.
- HTML specs inspect initial DOM and progress updates; QueryString and HtmlSpecFilterV2 specs check parameter preservation, URI decoding, exact/prefix paths, and substring filtering. These assertions alone do not establish full page-reload behavior.
- Package specs run npm pack and tar extraction, validate distributed filenames/content boundaries, and clean temporary artifacts; reset is tested in a subprocess. The inspected performance fixture deliberately creates 10,000 passing and 10,000 failing specs, rather than proving a speed threshold.
- Inspected CI definitions schedule Safari on macos-latest with Node 22, and CircleCI Node 20/22/24/26 serial/parallel jobs plus Windows and trusted-branch Sauce browser tests; these definitions were not executed or checked for green runs.
Risk map
The principal runtime boundaries are arbitrary test callbacks, global mutation, asynchronous completion, reporter cloning, and URL parsing. Development tooling additionally invokes shells, writes outside the checkout, and integrates with credential-bearing browser infrastructure. The observations below are source findings or labeled hypotheses, not confirmed vulnerabilities; inspection did not establish exhaustive security or test coverage.
- NodeAdapter temporarily removes all process listeners for uncaughtException, unhandledRejection, and rejectionHandled, then restores saved listeners on uninstall; Env.execute calls cleanup after awaited execution without a surrounding finally.
- Test functions execute directly in the host context via Function.call, and installGlobals assigns onto the chosen object; this execution boundary provides no callback isolation in the inspected path.
- Malformed URI escapes or invalid path JSON may interrupt browser configuration/selection because QueryString.decodeURIComponent and HtmlSpecFilterV2.JSON.parse lack local recovery. This is a static failure hypothesis, not a reproduced defect. (inferred)
- Late async results can outlive their originating runnable: Env diagnoses late expectations, but routeLateFailure can only log when all results have already been reported; QueueRunner separately detects conflicting async styles and repeated done calls.
- The standalone template requests boot0.js, while the standalone archive's framework asset list includes jasmine.js, jasmine-html.js, jasmine.css, and boot.js but no boot0.js; this is a source-level packaging mismatch.
- ci:performance passes jasmine-browser-performance.json, but ci.js always requires jasmine-browser.js and does not read process.argv; serve:performance uses a server script that does consume its filename argument.
- Package tests invoke npm pack and interpolated tar commands, load code from an OS temporary directory, and remove artifacts; standalone builds also create/remove temporary files. Running these checks exceeds a read-only source audit.
- Sauce configuration passes SAUCE_USERNAME and SAUCE_ACCESS_KEY to a remote grid, and CircleCI downloads/extracts a Sauce Connect executable before invoking tunnel scripts; the download stanza shows no checksum verification and the credential context excludes pull-request branches.
Extension points
Extension primarily happens through public customization APIs and explicit factory registries. Runnable-scoped tables control inheritance and teardown of custom matchers, equality testers, formatters, and spy strategies. Reporters and external runners are separate integration seams with cloning and process-boundary constraints.
- A new built-in matcher must expose a getJasmineRequireObj factory and join the synchronous or asynchronous availableMatchers list, which instantiates registered factories.
- Env.addMatchers/addAsyncMatchers populate current-runnable tables; Expectation and AsyncExpectation install instance methods using those custom factories.
- Custom equality testers join a scoped ordered list; MatchersUtil.eq_ consults asymmetric matchers first, then accepts the first custom tester result that is not undefined.
- Custom object formatters enter RunableResources and are passed into the pretty printer; makeMatchersUtil combines that printer with the current equality testers.
- addSpyStrategy and setDefaultSpyStrategy customize scoped SpyFactory behavior; custom strategy factories must return a function and cannot replace an existing SpyStrategy member.
- Reporters implement any subset of six lifecycle events and register through Env.addReporter; dispatch supports returned promises or done callbacks, isolates event objects by cloning, and supports a fallback reporter.
- Configuration.specFilter is an execution-selection hook, and requireCore deliberately allows new Jasmine namespace properties while locking existing members except four timeout/pretty-print settings.
- External parallel runners can use ParallelReportDispatcher and Env's parallel loading/reset methods; the dispatcher explicitly requires a process separate from running specs, and parallel Env mode restricts configuration, reporters, focus, and seeded/nonrandom execution.
Contributor handoff
Start with the source/distribution distinction and the two-copy self-test model before changing behavior. Preserve public API compatibility, browser independence in core, scoped cleanup, and reporter event contracts. Tests and CI were inspected, not executed; this handoff describes future verification options subject to authorization, and the inventory is bounded rather than exhaustive.
- Read package.json, the contribution guide, and buildDistribution before editing: src is authoritative implementation, lib is distributed/self-testing output, and the guide requests rebuilding for validation then reverting generated jasmine.js/jasmine-html.js changes.
- Keep environment-independent changes in src/core and document-dependent code in src/html; the contribution guide requires public-interface caution and graceful cross-environment behavior.
- For scheduling changes, read Env.runQueue, Runner, TreeRunner, QueueRunner, and matching specs together; Env injects captured real timers, while TreeRunner chooses hook queues and skip policies.
- Use jasmineUnderTest/privateUnderTest for source assertions, with jasmine supplying test infrastructure; cleanup_ and resetEnv prevent environment/global-listener leakage between self-tests.
- Preserve repeat-run semantics: autoCleanClosures defaults true and clears spec functions; repeated execution requires disabling it, whereas parallelReset removes prior children and preserves top-level hooks.
- Preserve reporter serialization and lifecycle contracts: properties are validated through structuredClone plus JSON.stringify, events are cloned per reporter, and clearing resources precedes specDone.
- When execution is authorized, repository verification options are npm test, npm run test:parallel, npm run build, and browser serve/CI with JASMINE_BROWSER; Node selection excludes HTML specs, and package specs invoke shells/write artifacts. None of these tests or CI jobs was executed during this inspection.
- Investigate the standalone boot0.js mismatch and ignored ci:performance argument before relying on those workflows; use the inspected script bodies rather than assuming historical documentation or command names establish current behavior.
Languages
| Language | Files | Share of source |
|---|---|---|
| JavaScript | 286 | 99% |
| Markdown | 101 | docs/config |
| YAML | 7 | docs/config |
| JSON | 4 | docs/config |
| Sass | 2 | 1% |
| CSS | 1 | docs/config |
Start reading here
Probable source entrypoint: src/ — inferred from the directory tree and manifest, not the upstream docs.
Source roots
src/ (134 files) lib/ (13 files)
Source layout — src/
| Path | Files |
|---|---|
src/core/ | 81 |
Repository structure
| Top-level path | Files |
|---|---|
spec/ | 145 |
src/ | 134 |
release_notes/ | 96 |
lib/ | 13 |
scripts/ | 8 |
.github/ | 6 |
images/ | 1 |
.circleci/ | 1 |
Docs found: README.md
Package
package.json — jasmine-core v7.0.2, 15 declared dependencies.
@eslint/eslintrc@eslint/js@jasminejs/reportersarchivercss-url-embedejseslinteslint-plugin-compatglobglobalsjasminejasmine-browser-runner
CI & config entrypoints
README.md— Repository readme.github/workflows/safari.yml— GitHub Actions workflowpackage.json— npm scripts: build, buildStandaloneDist, ci, ci:performance, cleanup, lint, serve, serve:performance
Structural health signals
Average score 6.8/10 across 96 analyzed source files; 30 hotspots surfaced.
spec/core/integration/GlobalErrorHandlingSpec.js— 1240 lines, score 4 (Large file, Deep nesting)spec/core/integration/EnvSpec.js— 2888 lines, score 4.7 (Large file, Deep nesting)spec/core/integration/SpecRunningSpec.js— 1522 lines, score 4.7 (Large file, Deep nesting)
These are deterministic review leads — size, churn, and structural signals — not proof of a bug in this project.
Recent history
390d31e481062026-08-19 — Bump version to 7.0.2c29ae9d906ad2026-08-18 — Test that reset() rebinds globalseb00d3ae5cc92026-08-17 — Fix Node reset() fn303e1352e3732026-08-15 — Test that the distribution is built after changing the version numberacb7a511ae462026-08-15 — Bump version to 7.0.1