### Refactored example: using a helper function for login setup Source: https://jasmine.github.io/pages/faq.html This refactored example avoids the need for let by inlining the login setup into each inner describe's beforeEach using a helper function logIn. This ensures each part of the setup runs after all setup it depends on. ```javascript describe('When the user is logged in', function() { it('does some things that apply to any user', function() { logIn(MyFixtures.anyUser); // ... }); describe('as an admin', function() { beforeEach(function() { logIn(MyFixtures.adminUser); }); it('shows the admin controls', function() { // ... }); }); describe('as a non-admin', function() { beforeEach(function() { logIn(MyFixtures.nonAdminUser); }); it('does not show the admin controls', function() { // ... }); }); function logIn(user) { // Do something, potentially complicated, that causes the system to run // with `user` logged in. } }); ``` -------------------------------- ### Install jasmine example specs Source: https://jasmine.github.io/setup/ruby.html Install example specs with implementation. The Rails generator and the command line tool are alternatives depending on whether you use Rails. ```ruby rails g jasmine:examples ``` ```ruby jasmine examples ``` -------------------------------- ### Generate Example Spec and Source Files with npx jasmine examples Source: https://jasmine.github.io/setup/nodejs.html Creates example spec and source files, so you can see how to write your first suite. ```bash npx jasmine examples ``` -------------------------------- ### start() Source: https://jasmine.github.io/api/7.0/Timer Starts the timer. ```APIDOC ## start() ### Description Starts the timer. ### Method start() ``` -------------------------------- ### Start describe block for Jasmine 2.0 upgrade Source: https://jasmine.github.io/upgrade-guides/2.0 Starts the top-level describe block for the upgrade guide example. ```javascript describe("Upgrading to jasmine 2.0", function() { ``` -------------------------------- ### Clock: describe block Source: https://jasmine.github.io/upgrade-guides/2.0 Starts the clock example. ```javascript describe("Clock", function() { ``` -------------------------------- ### Clock: install in beforeEach Source: https://jasmine.github.io/upgrade-guides/2.0 Shows the old `useMock` and new `install` for the mock clock. ```javascript beforeEach(function() { /* was: jasmine.Clock.useMock(); */ jasmine.clock().install(); }); ``` -------------------------------- ### install() → {Clock} Source: https://jasmine.github.io/api/7.0/Clock Installs the mock clock over the built-in methods. Returns the Clock instance. ```APIDOC ## install() → {Clock} ### Description Install the mock clock over the built-in methods. ### Method N/A ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response (N/A) - **returns** (Clock) - The Clock instance. #### Response Example N/A ``` -------------------------------- ### Install and initialize with npm Source: https://jasmine.github.io/setup/browser.html Install jasmine-browser-runner and jasmine-core as dev dependencies, then initialize the configuration file. Use this with npm. ```bash npm install --save-dev jasmine-browser-runner jasmine-core npx jasmine-browser-runner init ``` -------------------------------- ### Jasmine Configuration File (spec/support/jasmine.mjs) Source: https://jasmine.github.io/setup/nodejs.html Example configuration for `spec/support/jasmine.mjs`. The `spec_dir` is prefixed to all `spec_files` and `helpers`. Helpers run once before all specs. Paths starting with `!` are excluded. ```json { // Spec directory path relative to the current working dir when jasmine is executed. // The value "" represents the current working directory. "spec_dir": "spec", // Array of filepaths (and globs) relative to spec_dir to include and exclude "spec_files": [ "**/*[sS]pec.?(m)js", "!**/*nospec.js" ], // Array of filepaths (and globs) relative to spec_dir to include before jasmine specs "helpers": [ "helpers/**/*.?(m)js" ], // Configuration of the Jasmine environment // "env" is optional, as are all of its properties. "env": { // Whether to fail a spec that ran no expectations "failSpecWithNoExpectations": false, // Stop execution of a spec after the first expectation failure in it "stopSpecOnExpectationFailure": false, // Stop execution of the suite after the first spec failure "stopOnSpecFailure": false, // Run specs in semi-random order "random": false } } ``` -------------------------------- ### Using beforeEach, afterEach, beforeAll, and afterAll Source: https://jasmine.github.io/tutorials/your_first_suite.html Shows the setup and teardown functions: beforeEach runs before each spec, afterEach after each spec, beforeAll once before all specs, and afterAll after all specs. beforeAll and afterAll can speed up tests with expensive setup but risk leaking state between specs. ```javascript describe("A suite with some shared setup", function() { let foo = 0; ``` ```javascript beforeEach(function() { foo += 1; }); ``` ```javascript afterEach(function() { foo = 0; }); ``` ```javascript beforeAll(function() { foo = 1; }); ``` ```javascript afterAll(function() { foo = 0; }); ``` -------------------------------- ### Non-working example: overriding user in inner describe Source: https://jasmine.github.io/pages/faq.html This example does not work because inner beforeEach functions run after the outer beforeEach, so changing the user in inner describes has no effect on the login setup. It illustrates a common anti-pattern. ```javascript // DOES NOT WORK describe('When the user is logged in', function() { let user = MyFixtures.anyUser beforeEach(function() { // Do something, potentially complicated, that causes the system to run // with `user` logged in. }); it('does some things that apply to any user', function() { // ... }); describe('as an admin', function() { beforeEach(function() { user = MyFixtures.adminUser; }); it('shows the admin controls', function() { // ... }); }); describe('as a non-admin', function() { beforeEach(function() { user = MyFixtures.nonAdminUser; }); it('does not show the admin controls', function() { // ... }); }); }); ``` -------------------------------- ### Install and initialize with Yarn Source: https://jasmine.github.io/setup/browser.html Install jasmine-browser-runner and jasmine-core as dev dependencies using Yarn, then initialize the configuration file. ```bash yarn add -D jasmine-browser-runner jasmine-core npx jasmine-browser-runner init ``` -------------------------------- ### Start jasmine server Source: https://jasmine.github.io/setup/ruby.html Starts a server that continues to run so you can point a browser at it. ```ruby rake jasmine ``` -------------------------------- ### Install React Testing Library with Yarn Source: https://jasmine.github.io/tutorials/react_with_browser Install @testing-library/react as a dev dependency using Yarn. ```bash $ yarn add --dev @testing-library/react ``` -------------------------------- ### Spies: describe and createSpy Source: https://jasmine.github.io/upgrade-guides/2.0 Starts the spies example, creating a spy with `jasmine.createSpy`. ```javascript describe("Spies", function() { it('should spy', function() { var spy = jasmine.createSpy('spy'); ``` -------------------------------- ### startServer(options) Source: https://jasmine.github.io/api/browser-runner/5.0/module-jasmine-browser-runner.html Starts a server that serves the specs and supporting files via HTTP. ```APIDOC ## startServer(options) → {Promise.} ### Description Starts a Server that will serve the specs and supporting files via HTTP. ### Method startServer ### Parameters - **options** (ServerCtorOptions) - Required - Options to use to construct the server. ### Returns A promise that is resolved when the server is started. Type: Promise. ``` -------------------------------- ### beforeAll(functionopt, timeoutopt) Source: https://jasmine.github.io/api/7.0/global.html Run some shared setup once before all of the specs in the describe are run. Be careful sharing setup to avoid leaking state between specs. ```APIDOC ## beforeAll(functionopt, timeoutopt) ### Description Run some shared setup once before all of the specs in the `describe` are run. Be careful sharing setup to avoid leaking state between specs. ### Parameters - **function** (implementationCallback) - Optional - Function that contains the code to setup your specs. - **timeout** (Int) - Optional - Default: `jasmine.DEFAULT_TIMEOUT_INTERVAL` - Custom timeout for an async beforeAll. ### Since 2.1.0 ### See - async ``` -------------------------------- ### Install Jasmine Locally with npm Source: https://jasmine.github.io/setup/nodejs.html Installs the Jasmine module as a dev dependency for your project. Use `npx jasmine` to run the CLI after local installation. ```bash npm install --save-dev jasmine ``` -------------------------------- ### Start ahead-of-time response spec Source: https://jasmine.github.io/tutorials/mocking_ajax Starts a spec that demonstrates setting up responses ahead of time. ```javascript it("allows responses to be setup ahead of time", function () { const doneFn = jasmine.createSpy("success"); ``` -------------------------------- ### beforeEach(functionopt, timeoutopt) Source: https://jasmine.github.io/api/7.0/global.html Run some shared setup before each of the specs in the describe in which it is called. ```APIDOC ## beforeEach(functionopt, timeoutopt) ### Description Run some shared setup before each of the specs in the `describe` in which it is called. ### Parameters - **function** (implementationCallback) - Optional - Function that contains the code to setup your specs. - **timeout** (Int) - Optional - Default: `jasmine.DEFAULT_TIMEOUT_INTERVAL` - Custom timeout for an async beforeEach. ### Since 1.3.0 ### See - async ``` -------------------------------- ### Install dependencies with yarn or npm Source: https://jasmine.github.io/tutorials/react_with_node Install the required packages for testing React with Jasmine. Use yarn or npm depending on your package manager. ```bash $ yarn add --dev @babel/core \ @babel/register \ babel-preset-react-app \ cross-env \ jsdom \ jasmine ``` ```bash $ npm install --save-dev @babel/core \ @babel/register \ babel-preset-react-app \ cross-env \ jsdom \ jasmine ``` -------------------------------- ### RemoteSeleniumGridConfig example Source: https://jasmine.github.io/api/browser-runner/5.0/RemoteSeleniumGridConfig Example configuration for running specs on a remote Selenium grid. Additional properties such as "sauce:options" are included in the capabilities object passed to Selenium Webdriver. ```json { "url": "https://ondemand.saucelabs.com/wd/hub", "platformName": "macOS 12", "sauce:options": { "tunnelName": "the same tunnel name that was provided to Sauce Connect", "userName": "your Saucelabs username", "accessKey": "your Saucelabs access key" } } ``` -------------------------------- ### Install @testing-library/react with yarn or npm Source: https://jasmine.github.io/tutorials/react_with_node Install the React Testing Library package to render React components and inspect results in Jasmine specs. Use either the yarn or npm command. ```bash $ yarn add --dev @testing-library/react ``` ```bash $ npm install --save-dev @testing-library/react ``` -------------------------------- ### Install jasmine.Ajax in beforeEach Source: https://jasmine.github.io/tutorials/mocking_ajax Installs the jasmine-ajax mock in a beforeEach to mock all AJAX calls for the entire suite. ```javascript beforeEach(function() { jasmine.Ajax.install(); }); ``` -------------------------------- ### jasmine.getEnv() Source: https://jasmine.github.io/api/7.0/jasmine Gets the currently booted Jasmine Environment. ```APIDOC ## jasmine.getEnv() ### Description Get the currently booted Jasmine Environment. ### Method getEnv ### Returns - **Env** - The currently booted Jasmine Environment. ### Since 1.3.0 ``` -------------------------------- ### Start a describe block for pending specs Source: https://jasmine.github.io/tutorials/your_first_suite.html Starts a describe block for pending specs; the following specs are marked pending. ```javascript describe("Pending specs", function() { ``` -------------------------------- ### Start the Jasmine server Source: https://jasmine.github.io/setup/python.html Starts the Jasmine server, which serves the Jasmine suite in a browser. The suite runs every time the page is reloaded at localhost:8888. ```bash jasmine server ``` -------------------------------- ### Typical usage with globals - 7.0 installGlobals Source: https://jasmine.github.io/upgrade-guides/7.0 In 7.0, jasmine-core boots itself and you must call installGlobals to install the globals previously installed by boot. ```javascript const jasmineCore = require('jasmine-core'); jasmineCore.installGlobals(); ``` -------------------------------- ### Spies: basic setup and check Source: https://jasmine.github.io/upgrade-guides/2.0 Shows basic spy invocation and expectation. ```javascript spy('foo'); spy('bar'); expect(spy).toHaveBeenCalledWith('foo'); ``` -------------------------------- ### Open describe block for asymmetric equality testers Source: https://jasmine.github.io/tutorials/your_first_suite.html Opens the top-level describe block for the asymmetric equality tester examples on this page. The remaining examples are nested inside this block. ```javascript describe("Matching with finesse", function() { ``` -------------------------------- ### Install Jasmine Globally with npm Source: https://jasmine.github.io/setup/nodejs.html Optionally installs the Jasmine CLI globally so you can run `jasmine` directly without `npx`. Not recommended because it is hard to keep the global version in sync with project versions. ```bash npm install -g jasmine ``` -------------------------------- ### Start jasmine-browser-runner server programmatically (ESM and CommonJS) Source: https://jasmine.github.io/setup/browser.html Programmatically start the jasmine-browser-runner server with a custom configuration. The ESM version imports the config directly; the CommonJS version dynamically imports the config module. Both set `projectBaseDir` and call `startServer` with a custom port. ```javascript // ESM import path from 'path'; import jasmineBrowser from 'jasmine-browser-runner'; import config from './spec/support/jasmine-browser.mjs'; config.projectBaseDir = path.resolve('some/path'); jasmineBrowser.startServer(config, { port: 4321 }); ``` ```javascript // CommonJS const path = require('path'); const jasmineBrowser = require('jasmine-browser-runner'); import('./spec/support/jasmine-browser.mjs') .then(function({default: config}) { config.projectBaseDir = path.resolve('some/path'); jasmineBrowser.startServer(config, { port: 4321 }); }); ``` -------------------------------- ### spyOn(obj, methodName) → {Spy} Source: https://jasmine.github.io/api/7.0/global.html Installs a spy onto an existing object. ```APIDOC ## spyOn(obj, methodName) → {Spy} ### Description Installs a spy onto an existing object. `spyOn` may be overwritten by user or library code to customize Jasmine's behavior. ### Method spyOn ### Parameters - **obj** (Object) - Required - The object upon which to install the `Spy`. - **methodName** (String) - Required - The name of the method to replace with a `Spy`. ### Returns - **Spy** - The installed spy. ### Since 1.3.0 ``` -------------------------------- ### suiteStarted(result, done?) Source: https://jasmine.github.io/api/7.0/HtmlReporterV2 Reporter method invoked when a suite starts. ```APIDOC ## suiteStarted(result, done?) ### Description Invoked when a `describe` starts to run. ### Method suiteStarted ### Parameters - **result** (SuiteStartedEvent) - Required - Information about the individual `describe` being run. - **done** (function) - Optional - Used to specify that this callback is asynchronous and Jasmine should wait until it has been called before moving on. ### Returns Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. ``` -------------------------------- ### configuration() → {Configuration} Source: https://jasmine.github.io/api/7.0/Env Gets the current configuration for the Jasmine environment. ```APIDOC ## configuration() → {Configuration} ### Description Get the current configuration for your jasmine environment ### Method configuration ### Returns - **Configuration** - The current configuration ### Since 3.3.0 ``` -------------------------------- ### suiteStarted(result, doneopt) Source: https://jasmine.github.io/api/7.0/Reporter Callback invoked when a describe block starts running. Can be asynchronous. ```APIDOC ## suiteStarted(result, doneopt) ### Description Invoked when a `describe` starts to run. ### Parameters - **result** (SuiteStartedEvent) - Required - Information about the individual `describe` being run. - **done** (function) - Optional - Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. ### Returns Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. ``` -------------------------------- ### jasmine.clock() → {Clock} Source: https://jasmine.github.io/api/7.0/jasmine Get the currently booted mock Clock for this Jasmine environment. ```APIDOC ## jasmine.clock() → {Clock} ### Description Get the currently booted mock {Clock} for this Jasmine environment. ### Returns - **Clock** - The currently booted mock Clock. ### Since 2.0.0 ``` -------------------------------- ### Simple example using the library (CommonJS and ESM) Source: https://jasmine.github.io/setup/nodejs.html Shows a complete workflow: load config, configure default reporter, and execute. Includes both CommonJS and ESM versions. ```javascript // CommonJS const Jasmine = require('jasmine'); const runner = new Jasmine(); runner.loadConfigFile('spec/support/jasmine.json') .then(function() { runner.configureDefaultReporter({ showColors: false }); runner.execute(); }); // or ESM: import Jasmine from 'jasmine'; const runner = new Jasmine(); await runner.loadConfigFile('spec/support/jasmine.json'); runner.configureDefaultReporter({ showColors: false }); runner.execute(); ``` -------------------------------- ### Use a Jasmine spy to assert async callback arguments Source: https://jasmine.github.io/pages/faq.html Use a Jasmine spy to get better failure messages. The spy records the arguments, so you can assert with toHaveBeenCalledWith after awaiting the promise. ```javascript it("calls the onData callback with the expected args", async function() { const subject = new DataFetcher(); const callback = jasmine.createSpy('onData callback'); subject.onData(callback); await subject.fetch(); expect(callback).toHaveBeenCalledWith(expectedData); }); ``` -------------------------------- ### Configure srcFiles to load external script URL Source: https://jasmine.github.io/pages/faq.html Add external script URLs to the `srcFiles` array in your `jasmine-browser.json` or `jasmine-browser.js` configuration file to load them in your tests. The example shows loading jQuery from a CDN before your own JavaScript files. ```javascript // ... srcFiles: [ "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js", "**/*.js" ], // ... ``` -------------------------------- ### Wrap done to ignore multiple calls (allowUnsafeMultipleDone) Source: https://jasmine.github.io/pages/faq.html Implements the Jasmine 2-3 behavior of ignoring all but the first call to done, for specs that cannot eliminate extra done calls. Be aware that such specs are still buggy and may cause intermittent failures, unreported failures, or failures on the wrong spec. The example wraps done in a guard and shows a spec that calls done twice. ```javascript function allowUnsafeMultipleDone(fn) { return function(done) { let doneCalled = false; fn(function(err) { if (!doneCalled) { done(err); doneCalled = true; } }); } } it('calls done twice', allowUnsafeMultipleDone(function(done) { setTimeout(done); setTimeout(function() { // This code may interleave with subsequent specs or even run after Jasmine // has finished executing. done(); }, 50); })); ``` -------------------------------- ### Asynchronous Specs: describe block Source: https://jasmine.github.io/upgrade-guides/2.0 Starts the asynchronous specs example. The `done` callback is used to signal completion. ```javascript describe("Asynchronous Specs", function() { ``` -------------------------------- ### Jasmine spec for DataLoader: incorrect async/done and corrected await Source: https://jasmine.github.io/pages/faq.html Two Jasmine spec examples for the second scenario where code signals completion in multiple ways. The first shows the incorrect spec with both async and done, including the DataLoader class definition. The second shows the corrected spec that awaits the returned promise and uses jasmine.createSpy to verify the subscriber call. ```javascript // in DataLoader.js class DataLoader { constructor(fetch) { // ... } subscribe(subscriber) { // ... } async load() { // ... } } // in DataLoaderSpec.js // WARNING: does not work correctly it('provides the fetched data to observers', async function(done) { const fetch = function() { return Promise.resolve(/*...*/); }; const subscriber = function(result) { expect(result).toEqual(/*...*/); done(); }; const subject = new DataLoader(fetch); subject.subscribe(subscriber); await subject.load(/*...*/); }); ``` ```javascript it('provides the fetched data to observers', async function(/* Note: no done param */) { const fetch = function() { return Promise.resolve(/*...*/); }; const subscriber = jasmine.createSpy('subscriber'); const subject = new DataLoader(fetch); subject.subscribe(subscriber); // Await the returned promise. This will fail the spec if the promise // is rejected or isn't resolved before the spec timeout. await subject.load(/*...*/); // The subscriber should have been called by now. If not, // that's a bug in DataLoader, and we want the following to fail. expect(subscriber).toHaveBeenCalledWith(/*...*/); }); ``` -------------------------------- ### Create getter and setter spies with spyOnProperty Source: https://jasmine.github.io/tutorials/spying_on_properties Use spyOnProperty with the third argument "get" or "set" to create a getter or setter spy. The example shows creating both types on the same property and chaining .and.returnValue() or .and.callThrough(). ```javascript it("allows you to create spies for either type", function() { spyOnProperty(someObject, "myValue", "get").and.returnValue(30); spyOnProperty(someObject, "myValue", "set").and.callThrough(); }); ``` -------------------------------- ### Test code with separate success/failure channels using Promise.race Source: https://jasmine.github.io/pages/faq.html Use Promise.race to wait for either a success or failure signal from code that uses different channels (e.g., subscribe and onError). Assumes the code under test signals only one outcome, never both. The example shows a DataLoader class and a Jasmine spec that converts both channels to promises and races them. ```javascript // in DataLoader.js class DataLoader { constructor(fetch) { // ... } subscribe(subscriber) { // ... } onError(errorSubscriber) { // ... } load() { // ... } } // in DataLoaderSpec.js it('provides the fetched data to observers', async function() { const fetch = function() { return Promise.resolve(/*...*/); }; let resolveSubscriberPromise, rejectErrorPromise; const subscriberPromise = new Promise(function(resolve) { resolveSubscriberPromise = resolve; }); const errorPromise = new Promise(function(resolve, reject) { rejectErrorPromise = reject; }); const subject = new DataLoader(fetch); subject.subscribe(resolveSubscriberPromise); subject.onError(rejectErrorPromise); const result = await Promise.race([subscriberPromise, errorPromise]); expect(result).toEqual(/*...*/); }); ``` -------------------------------- ### new Server(options) Source: https://jasmine.github.io/api/browser-runner/5.0/Server Constructor for the Server class with options. ```APIDOC ## new Server(options) ### Description Creates a new Server instance with the given options. ### Constructor `new Server(options)` ### Parameters - **options** (ServerCtorOptions) - Required - Configuration options for the server. ### Methods #### hostname() → {string} Gets the hostname that the server is listening on. The server must be started before this method is called. ##### Returns: - **Type**: string - **Description**: The hostname (localhost if not specified) #### port() → {number} Gets the port that the server is listening on. The server must be started before this method is called. ##### Returns: - **Type**: number - **Description**: The port number #### scheme() → {string} Gets the URL scheme that the server is listening on. The server must be started before this method is called. ##### Returns: - **Type**: string - **Description**: The URL scheme ('http' or 'https') #### start() → {Promise.} Starts the server. ##### Returns: - **Type**: Promise. - **Description**: A promise that resolves upon successful start. #### stop() → {Promise.} Stops the server. ##### Returns: - **Type**: Promise. ``` -------------------------------- ### Install Jasmine with pip Source: https://jasmine.github.io/setup/python.html Installs the Jasmine Python package using pip. This is the recommended way to install Jasmine for Python-based web projects or JavaScript projects that use Python. ```bash pip install jasmine ``` -------------------------------- ### Initialize a Jasmine Project with npx jasmine init Source: https://jasmine.github.io/setup/nodejs.html Creates a spec directory and configuration JSON for Jasmine, preparing the project for writing specs. ```bash npx jasmine init ``` -------------------------------- ### Start respondWith call Source: https://jasmine.github.io/tutorials/mocking_ajax Starts specifying the response for the most recent request using respondWith. ```javascript jasmine.Ajax.requests.mostRecent().respondWith({ ``` -------------------------------- ### Set up jsdom helper Source: https://jasmine.github.io/tutorials/react_with_node Create spec/helpers/jsdom.js to provide a simulated browser environment for the specs. ```javascript import {JSDOM} from 'jsdom'; const dom = new JSDOM(''); global.document = dom.window.document; global.window = dom.window; global.navigator = dom.window.navigator; ``` -------------------------------- ### new Server() Source: https://jasmine.github.io/api/browser-runner/5.0/Server Constructor for the Server class without options. ```APIDOC ## new Server() ### Description Creates a new Server instance that serves the specs and supporting files via HTTP. ### Constructor `new Server()` ### Methods #### hostname() → {string} Gets the hostname that the server is listening on. The server must be started before this method is called. ##### Returns: - **Type**: string - **Description**: The hostname (localhost if not specified) #### port() → {number} Gets the port that the server is listening on. The server must be started before this method is called. ##### Returns: - **Type**: number - **Description**: The port number #### scheme() → {string} Gets the URL scheme that the server is listening on. The server must be started before this method is called. ##### Returns: - **Type**: string - **Description**: The URL scheme ('http' or 'https') #### start() → {Promise.} Starts the server. ##### Returns: - **Type**: Promise. - **Description**: A promise that resolves upon successful start. #### stop() → {Promise.} Stops the server. ##### Returns: - **Type**: Promise. ``` -------------------------------- ### Initialize a Jasmine project Source: https://jasmine.github.io/setup/python.html Initializes a Jasmine project by creating a spec directory and a configuration YAML file. Run this after installing Jasmine to set up the project structure. ```bash jasmine init ``` -------------------------------- ### Serve specs interactively Source: https://jasmine.github.io/setup/browser.html Start the server for interactive spec running. Visit http://localhost:8888/ in your browser. ```bash npx jasmine-browser-runner serve ``` -------------------------------- ### Install jasmine with Rails generator Source: https://jasmine.github.io/setup/ruby.html Rails generator to install a default jasmine.yml and a sample jasmine_helper.rb. ```ruby rails g jasmine:install ``` -------------------------------- ### Start mocking ajax test suite Source: https://jasmine.github.io/tutorials/mocking_ajax Starts the top-level test suite for mocking AJAX calls with jasmine-ajax. ```javascript describe("mocking ajax", function() { ``` -------------------------------- ### elapsed() Source: https://jasmine.github.io/api/7.0/Timer Determines the time since the timer was started. Returns the elapsed time in milliseconds, or NaN if the timer has not been started. ```APIDOC ## elapsed() ### Description Determines the time since the timer was started. ### Method elapsed() ### Returns - **number** - Elapsed time in milliseconds, or NaN if the timer has not been started. ``` -------------------------------- ### Discard existing state - 7.0 installGlobals and reset Source: https://jasmine.github.io/upgrade-guides/7.0 In 7.0, use installGlobals to install globals and reset to discard all state and configuration and reinitialize. ```javascript const jasmineCore = require('jasmine-core'); jasmineCore.installGlobals(); jasmineCore.reset(); ``` -------------------------------- ### Initialize Jasmine with yarn or npx Source: https://jasmine.github.io/tutorials/react_with_node Initialize Jasmine to create the default spec/support/jasmine.json configuration. Use the command matching your package manager. ```bash $ yarn run jasmine init ``` ```bash $ npx jasmine init ``` -------------------------------- ### Jasmine-browser-runner middleware example Source: https://jasmine.github.io/upgrade-guides/7.0 Middleware in jasmine-browser-runner are now functions that take request, response, and next parameters. This example sets security headers. ```javascript // jasmine-browser.mjs module.exports = { // ... "middleware": { "/": function(req, res, next) { res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); next(); } } }; ``` -------------------------------- ### Using jasmine.Timer Source: https://jasmine.github.io/api/7.0/Timer Creates a new jasmine.Timer, starts it, and retrieves the elapsed time in milliseconds. The elapsed() method returns NaN if the timer has not been started. ```javascript const timer = new jasmine.Timer(); timer.start(); const elapsed = timer.elapsed() ``` -------------------------------- ### Run tests with yarn or npm Source: https://jasmine.github.io/tutorials/react_with_node Run the test suite using either Yarn or npm. Both commands are equivalent and execute the project's test script. ```bash $ yarn test ``` ```bash $ npm test ``` -------------------------------- ### Load configuration from file or object Source: https://jasmine.github.io/setup/nodejs.html Loads configuration either from a JSON file using loadConfigFile or from an object using loadConfig. The object example shows spec_dir, spec_files, and helpers patterns. ```javascript await runner.loadConfigFile('spec/support/jasmine.json'); runner.loadConfig({ spec_dir: 'spec', spec_files: [ 'appSpec.js', 'requests/**/*[sS]pec.js', 'utils/**/*[sS]pec.js' ], helpers: [ 'helpers/**/*.js' ] }); ``` -------------------------------- ### Babel configuration with React and env presets Source: https://jasmine.github.io/tutorials/react_with_browser Create a Babel configuration file with the required presets for React and environment support. ```json { "presets": [ "@babel/preset-react", "@babel/preset-env" ] } ``` -------------------------------- ### Uninstall jasmine.Ajax and start response spec Source: https://jasmine.github.io/tutorials/mocking_ajax Uninstalls the mock in afterEach to restore real AJAX behavior, then starts a spec that specifies a response when needed. ```javascript afterEach(function() { jasmine.Ajax.uninstall(); }); it("specifying response when you need it", function() { const doneFn = jasmine.createSpy("success"); ```