Socket
Socket
Sign inDemoInstall

jasmine

Package Overview
Dependencies
Maintainers
4
Versions
55
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jasmine - npm Package Compare versions

Comparing version 3.99.0 to 4.0.0

lib/exit_handler.js

91

lib/command.js
const path = require('path');
const fs = require('fs');
const Loader = require('./loader');

@@ -33,3 +34,3 @@ exports = module.exports = Command;

this.run = function(jasmine, commands) {
this.run = async function(jasmine, commands) {
setEnvironmentVariables(commands);

@@ -57,3 +58,3 @@

} else {
runJasmine(jasmine, env, print);
await runJasmine(jasmine, env, print);
}

@@ -77,3 +78,2 @@ }

filter,
stopOnFailure,
failFast,

@@ -95,6 +95,4 @@ random,

requires.push(arg.match("^--require=(.*)")[1]);
} else if (arg.match("^--stop-on-failure=")) {
stopOnFailure = arg.match("^--stop-on-failure=(.*)")[1] === 'true';
} else if (arg.match("^--fail-fast=")) {
failFast = arg.match("^--fail-fast=(.*)")[1] === 'true';
} else if (arg === '--fail-fast') {
failFast = true;
} else if (arg.match("^--random=")) {

@@ -120,3 +118,2 @@ random = arg.match("^--random=(.*)")[1] === 'true';

filter: filter,
stopOnFailure: stopOnFailure,
failFast: failFast,

@@ -133,12 +130,73 @@ helpers: helpers,

function runJasmine(jasmine, env, print) {
const loadConfig = require('./loadConfig');
loadConfig(jasmine, env, print);
jasmine.execute(env.files, env.filter)
.catch(function(error) {
console.error(error);
process.exit(1);
async function runJasmine(jasmine, env, print) {
await jasmine.loadConfigFile(env.configPath || process.env.JASMINE_CONFIG_PATH);
if (env.failFast !== undefined) {
jasmine.env.configure({
stopSpecOnExpectationFailure: env.failFast,
stopOnSpecFailure: env.failFast
});
}
if (env.seed !== undefined) {
jasmine.seed(env.seed);
}
if (env.random !== undefined) {
jasmine.randomizeTests(env.random);
}
if (env.helpers !== undefined && env.helpers.length) {
jasmine.addHelperFiles(env.helpers);
}
if (env.requires !== undefined && env.requires.length) {
jasmine.addRequires(env.requires);
}
if (env.reporter !== undefined) {
await registerReporter(env.reporter, jasmine);
}
jasmine.showColors(env.color);
try {
await jasmine.execute(env.files, env.filter);
} catch (error) {
console.error(error);
process.exit(1);
}
}
async function registerReporter(reporterModuleName, jasmine) {
let Reporter;
try {
Reporter = await new Loader().load(resolveReporter(reporterModuleName));
} catch (e) {
throw new Error('Failed to load reporter module '+ reporterModuleName +
'\nUnderlying error: ' + e.stack + '\n(end underlying error)');
}
let reporter;
try {
reporter = new Reporter();
} catch (e) {
throw new Error('Failed to instantiate reporter from '+ reporterModuleName +
'\nUnderlying error: ' + e.stack + '\n(end underlying error)');
}
jasmine.clearReporters();
jasmine.addReporter(reporter);
}
function resolveReporter(nameOrPath) {
if (nameOrPath.startsWith('./') || nameOrPath.startsWith('../')) {
return path.resolve(nameOrPath);
} else {
return nameOrPath;
}
}
function initJasmine(options) {

@@ -208,4 +266,3 @@ const print = options.print;

print('%s\tload module that match the given string', lPad('--require=', 18));
print('%s\t[true|false] stop spec execution on expectation failure', lPad('--stop-on-failure=', 18));
print('%s\t[true|false] stop Jasmine execution on spec failure', lPad('--fail-fast=', 18));
print('%s\tstop Jasmine execution on spec failure', lPad('--fail-fast', 18));
print('%s\tpath to your optional jasmine.json', lPad('--config=', 18));

@@ -212,0 +269,0 @@ print('%s\tpath to reporter to use instead of the default Jasmine reporter', lPad('--reporter=', 18));

6

lib/examples/jasmine.json

@@ -9,4 +9,6 @@ {

],
"stopSpecOnExpectationFailure": false,
"random": true
"env": {
"stopSpecOnExpectationFailure": false,
"random": true
}
}

@@ -5,3 +5,3 @@ const path = require('path');

const Loader = require('./loader');
const CompletionReporter = require('./reporters/completion_reporter');
const ExitHandler = require('./exit_handler');
const ConsoleSpecFilter = require('./filters/console_spec_filter');

@@ -24,2 +24,13 @@

*/
/**
* Whether to create the globals (describe, it, etc) that make up Jasmine's
* spec-writing interface. If it is set to false, the spec-writing interface
* can be accessed via jasmine-core's `noGlobals` method, e.g.:
*
* `const {describe, it, expect, jasmine} = require('jasmine-core').noGlobals();`
*
* @name JasmineOptions#globals
* @type (boolean | undefined)
* @default true
*/

@@ -39,4 +50,9 @@ /**

const jasmineCore = options.jasmineCore || require('jasmine-core');
this.jasmineCorePath = path.join(jasmineCore.files.path, 'jasmine.js');
this.jasmine = jasmineCore.boot(jasmineCore);
if (options.globals === false) {
this.jasmine = jasmineCore.noGlobals().jasmine;
} else {
this.jasmine = jasmineCore.boot(jasmineCore);
}
this.projectBaseDir = options.projectBaseDir || path.resolve();

@@ -56,4 +72,2 @@ this.specDir = '';

this.reportersCount = 0;
this.completionReporter = new CompletionReporter();
this.onCompleteCallbackAdded = false;
this.exit = process.exit;

@@ -65,8 +79,2 @@ this.showingColors = true;

const jasmineRunner = this;
this.completionReporter.onComplete(function(passed) {
jasmineRunner.exitCodeCompletion(passed);
});
this.checkExit = checkExit(this);
/**

@@ -84,4 +92,2 @@ * @function

*
* _Note_: If {@link Jasmine#onComplete|onComplete} is called, Jasmine will not
* exit when the suite completes even if exitOnCompletion is set to true.
* @name Jasmine#exitOnCompletion

@@ -187,3 +193,2 @@ * @type {boolean}

options.showColors = options.hasOwnProperty('showColors') ? options.showColors : true;
options.jasmineCorePath = options.jasmineCorePath || this.jasmineCorePath;

@@ -217,19 +222,8 @@ this.reporter.setOptions(options);

for (const file of files) {
await this.loader.load(file, this._alwaysImport || false);
await this.loader.load(file);
}
};
Jasmine.prototype.loadRequires = function() {
// TODO: In 4.0, switch to calling _loadFiles
// (requires making this function async)
this.requires.forEach(function(r) {
if (r.startsWith('./') || r.startsWith("../")) {
console.warn('DEPRECATION: requires with relative paths (in this case ' +
`${r}) are currently resolved relative to the jasmine/lib/jasmine ` +
'module but will be relative to the current working directory in ' +
'Jasmine 4.0.');
}
require(r);
});
Jasmine.prototype.loadRequires = async function() {
await this._loadFiles(this.requires);
};

@@ -242,13 +236,26 @@

* @param {string} [configFilePath=spec/support/jasmine.json]
* @return Promise
*/
Jasmine.prototype.loadConfigFile = function(configFilePath) {
try {
const absoluteConfigFilePath = path.resolve(this.projectBaseDir, configFilePath || 'spec/support/jasmine.json');
const config = require(absoluteConfigFilePath);
this.loadConfig(config);
} catch (e) {
if(configFilePath || e.code != 'MODULE_NOT_FOUND') { throw e; }
Jasmine.prototype.loadConfigFile = async function(configFilePath) {
if (configFilePath) {
await this.loadSpecificConfigFile_(configFilePath);
} else {
for (const ext of ['json', 'js']) {
try {
await this.loadSpecificConfigFile_(`spec/support/jasmine.${ext}`);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND' && e.code !== 'ERR_MODULE_NOT_FOUND') {
throw e;
}
}
}
}
};
Jasmine.prototype.loadSpecificConfigFile_ = async function(relativePath) {
const absolutePath = path.resolve(this.projectBaseDir, relativePath);
const config = await this.loader.load(absolutePath);
this.loadConfig(config);
};
/**

@@ -325,7 +332,6 @@ * Loads configuration from the specified object.

*/
if (config.jsLoader === 'import') {
checkForJsFileImportSupport();
this._alwaysImport = true;
} else if (config.jsLoader === 'require' || config.jsLoader === undefined) {
this._alwaysImport = false;
if (config.jsLoader === 'import' || config.jsLoader === undefined) {
this.loader.alwaysImport = true;
} else if (config.jsLoader === 'require') {
this.loader.alwaysImport = false;
} else {

@@ -392,35 +398,2 @@ throw new Error(`"${config.jsLoader}" is not a valid value for the ` +

// Deprecated synonyms for the above. These are confusingly named (addSpecFiles
// doesn't just do N of what addSpecFile does) but they've been around a long
// time and there might be quite a bit of code that uses them.
/**
* Synonym for {@link Jasmine#addMatchingSpecFiles}
* @function
* @name Jasmine#addSpecFiles
* @deprecated Use {@link Jasmine#addMatchingSpecFiles|addMatchingSpecFiles},
* {@link Jasmine#loadConfig|loadConfig}, or {@link Jasmine#loadConfigFile|loadConfigFile}
* instead.
*/
Jasmine.prototype.addSpecFiles = function(globs) {
this.env.deprecated('jasmine#addSpecFiles is deprecated. Use ' +
'jasmine#addMatchingSpecFiles instead.');
this.addMatchingSpecFiles(globs);
};
/**
* Synonym for {@link Jasmine#addMatchingHelperFiles}
* @name Jasmine#addHelperFiles
* @function
* @deprecated Use {@link Jasmine#addMatchingHelperFiles|addMatchingHelperFiles},
* {@link Jasmine#loadConfig|loadConfig}, or {@link Jasmine#loadConfigFile|loadConfigFile}
* instead.
*/
Jasmine.prototype.addHelperFiles = function(globs) {
this.env.deprecated('jasmine#addHelperFiles is deprecated. Use ' +
'jasmine#addMatchingHelperFiles instead.');
this.addMatchingHelperFiles(globs);
};
Jasmine.prototype.addRequires = function(requires) {

@@ -472,24 +445,2 @@ const jasmineRunner = this;

/**
* Registers a callback that will be called when execution finishes.
*
* _Note_: Only one callback can be registered. The callback will be called
* after the suite has completed and the results have been finalized, but not
* necessarily before all of Jasmine's cleanup has finished. Calling this
* function will also prevent Jasmine from exiting the Node process at the end
* of suite execution.
*
* @deprecated Set {@link Jasmine#exitOnCompletion|exitOnCompletion} to false
* and use the promise returned from {@link Jasmine#execute|execute} instead.
* @param {function} onCompleteCallback
*/
Jasmine.prototype.onComplete = function(onCompleteCallback) {
this.env.deprecated(
'Jasmine#onComplete is deprecated. Instead of calling onComplete, set ' +
"the Jasmine instance's exitOnCompletion property to false and use the " +
'promise returned from the execute method.'
);
this.completionReporter.onComplete(onCompleteCallback);
};
/**
* Sets whether to cause specs to only have one expectation failure.

@@ -516,3 +467,3 @@ * @function

Jasmine.prototype.exitCodeCompletion = function(passed) {
Jasmine.prototype.flushOutput = async function() {
// Ensure that all data has been written to stdout and stderr,

@@ -523,40 +474,9 @@ // then exit with an appropriate status code. Otherwise, we

// reading quickly enough.
const jasmineRunner = this;
const streams = [process.stdout, process.stderr];
let writesToWait = streams.length;
streams.forEach(function(stream) {
stream.write('', null, exitIfAllStreamsCompleted);
var streams = [process.stdout, process.stderr];
var promises = streams.map(stream => {
return new Promise(resolve => stream.write('', null, resolve));
});
function exitIfAllStreamsCompleted() {
writesToWait--;
if (writesToWait === 0 && jasmineRunner.exitOnCompletion) {
if(passed) {
jasmineRunner.exit(0);
}
else {
jasmineRunner.exit(1);
}
}
}
return Promise.all(promises);
};
const checkExit = function(jasmineRunner) {
return function() {
if (!jasmineRunner.completionReporter.isComplete()) {
process.exitCode = 4;
}
};
};
function checkForJsFileImportSupport() {
const v = process.versions.node
.split('.')
.map(el => parseInt(el, 10));
if (v[0] < 12 || (v[0] === 12 && v[1] < 17)) {
console.warn('Warning: jsLoader: "import" may not work reliably on Node ' +
'versions before 12.17.');
}
}
/**

@@ -575,5 +495,3 @@ * Runs the test suite.

Jasmine.prototype.execute = async function(files, filterString) {
this.completionReporter.exitHandler = this.checkExit;
this.loadRequires();
await this.loadRequires();
await this.loadHelpers();

@@ -601,15 +519,27 @@ if (!this.defaultReporterConfigured) {

if (!this.completionReporterInstalled_) {
this.addReporter(this.completionReporter);
this.completionReporterInstalled_ = true;
const prematureExitHandler = new ExitHandler(() => this.exit(4));
prematureExitHandler.install();
const overallResult = await this.env.execute();
await this.flushOutput();
prematureExitHandler.uninstall();
if (this.exitOnCompletion) {
this.exit(exitCodeForStatus(overallResult.overallStatus));
}
let overallResult;
this.addReporter({
jasmineDone: r => overallResult = r
});
await new Promise(resolve => {
this.env.execute(null, resolve);
});
return overallResult;
};
function exitCodeForStatus(status) {
switch (status) {
case 'passed':
return 0;
case 'incomplete':
return 2;
case 'failed':
return 3;
default:
console.error(`Unrecognized overall status: ${status}`);
return 1;
}
}

@@ -0,1 +1,2 @@

const path = require('path');
module.exports = Loader;

@@ -7,16 +8,21 @@

this.import_ = options.importShim || importShim;
this.resolvePath_ = options.resolvePath || path.resolve.bind(path);
this.alwaysImport = true;
}
Loader.prototype.load = function(path, alwaysImport) {
if (alwaysImport || path.endsWith('.mjs')) {
Loader.prototype.load = function(modulePath) {
if ((this.alwaysImport && !modulePath.endsWith('.json')) || modulePath.endsWith('.mjs')) {
// The ES module spec requires import paths to be valid URLs. As of v14,
// Node enforces this on Windows but not on other OSes.
const url = `file://${path}`;
return this.import_(url).catch(function(e) {
return Promise.reject(fixupImportException(e, path));
});
// Node enforces this on Windows but not on other OSes. On OS X, import
// paths that are URLs must not contain parent directory references.
const url = `file://${this.resolvePath_(modulePath)}`;
return this.import_(url)
.then(
mod => mod.default,
e => Promise.reject(fixupImportException(e, modulePath))
);
} else {
return new Promise(resolve => {
this.require_(path);
resolve();
const result = this.require_(modulePath);
resolve(result);
});

@@ -26,8 +32,8 @@ }

function requireShim(path) {
require(path);
function requireShim(modulePath) {
return require(modulePath);
}
function importShim(path) {
return import(path);
function importShim(modulePath) {
return import(modulePath);
}

@@ -98,3 +104,3 @@

// paths (c:\path\to\file.js) or URLs (file:///c:/path/to/file.js).
if (!(e instanceof SyntaxError)) {

@@ -101,0 +107,0 @@ return e;

@@ -15,3 +15,2 @@ module.exports = exports = ConsoleReporter;

showColors = false,
jasmineCorePath = null,
specCount,

@@ -29,3 +28,3 @@ executableSpecCount,

failedSuites = [],
stackFilter = defaultStackFilter;
stackFilter = stack => stack;

@@ -53,5 +52,2 @@ /**

showColors = options.showColors || false;
if (options.jasmineCorePath) {
jasmineCorePath = options.jasmineCorePath;
}
if (options.stackFilter) {

@@ -85,2 +81,6 @@ stackFilter = options.stackFilter;

this.jasmineDone = function(result) {
if (result.failedExpectations) {
failureCount += result.failedExpectations.length;
}
printNewline();

@@ -106,3 +106,3 @@ printNewline();

}
for(i = 0; i < pendingSpecs.length; i++) {
for (let i = 0; i < pendingSpecs.length; i++) {
pendingSpecDetails(pendingSpecs[i], i + 1);

@@ -213,13 +213,2 @@ }

function defaultStackFilter(stack) {
if (!stack) {
return '';
}
const filteredStack = stack.split('\n').filter(function(stackLine) {
return stackLine.indexOf(jasmineCorePath) === -1;
}).join('\n');
return filteredStack;
}
function specFailureDetails(result, failedSpecNumber) {

@@ -231,8 +220,8 @@ printNewline();

if (result.trace) {
if (result.debugLogs) {
printNewline();
print(indent('Trace:', 2));
print(indent('Debug logs:', 2));
printNewline();
for (const entry of result.trace) {
for (const entry of result.debugLogs) {
print(indent(`${entry.timestamp}ms: ${entry.message}`, 4));

@@ -239,0 +228,0 @@ printNewline();

@@ -13,3 +13,3 @@ {

"license": "MIT",
"version": "3.99.0",
"version": "4.0.0",
"repository": {

@@ -23,2 +23,3 @@ "type": "git",

},
"exports": "./lib/jasmine.js",
"files": [

@@ -33,3 +34,3 @@ "bin",

"glob": "^7.1.6",
"jasmine-core": "~3.99.0"
"jasmine-core": "^4.0.0"
},

@@ -36,0 +37,0 @@ "bin": "./bin/jasmine.js",

@@ -17,87 +17,40 @@ [![Build Status](https://circleci.com/gh/jasmine/jasmine-npm.svg?style=shield)](https://circleci.com/gh/jasmine/jasmine-npm)

https://jasmine.github.io/edge/node.html
https://jasmine.github.io/setup/nodejs.html
## Installation
## Quick Start
Installation:
```sh
# Local installation:
npm install --save-dev jasmine
# Global installation
npm install -g jasmine
```
## Initializing
To initialize a project for Jasmine:
To initialize a project for Jasmine
```sh
npx jasmine init
````
`jasmine init`
To seed your project with some examples:
To initialize a project for Jasmine when being installed locally
```sh
npx jasmine examples
````
`node_modules/.bin/jasmine init`
To run your test suite:
or
```sh
npx jasmine
````
`npx jasmine init`
## ES and CommonJS module compatibility
To seed your project with some examples
Jasmine is compatible with both ES modules and CommonJS modules. See the
[setup guide](https://jasmine.github.io/setup/nodejs.html) for more information.
`jasmine examples`
## Usage
## Node version compatibility
To run your test suite
Jasmine supports Node 12.x where x >=17, Node 14, and Node 16.
`jasmine`
## Configuration
Customize `spec/support/jasmine.json` to enumerate the source and spec files you would like the Jasmine runner to include.
You may use dir glob strings.
More information on the format of `jasmine.json` can be found in [the documentation](http://jasmine.github.io/edge/node.html#section-Configuration)
Alternatively, you may specify the path to your `jasmine.json` by setting an environment variable or an option:
```shell
jasmine JASMINE_CONFIG_PATH=relative/path/to/your/jasmine.json
jasmine --config=relative/path/to/your/jasmine.json
```
## Using ES modules
If the name of a spec file or helper file ends in `.mjs`, Jasmine will load it
as an [ES module](https://nodejs.org/docs/latest-v13.x/api/esm.html) rather
than a CommonJS module. This allows the spec file or helper to import other
ES modules. No extra configuration is required.
You can also use ES modules with names ending in `.js` by adding
`"jsLoader": "import"` to `jasmine.json`. This should work for CommonJS modules
as well as ES modules. We expect to make it the default in a future release.
Please [log an issue](https://github.com/jasmine/jasmine-npm/issues) if you have
code that doesn't load correctly with `"jsLoader": "import"`.
# Filtering specs
Execute only those specs which filename match given glob:
```shell
jasmine "spec/**/critical/*Spec.js"
```
Or a single file:
```shell
jasmine spec/currentSpec.js
```
Or execute only those specs which name matches a particular regex:
```shell
jasmine --filter "adapter21*"
```
(where the *name* of a spec is the first parameter passed to `describe()`)
## Support

@@ -104,0 +57,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc