Compare commits

..

5 Commits

Author SHA1 Message Date
Steve Gravrock 9cf9b856b0 Bump version to 5.13.0
Test in latest available Safari / build (push) Has been cancelled
2025-12-01 17:25:03 -08:00
Steve Gravrock db6c142afd Copy 6.0.0-beta.0 release notes from branch 2025-11-28 11:49:05 -08:00
Steve Gravrock 1e691b2470 Prettier 2025-11-27 06:53:27 -08:00
Steve Gravrock c5555dd8cc Better debug logging for spec that occasionally fails in FF 2025-11-27 06:30:09 -08:00
Steve Gravrock 78c14f81a8 Copy 6.0.0-alpha.2 release notes from branch 2025-11-15 14:40:39 -08:00
267 changed files with 6437 additions and 10625 deletions
+17 -5
View File
@@ -16,6 +16,10 @@ executors:
docker: docker:
- image: cimg/node:20.0.0 - image: cimg/node:20.0.0
working_directory: ~/workspace working_directory: ~/workspace
node18:
docker:
- image: cimg/node:18.20.5
working_directory: ~/workspace
jobs: jobs:
build: build:
@@ -64,7 +68,7 @@ jobs:
command: npm run test:parallel command: npm run test:parallel
test_browsers: &test_browsers test_browsers: &test_browsers
executor: node20 executor: node18
steps: steps:
- attach_workspace: - attach_workspace:
at: . at: .
@@ -109,6 +113,9 @@ workflows:
- build: - build:
executor: node20 executor: node20
name: build_node_20 name: build_node_20
- build:
executor: node18
name: build_node_18
- test_node: - test_node:
executor: node22 executor: node22
name: test_node_22 name: test_node_22
@@ -119,6 +126,11 @@ workflows:
name: test_node_20 name: test_node_20
requires: requires:
- build_node_20 - build_node_20
- test_node:
executor: node18
name: test_node_18
requires:
- build_node_18
- test_parallel: - test_parallel:
executor: node24 executor: node24
name: test_parallel_node_24 name: test_parallel_node_24
@@ -135,13 +147,13 @@ workflows:
requires: requires:
- build_node_20 - build_node_20
- test_parallel: - test_parallel:
executor: node20 executor: node18
name: test_parallel_node_20 name: test_parallel_node_18
requires: requires:
- build_node_20 - build_node_18
- test_browsers: - test_browsers:
requires: requires:
- build_node_20 - build_node_18
filters: filters:
branches: branches:
ignore: /pull\/.*/ # Don't run on pull requests. ignore: /pull\/.*/ # Don't run on pull requests.
+1 -1
View File
@@ -29,7 +29,7 @@ Microsoft Edge) as well as Node.
| Environment | Supported versions | | Environment | Supported versions |
|-------------------|----------------------------------| |-------------------|----------------------------------|
| Node | 20, 22, 24 | | Node | 18.20.5+*, 20, 22, 24 |
| Safari | 16*, 17*, 26* | | Safari | 16*, 17*, 26* |
| Chrome | Evergreen | | Chrome | Evergreen |
| Firefox | Evergreen, 102*, 115*, 128*, 140 | | Firefox | Evergreen, 102*, 115*, 128*, 140 |
+15 -42
View File
@@ -1,29 +1,3 @@
/*
Copyright (c) 2008-2019 Pivotal Labs
Copyright (c) 2008-2025 The Jasmine developers
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
/** /**
* Note: Only available on Node. * Note: Only available on Node.
* @module jasmine-core * @module jasmine-core
@@ -32,7 +6,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
const jasmineRequire = require('./jasmine-core/jasmine.js'); const jasmineRequire = require('./jasmine-core/jasmine.js');
module.exports = jasmineRequire; module.exports = jasmineRequire;
const bootWithoutGlobals = (function() { const boot = (function() {
let jasmine, jasmineInterface; let jasmine, jasmineInterface;
return function bootWithoutGlobals(reinitialize) { return function bootWithoutGlobals(reinitialize) {
@@ -42,22 +16,20 @@ const bootWithoutGlobals = (function() {
jasmineInterface = jasmineRequire.interface(jasmine, env); jasmineInterface = jasmineRequire.interface(jasmine, env);
} }
return { jasmine, jasmineInterface }; return {jasmine, jasmineInterface};
}; };
})(); }());
/** /**
* Boots a copy of Jasmine and returns an object as described in {@link jasmine}. * Boots a copy of Jasmine and returns an object as described in {@link jasmine}.
* @param {boolean} [reinitialize=true] Whether to create a new copy of Jasmine if one already exists * If boot is called multiple times, the same object is returned every time
* unless true is passed.
* @param {boolean} [reinitialize=false] Whether to create a new copy of Jasmine if one already exists
* @type {function} * @type {function}
* @return {jasmine} * @return {jasmine}
*/ */
module.exports.boot = function(reinitialize) { module.exports.boot = function(reinitialize) {
if (reinitialize === undefined) { const {jasmine, jasmineInterface} = boot(reinitialize);
reinitialize = true;
}
const { jasmine, jasmineInterface } = bootWithoutGlobals(reinitialize);
for (const k in jasmineInterface) { for (const k in jasmineInterface) {
global[k] = jasmineInterface[k]; global[k] = jasmineInterface[k];
@@ -69,13 +41,14 @@ module.exports.boot = function(reinitialize) {
/** /**
* Boots a copy of Jasmine and returns an object containing the properties * Boots a copy of Jasmine and returns an object containing the properties
* that would normally be added to the global object. If noGlobals is called * that would normally be added to the global object. If noGlobals is called
* multiple times, the same object is returned every time. * multiple times, the same object is returned every time unless true is passed.
* *
* @param {boolean} [reinitialize=false] Whether to create a new copy of Jasmine if one already exists
* @example * @example
* const {describe, beforeEach, it, expect, jasmine} = require('jasmine-core').noGlobals(); * const {describe, beforeEach, it, expect, jasmine} = require('jasmine-core').noGlobals();
*/ */
module.exports.noGlobals = function() { module.exports.noGlobals = function(reinitialize) {
const { jasmineInterface } = bootWithoutGlobals(false); const {jasmineInterface} = boot(reinitialize);
return jasmineInterface; return jasmineInterface;
}; };
@@ -90,16 +63,16 @@ const rootPath = path.join(__dirname, 'jasmine-core'),
jsFilesToSkip = ['jasmine.js'].concat(bootFiles, legacyBootFiles); jsFilesToSkip = ['jasmine.js'].concat(bootFiles, legacyBootFiles);
fs.readdirSync(rootPath).forEach(function(file) { fs.readdirSync(rootPath).forEach(function(file) {
if (fs.statSync(path.join(rootPath, file)).isFile()) { if(fs.statSync(path.join(rootPath, file)).isFile()) {
switch (path.extname(file)) { switch(path.extname(file)) {
case '.css': case '.css':
cssFiles.push(file); cssFiles.push(file);
break; break;
case '.js': case '.js':
if (jsFilesToSkip.indexOf(file) < 0) { if (jsFilesToSkip.indexOf(file) < 0) {
jsFiles.push(file); jsFiles.push(file);
} }
break; break;
} }
} }
}); });
-2
View File
@@ -22,8 +22,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
'use strict';
/** /**
This file starts the process of "booting" Jasmine. It initializes Jasmine, This file starts the process of "booting" Jasmine. It initializes Jasmine,
makes its globals available, and creates the env. This file should be loaded makes its globals available, and creates the env. This file should be loaded
+64 -13
View File
@@ -22,8 +22,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
'use strict';
/** /**
This file finishes 'booting' Jasmine, performing all of the necessary This file finishes 'booting' Jasmine, performing all of the necessary
initialization before executing the loaded environment and all of a project's initialization before executing the loaded environment and all of a project's
@@ -39,18 +37,63 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(function() { (function() {
const env = jasmine.getEnv(); const env = jasmine.getEnv();
const urls = new jasmine.HtmlReporterV2Urls();
/**
* ## Runner Parameters
*
* More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface.
*/
const queryString = new jasmine.QueryString({
getWindowLocation: function() {
return window.location;
}
});
const filterSpecs = !!queryString.getParam('spec');
const config = {
stopOnSpecFailure: queryString.getParam('stopOnSpecFailure'),
stopSpecOnExpectationFailure: queryString.getParam(
'stopSpecOnExpectationFailure'
),
hideDisabled: queryString.getParam('hideDisabled')
};
const random = queryString.getParam('random');
if (random !== undefined && random !== '') {
config.random = random;
}
const seed = queryString.getParam('seed');
if (seed) {
config.seed = seed;
}
/** /**
* ## Reporters * ## Reporters
* The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any).
*/ */
const htmlReporter = new jasmine.HtmlReporterV2({ const htmlReporter = new jasmine.HtmlReporter({
env, env: env,
urls, navigateWithNewParam: function(key, value) {
getContainer() { return queryString.navigateWithNewParam(key, value);
},
addToExistingQueryString: function(key, value) {
return queryString.fullStringWithNewParam(key, value);
},
getContainer: function() {
return document.body; return document.body;
} },
createElement: function() {
return document.createElement.apply(document, arguments);
},
createTextNode: function() {
return document.createTextNode.apply(document, arguments);
},
timer: new jasmine.Timer(),
filterSpecs: filterSpecs
}); });
/** /**
@@ -58,13 +101,21 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
env.addReporter(jsApiReporter); env.addReporter(jsApiReporter);
env.addReporter(htmlReporter); env.addReporter(htmlReporter);
/** /**
* Configures Jasmine based on the current set of query parameters. This * Filter which specs will be run by matching the start of the full name against the `spec` query param.
* supports all parameters set by the HTML reporter as well as
* spec=partialPath, which filters out specs whose paths don't contain the
* parameter.
*/ */
env.configure(urls.configFromCurrentUrl()); const specFilter = new jasmine.HtmlSpecFilter({
filterString: function() {
return queryString.getParam('spec');
}
});
config.specFilter = function(spec) {
return specFilter.matches(spec.getFullName());
};
env.configure(config);
/** /**
* ## Execution * ## Execution
File diff suppressed because it is too large Load Diff
+3 -50
View File
@@ -8,7 +8,7 @@ body {
background-color: #eee; background-color: #eee;
padding: 5px; padding: 5px;
margin: -8px; margin: -8px;
font-size: 12px; font-size: 11px;
font-family: Monaco, "Lucida Console", monospace; font-family: Monaco, "Lucida Console", monospace;
line-height: 14px; line-height: 14px;
color: #333; color: #333;
@@ -63,7 +63,6 @@ body {
float: right; float: right;
line-height: 28px; line-height: 28px;
padding-right: 9px; padding-right: 9px;
font-size: 12px;
} }
.jasmine_html-reporter .jasmine-symbol-summary { .jasmine_html-reporter .jasmine-symbol-summary {
overflow: hidden; overflow: hidden;
@@ -116,23 +115,6 @@ body {
color: #ba9d37; color: #ba9d37;
content: "•"; content: "•";
} }
.jasmine_html-reporter progress {
width: 100%;
}
.jasmine_html-reporter progress[value] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.jasmine_html-reporter progress[value]::-webkit-progress-value, .jasmine_html-reporter progress[value]::-moz-progress-bar {
background: #007069;
}
.failed .jasmine_html-reporter progress[value]::-webkit-progress-value, .failed .jasmine_html-reporter progress[value]::-moz-progress-bar {
background: #ca3a11;
}
.jasmine_html-reporter progress.failed[value]::-webkit-progress-value, .jasmine_html-reporter progress.failed[value]::-moz-progress-bar {
background: #ca3a11;
}
.jasmine_html-reporter .jasmine-run-options { .jasmine_html-reporter .jasmine-run-options {
float: right; float: right;
margin-right: 5px; margin-right: 5px;
@@ -163,12 +145,8 @@ body {
display: block; display: block;
color: #eee; color: #eee;
} }
.jasmine_html-reporter .jasmine-bar.jasmine-in-progress {
color: #333;
}
.jasmine_html-reporter .jasmine-bar.jasmine-failed, .jasmine_html-reporter .jasmine-bar.jasmine-errored { .jasmine_html-reporter .jasmine-bar.jasmine-failed, .jasmine_html-reporter .jasmine-bar.jasmine-errored {
background-color: #ca3a11; background-color: #ca3a11;
color: #eee;
border-bottom: 1px solid #eee; border-bottom: 1px solid #eee;
} }
.jasmine_html-reporter .jasmine-bar.jasmine-passed { .jasmine_html-reporter .jasmine-bar.jasmine-passed {
@@ -198,17 +176,11 @@ body {
color: white; color: white;
} }
.jasmine_html-reporter.jasmine-spec-list .jasmine-bar.jasmine-menu.jasmine-failure-list, .jasmine_html-reporter.jasmine-spec-list .jasmine-bar.jasmine-menu.jasmine-failure-list,
.jasmine_html-reporter.jasmine-spec-list .jasmine-results .jasmine-failures, .jasmine_html-reporter.jasmine-spec-list .jasmine-results .jasmine-failures {
.jasmine_html-reporter.jasmine-spec-list .jasmine-performance-view {
display: none; display: none;
} }
.jasmine_html-reporter.jasmine-failure-list .jasmine-bar.jasmine-menu.jasmine-spec-list, .jasmine_html-reporter.jasmine-failure-list .jasmine-bar.jasmine-menu.jasmine-spec-list,
.jasmine_html-reporter.jasmine-failure-list .jasmine-summary, .jasmine_html-reporter.jasmine-failure-list .jasmine-summary {
.jasmine_html-reporter.jasmine-failure-list .jasmine-performance-view {
display: none;
}
.jasmine_html-reporter.jasmine-performance .jasmine-results .jasmine-failures,
.jasmine_html-reporter.jasmine-performance .jasmine-summary {
display: none; display: none;
} }
.jasmine_html-reporter .jasmine-results { .jasmine_html-reporter .jasmine-results {
@@ -330,22 +302,3 @@ body {
.jasmine_html-reporter .jasmine-debug-log .jasmine-debug-log-msg { .jasmine_html-reporter .jasmine-debug-log .jasmine-debug-log-msg {
white-space: pre; white-space: pre;
} }
.jasmine-hidden {
display: none;
}
.jasmine-tab + .jasmine-tab:before {
content: " | ";
}
.jasmine-performance-view h2, .jasmine-performance-view h3 {
margin-top: 1em;
margin-bottom: 1em;
}
.jasmine-performance-view table {
border-spacing: 5px;
}
.jasmine-performance-view th, .jasmine-performance-view td {
text-align: left;
}
+813 -1207
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,7 +1,7 @@
{ {
"name": "jasmine-core", "name": "jasmine-core",
"license": "MIT", "license": "MIT",
"version": "6.0.0-alpha.2", "version": "5.13.0",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/jasmine/jasmine.git" "url": "https://github.com/jasmine/jasmine.git"
@@ -45,8 +45,8 @@
"eslint-plugin-compat": "^6.0.2", "eslint-plugin-compat": "^6.0.2",
"glob": "^10.2.3", "glob": "^10.2.3",
"globals": "^16.0.0", "globals": "^16.0.0",
"jasmine": "github:jasmine/jasmine-npm#6.0", "jasmine": "^5.0.0",
"jasmine-browser-runner": "github:jasmine/jasmine-browser-runner#4.0", "jasmine-browser-runner": "github:jasmine/jasmine-browser-runner",
"jsdom": "^26.0.0", "jsdom": "^26.0.0",
"prettier": "1.17.1", "prettier": "1.17.1",
"sass": "^1.58.3" "sass": "^1.58.3"
+44
View File
@@ -0,0 +1,44 @@
# Jasmine Core 5.13.0 Release Notes
## Changes to supported environments
Safari 26 is now supported on a best-effort basis.
Due to the limited availability of Safari 18 and later on free CI services,
Safari support in future jasmine-core versions will be limited to:
* Best-effort support for the latest Safari version available on GitHub Actions,
which may change at any time.
* Best-effort support for Safari 16 and 17 for as long as it remains practical.
## New Features
* New `extraItStackFrames` and `extraDescribeStackFrames` config options to fix
the filename properties of reporter events in configurations that wrap
`it`/`describe`, such as zone.js. The `filename` properties of reporter events
are no longer deprecated.
* `jasmine.allOf` asymmetric equality tester
* Merges [#2087](https://github.com/jasmine/jasmine/issues/2083) from @jonahd-g
* Fixes [#2083](https://github.com/jasmine/jasmine/pull/2087)
## Supported environments
This version has been tested in the following environments.
| Environment | Supported versions |
|-------------|--------------------------------|
| Node | 18.20.5**, 20, 22, 24 |
| Safari** | 16, 17, 26.1 |
| Chrome | 142* |
| Firefox | 102**, 115**, 128**, 140, 145* |
| Edge | 142* |
\* Evergreen browser. Each version of Jasmine is tested against the latest
version available at release time.<br>
\** Supported on a best-effort basis. Support for these versions may be dropped
if it becomes impractical, and bugs affecting only these versions may not be
treated as release blockers.
------
_Release Notes generated with _[Anchorman](http://github.com/infews/anchorman)_
+74
View File
@@ -0,0 +1,74 @@
# Jasmine Core 6.0.0-beta.0 Release Notes
This is a pre-release, intended to offer a preview of upcoming changes and to
solicit feedback.
## A Note About Pre-Release Compatibility
There may be additional breaking changes in future 6.0 pre-releases or in the
final 6.0 release. That's allowed by the semver specification, but users are
sometimes unpleasantly surprised by it.
NPM's implementation of carat version ranges assumes that subsequent
pre-releases and final releases are fully compatible with earlier pre-releases.
If your package.json contains `"jasmine-core": "^6.0.0-beta.0`,
NPM might install any later 6.x version even though there is no guarantee of
compatibility. If that isn't ok, you should specify an exact pre-release version:
`"jasmine-core": "6.0.0-beta.0`.
## Breaking changes
* boot1.js no longer adds jsApiReporter to the env.
* HtmlReporterV2 initialization and boot1.js have been simplified. If you
maintain your own boot file, update it to match the boot1.js included in this
package.
## New features
* Statically exposed pretty printer as jasmine.pp().
## Bug fixes
* Fixed HtmlReporterV2 progress bar when running a subset of specs.
## Deprecations
* jsApiReporter is deprecated.
* Detect monkey patching and emit a deprecation warning.
## Documentation improvements
* Documented the set of possible spec statuses.
## Internal improvements
* Replaced isArray helper with native Array.isArray
## Supported environments
This version has been tested in the following environments.
| Environment | Supported versions |
|-------------------|--------------------------------|
| Node | 20, 22, 24 |
| Safari | 16**, 17**, 26.1** |
| Chrome | 142* |
| Firefox | 102**, 115**, 128**, 140, 145* |
| Edge | 142* |
\* Evergreen browser. Each version of Jasmine is tested against the latest
version available at release time.<br>
\** Supported on a best-effort basis. Support for these versions may be dropped
if it becomes impractical, and bugs affecting only these versions may not be
treated as release blockers.
------
_Release Notes generated with _[Anchorman](http://github.com/infews/anchorman)_
-4
View File
@@ -70,10 +70,6 @@ function concatFiles() {
{ {
dest: 'lib/jasmine-core/boot1.js', dest: 'lib/jasmine-core/boot1.js',
src: ['src/boot/boot1.js'], src: ['src/boot/boot1.js'],
},
{
dest: 'lib/jasmine-core.js',
src: ['src/boot/jasmine-core.js'],
} }
]; ];
const licenseBanner = { const licenseBanner = {
+62 -33
View File
@@ -1,7 +1,7 @@
describe('AsyncExpectation', function() { describe('AsyncExpectation', function() {
beforeEach(function() { beforeEach(function() {
privateUnderTest.Expectation.addAsyncCoreMatchers( jasmineUnderTest.Expectation.addAsyncCoreMatchers(
privateUnderTest.asyncMatchers jasmineUnderTest.asyncMatchers
); );
}); });
@@ -9,9 +9,9 @@ describe('AsyncExpectation', function() {
it('converts a pass to a fail', function() { it('converts a pass to a fail', function() {
const addExpectationResult = jasmine.createSpy('addExpectationResult'), const addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = Promise.resolve(), actual = Promise.resolve(),
pp = privateUnderTest.makePrettyPrinter(), pp = jasmineUnderTest.makePrettyPrinter(),
expectation = privateUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
matchersUtil: new privateUnderTest.MatchersUtil({ pp: pp }), matchersUtil: new jasmineUnderTest.MatchersUtil({ pp: pp }),
actual: actual, actual: actual,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
}); });
@@ -30,8 +30,8 @@ describe('AsyncExpectation', function() {
it('converts a fail to a pass', function() { it('converts a fail to a pass', function() {
const addExpectationResult = jasmine.createSpy('addExpectationResult'), const addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = Promise.reject(new Error('nope')), actual = Promise.reject(new Error('nope')),
expectation = privateUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
matchersUtil: new privateUnderTest.MatchersUtil({ matchersUtil: new jasmineUnderTest.MatchersUtil({
pp: function() {} pp: function() {}
}), }),
actual: actual, actual: actual,
@@ -55,7 +55,7 @@ describe('AsyncExpectation', function() {
const addExpectationResult = jasmine.createSpy('addExpectationResult'), const addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = dummyPromise(), actual = dummyPromise(),
expectation = privateUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: actual, actual: actual,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
}); });
@@ -80,7 +80,7 @@ describe('AsyncExpectation', function() {
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = privateUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: Promise.reject('rejected'), actual: Promise.reject('rejected'),
addExpectationResult: addExpectationResult, addExpectationResult: addExpectationResult,
matchersUtil: matchersUtil matchersUtil: matchersUtil
@@ -105,10 +105,10 @@ describe('AsyncExpectation', function() {
buildFailureMessage: function() { buildFailureMessage: function() {
return 'failure message'; return 'failure message';
}, },
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = privateUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: Promise.reject('b'), actual: Promise.reject('b'),
addExpectationResult: addExpectationResult, addExpectationResult: addExpectationResult,
matchersUtil: matchersUtil matchersUtil: matchersUtil
@@ -140,7 +140,7 @@ describe('AsyncExpectation', function() {
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const actual = Promise.reject(new Error('nope')); const actual = Promise.reject(new Error('nope'));
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: actual, actual: actual,
addExpectationResult: addExpectationResult, addExpectationResult: addExpectationResult,
matchersUtil: matchersUtil matchersUtil: matchersUtil
@@ -161,11 +161,11 @@ describe('AsyncExpectation', function() {
it('works with #not', function() { it('works with #not', function() {
const addExpectationResult = jasmine.createSpy('addExpectationResult'), const addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = Promise.resolve(), actual = Promise.resolve(),
pp = privateUnderTest.makePrettyPrinter(), pp = jasmineUnderTest.makePrettyPrinter(),
expectation = privateUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: actual, actual: actual,
addExpectationResult: addExpectationResult, addExpectationResult: addExpectationResult,
matchersUtil: new privateUnderTest.MatchersUtil({ pp: pp }) matchersUtil: new jasmineUnderTest.MatchersUtil({ pp: pp })
}); });
return expectation return expectation
@@ -185,11 +185,11 @@ describe('AsyncExpectation', function() {
it('works with #not and a custom message', function() { it('works with #not and a custom message', function() {
const addExpectationResult = jasmine.createSpy('addExpectationResult'), const addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = Promise.resolve('a'), actual = Promise.resolve('a'),
expectation = privateUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: actual, actual: actual,
addExpectationResult: addExpectationResult, addExpectationResult: addExpectationResult,
matchersUtil: new privateUnderTest.MatchersUtil({ matchersUtil: new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}) })
}); });
@@ -214,7 +214,7 @@ describe('AsyncExpectation', function() {
toFoo: function() {}, toFoo: function() {},
toBar: function() {} toBar: function() {}
}, },
expectation = privateUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
customAsyncMatchers: asyncMatchers customAsyncMatchers: asyncMatchers
}); });
@@ -236,7 +236,7 @@ describe('AsyncExpectation', function() {
buildFailureMessage: jasmine.createSpy('buildFailureMessage') buildFailureMessage: jasmine.createSpy('buildFailureMessage')
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = privateUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
actual: 'an actual', actual: 'an actual',
@@ -263,7 +263,7 @@ describe('AsyncExpectation', function() {
buildFailureMessage: jasmine.createSpy('buildFailureMessage') buildFailureMessage: jasmine.createSpy('buildFailureMessage')
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = privateUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
actual: 'an actual', actual: 'an actual',
@@ -290,7 +290,7 @@ describe('AsyncExpectation', function() {
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
actual: 'an actual', actual: 'an actual',
@@ -303,6 +303,8 @@ describe('AsyncExpectation', function() {
passed: true, passed: true,
message: '', message: '',
error: undefined, error: undefined,
expected: 'hello',
actual: 'an actual',
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
}); });
}); });
@@ -325,7 +327,7 @@ describe('AsyncExpectation', function() {
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
actual: 'an actual', actual: 'an actual',
@@ -336,6 +338,8 @@ describe('AsyncExpectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: '', message: '',
error: undefined, error: undefined,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
@@ -358,7 +362,7 @@ describe('AsyncExpectation', function() {
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: 'an actual', actual: 'an actual',
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -368,6 +372,8 @@ describe('AsyncExpectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message', message: 'I am a custom message',
error: undefined, error: undefined,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
@@ -392,7 +398,7 @@ describe('AsyncExpectation', function() {
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -402,6 +408,8 @@ describe('AsyncExpectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message', message: 'I am a custom message',
error: undefined, error: undefined,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
@@ -420,8 +428,9 @@ describe('AsyncExpectation', function() {
} }
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const actual = 'an actual';
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -433,6 +442,8 @@ describe('AsyncExpectation', function() {
passed: true, passed: true,
message: '', message: '',
error: undefined, error: undefined,
expected: 'hello',
actual: actual,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
}); });
}); });
@@ -454,8 +465,9 @@ describe('AsyncExpectation', function() {
} }
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const actual = 'an actual';
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
actual: 'an actual', actual: 'an actual',
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
@@ -466,6 +478,8 @@ describe('AsyncExpectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: actual,
message: 'default message', message: 'default message',
error: undefined, error: undefined,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
@@ -487,8 +501,9 @@ describe('AsyncExpectation', function() {
} }
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const actual = 'an actual';
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -498,6 +513,8 @@ describe('AsyncExpectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: actual,
message: 'I am a custom message', message: 'I am a custom message',
error: undefined, error: undefined,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
@@ -519,8 +536,9 @@ describe('AsyncExpectation', function() {
} }
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const actual = 'an actual';
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -530,6 +548,8 @@ describe('AsyncExpectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(true, { expect(addExpectationResult).toHaveBeenCalledWith(true, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: true, passed: true,
expected: 'hello',
actual: actual,
message: '', message: '',
error: undefined, error: undefined,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
@@ -554,8 +574,9 @@ describe('AsyncExpectation', function() {
} }
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const actual = 'an actual';
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -565,6 +586,8 @@ describe('AsyncExpectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: actual,
message: "I'm a custom message", message: "I'm a custom message",
error: undefined, error: undefined,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
@@ -589,7 +612,7 @@ describe('AsyncExpectation', function() {
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: 'an actual', actual: 'an actual',
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -599,6 +622,8 @@ describe('AsyncExpectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message', message: 'I am a custom message',
error: undefined, error: undefined,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
@@ -621,7 +646,7 @@ describe('AsyncExpectation', function() {
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.asyncFactory({ const expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: 'an actual', actual: 'an actual',
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -631,6 +656,8 @@ describe('AsyncExpectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message', message: 'I am a custom message',
error: undefined, error: undefined,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
@@ -655,7 +682,7 @@ describe('AsyncExpectation', function() {
}; };
const addExpectationResult = jasmine.createSpy('addExpectationResult'); const addExpectationResult = jasmine.createSpy('addExpectationResult');
let expectation = privateUnderTest.Expectation.asyncFactory({ let expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: 'an actual', actual: 'an actual',
customAsyncMatchers: matchers, customAsyncMatchers: matchers,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -665,6 +692,8 @@ describe('AsyncExpectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message', message: 'I am a custom message',
error: undefined, error: undefined,
errorForStack: jasmine.any(Error) errorForStack: jasmine.any(Error)
+16 -16
View File
@@ -1,6 +1,6 @@
describe('CallTracker', function() { describe('CallTracker', function() {
it('tracks that it was called when executed', function() { it('tracks that it was called when executed', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
expect(callTracker.any()).toBe(false); expect(callTracker.any()).toBe(false);
@@ -10,7 +10,7 @@ describe('CallTracker', function() {
}); });
it('tracks that number of times that it is executed', function() { it('tracks that number of times that it is executed', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
expect(callTracker.count()).toEqual(0); expect(callTracker.count()).toEqual(0);
@@ -20,7 +20,7 @@ describe('CallTracker', function() {
}); });
it('tracks the params from each execution', function() { it('tracks the params from each execution', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
callTracker.track({ object: void 0, args: [] }); callTracker.track({ object: void 0, args: [] });
callTracker.track({ object: {}, args: [0, 'foo'] }); callTracker.track({ object: {}, args: [0, 'foo'] });
@@ -31,7 +31,7 @@ describe('CallTracker', function() {
}); });
it("tracks the 'this' object from each execution", function() { it("tracks the 'this' object from each execution", function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
const this0 = {}, const this0 = {},
this1 = {}; this1 = {};
@@ -45,13 +45,13 @@ describe('CallTracker', function() {
}); });
it('returns any empty array when there was no call', function() { it('returns any empty array when there was no call', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
expect(callTracker.argsFor(0)).toEqual([]); expect(callTracker.argsFor(0)).toEqual([]);
}); });
it('allows access for the arguments for all calls', function() { it('allows access for the arguments for all calls', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
callTracker.track({ object: {}, args: [] }); callTracker.track({ object: {}, args: [] });
callTracker.track({ object: {}, args: [0, 'foo'] }); callTracker.track({ object: {}, args: [0, 'foo'] });
@@ -60,7 +60,7 @@ describe('CallTracker', function() {
}); });
it('tracks the context and arguments for each call', function() { it('tracks the context and arguments for each call', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
callTracker.track({ object: {}, args: [] }); callTracker.track({ object: {}, args: [] });
callTracker.track({ object: {}, args: [0, 'foo'] }); callTracker.track({ object: {}, args: [0, 'foo'] });
@@ -71,7 +71,7 @@ describe('CallTracker', function() {
}); });
it('simplifies access to the arguments for the last (most recent) call', function() { it('simplifies access to the arguments for the last (most recent) call', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
callTracker.track(); callTracker.track();
callTracker.track({ object: {}, args: [0, 'foo'] }); callTracker.track({ object: {}, args: [0, 'foo'] });
@@ -83,13 +83,13 @@ describe('CallTracker', function() {
}); });
it("returns a useful falsy value when there isn't a last (most recent) call", function() { it("returns a useful falsy value when there isn't a last (most recent) call", function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
expect(callTracker.mostRecent()).toBeFalsy(); expect(callTracker.mostRecent()).toBeFalsy();
}); });
it('simplifies access to the arguments for the first (oldest) call', function() { it('simplifies access to the arguments for the first (oldest) call', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
callTracker.track({ object: {}, args: [0, 'foo'] }); callTracker.track({ object: {}, args: [0, 'foo'] });
@@ -97,13 +97,13 @@ describe('CallTracker', function() {
}); });
it("returns a useful falsy value when there isn't a first (oldest) call", function() { it("returns a useful falsy value when there isn't a first (oldest) call", function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
expect(callTracker.first()).toBeFalsy(); expect(callTracker.first()).toBeFalsy();
}); });
it('allows the tracking to be reset', function() { it('allows the tracking to be reset', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
callTracker.track(); callTracker.track();
callTracker.track({ object: {}, args: [0, 'foo'] }); callTracker.track({ object: {}, args: [0, 'foo'] });
@@ -117,7 +117,7 @@ describe('CallTracker', function() {
}); });
it('allows object arguments to be shallow cloned', function() { it('allows object arguments to be shallow cloned', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
callTracker.saveArgumentsByValue(); callTracker.saveArgumentsByValue();
const objectArg = { foo: 'bar' }, const objectArg = { foo: 'bar' },
@@ -135,7 +135,7 @@ describe('CallTracker', function() {
}); });
it('allows object arguments to be deep cloned', function() { it('allows object arguments to be deep cloned', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
callTracker.saveArgumentsByValue(args => JSON.parse(JSON.stringify(args))); callTracker.saveArgumentsByValue(args => JSON.parse(JSON.stringify(args)));
const objectArg = { foo: { bar: { baz: ['qux'] } } }, const objectArg = { foo: { bar: { baz: ['qux'] } } },
@@ -158,7 +158,7 @@ describe('CallTracker', function() {
}); });
it('can take any function to transform arguments when saving by value', function() { it('can take any function to transform arguments when saving by value', function() {
const callTracker = new privateUnderTest.CallTracker(); const callTracker = new jasmineUnderTest.CallTracker();
callTracker.saveArgumentsByValue(JSON.stringify); callTracker.saveArgumentsByValue(JSON.stringify);
const objectArg = { foo: { bar: { baz: ['qux'] } } }, const objectArg = { foo: { bar: { baz: ['qux'] } } },
@@ -171,7 +171,7 @@ describe('CallTracker', function() {
}); });
it('saves primitive arguments by value', function() { it('saves primitive arguments by value', function() {
const callTracker = new privateUnderTest.CallTracker(), const callTracker = new jasmineUnderTest.CallTracker(),
args = [undefined, null, false, '', /\s/, 0, 1.2, NaN]; args = [undefined, null, false, '', /\s/, 0, 1.2, NaN];
callTracker.saveArgumentsByValue(); callTracker.saveArgumentsByValue();
@@ -1,6 +1,6 @@
describe('StackClearer', function() { describe('ClearStack', function() {
it('works in an integrationy way', function(done) { it('works in an integrationy way', function(done) {
const { clearStack } = privateUnderTest.getStackClearer( const clearStack = jasmineUnderTest.getClearStack(
jasmineUnderTest.getGlobal() jasmineUnderTest.getGlobal()
); );
@@ -36,7 +36,7 @@ describe('StackClearer', function() {
queueMicrotask queueMicrotask
}; };
const { clearStack } = privateUnderTest.getStackClearer(global); const clearStack = jasmineUnderTest.getClearStack(global);
for (let i = 0; i < 9; i++) { for (let i = 0; i < 9; i++) {
clearStack(function() {}); clearStack(function() {});
@@ -73,6 +73,17 @@ describe('StackClearer', function() {
} }
}; };
}); });
describe('when MessageChannel is unavailable', function() {
usesQueueMicrotaskWithSetTimeout(function() {
return {
navigator: {
userAgent: 'CERN-LineMode/2.15 libwww/2.17b3',
MessageChannel: undefined
}
};
});
});
}); });
describe('in Node', function() { describe('in Node', function() {
@@ -93,7 +104,7 @@ describe('StackClearer', function() {
...makeGlobal(), ...makeGlobal(),
MessageChannel: fakeMessageChannel MessageChannel: fakeMessageChannel
}; };
const { clearStack } = privateUnderTest.getStackClearer(global); const clearStack = jasmineUnderTest.getClearStack(global);
let called = false; let called = false;
clearStack(function() { clearStack(function() {
@@ -114,7 +125,7 @@ describe('StackClearer', function() {
return fakeChannel; return fakeChannel;
} }
}; };
const { clearStack } = privateUnderTest.getStackClearer(global); const clearStack = jasmineUnderTest.getClearStack(global);
for (let i = 0; i < 9; i++) { for (let i = 0; i < 9; i++) {
clearStack(function() {}); clearStack(function() {});
@@ -139,7 +150,7 @@ describe('StackClearer', function() {
setTimeout, setTimeout,
MessageChannel: fakeMessageChannel MessageChannel: fakeMessageChannel
}; };
const { clearStack } = privateUnderTest.getStackClearer(global); const clearStack = jasmineUnderTest.getClearStack(global);
const fn = jasmine.createSpy('second clearStack function'); const fn = jasmine.createSpy('second clearStack function');
clearStack(function() { clearStack(function() {
@@ -159,7 +170,7 @@ describe('StackClearer', function() {
fn(); fn();
} }
}; };
const { clearStack } = privateUnderTest.getStackClearer(global); const clearStack = jasmineUnderTest.getClearStack(global);
let called = false; let called = false;
clearStack(function() { clearStack(function() {
@@ -169,82 +180,30 @@ describe('StackClearer', function() {
expect(called).toBe(true); expect(called).toBe(true);
}); });
function hasSetTimeoutBehavior(configure) { it('uses setTimeout instead of queueMicrotask every 10 calls to make sure we release the CPU', function() {
it('uses setTimeout instead of queueMicrotask every 10 calls', function() { const queueMicrotask = jasmine.createSpy('queueMicrotask');
const queueMicrotask = jasmine.createSpy('queueMicrotask'); const setTimeout = jasmine.createSpy('setTimeout');
const setTimeout = jasmine.createSpy('setTimeout'); const global = {
const global = { ...makeGlobal(),
...makeGlobal(), queueMicrotask,
queueMicrotask, setTimeout
setTimeout };
}; const clearStack = jasmineUnderTest.getClearStack(global);
const stackClearer = privateUnderTest.getStackClearer(global);
if (configure) { for (let i = 0; i < 9; i++) {
configure(stackClearer); clearStack(function() {});
} }
for (let i = 0; i < 9; i++) { expect(queueMicrotask).toHaveBeenCalled();
stackClearer.clearStack(function() {}); expect(setTimeout).not.toHaveBeenCalled();
}
expect(queueMicrotask).toHaveBeenCalled(); clearStack(function() {});
expect(setTimeout).not.toHaveBeenCalled(); expect(queueMicrotask).toHaveBeenCalledTimes(9);
expect(setTimeout).toHaveBeenCalledTimes(1);
stackClearer.clearStack(function() {}); clearStack(function() {});
expect(queueMicrotask).toHaveBeenCalledTimes(9); expect(queueMicrotask).toHaveBeenCalledTimes(10);
expect(setTimeout).toHaveBeenCalledTimes(1); expect(setTimeout).toHaveBeenCalledTimes(1);
stackClearer.clearStack(function() {});
expect(queueMicrotask).toHaveBeenCalledTimes(10);
expect(setTimeout).toHaveBeenCalledTimes(1);
});
}
hasSetTimeoutBehavior();
describe('With yield strategy explicitly set to count', function() {
hasSetTimeoutBehavior(function(stackClearer) {
stackClearer.setSafariYieldStrategy('count');
});
});
describe('With yield strategy set to time', function() {
beforeEach(function() {
jasmine.clock().install();
jasmine.clock().mockDate();
});
afterEach(function() {
jasmine.clock().uninstall();
});
it('uses setTimeout instead of queueMicrotask every 25 milliseconds', function() {
const queueMicrotask = jasmine.createSpy('queueMicrotask');
const setTimeout = jasmine.createSpy('setTimeout');
const global = {
...makeGlobal(),
queueMicrotask,
setTimeout
};
const stackClearer = privateUnderTest.getStackClearer(global);
stackClearer.setSafariYieldStrategy('time');
// 10+ counts should not trigger a setTimeout if they happen fast enough
jasmine.clock().tick(24);
for (let i = 0; i < 11; i++) {
stackClearer.clearStack(function() {});
}
expect(queueMicrotask).toHaveBeenCalled();
expect(setTimeout).not.toHaveBeenCalled();
queueMicrotask.calls.reset();
jasmine.clock().tick(1);
stackClearer.clearStack(function() {});
expect(queueMicrotask).not.toHaveBeenCalled();
expect(setTimeout).toHaveBeenCalledTimes(1);
});
}); });
} }
@@ -256,7 +215,7 @@ describe('StackClearer', function() {
fn(); fn();
} }
}; };
const { clearStack } = privateUnderTest.getStackClearer(global); const clearStack = jasmineUnderTest.getClearStack(global);
let called = false; let called = false;
clearStack(function() { clearStack(function() {
@@ -274,7 +233,7 @@ describe('StackClearer', function() {
queueMicrotask, queueMicrotask,
setTimeout setTimeout
}; };
const { clearStack } = privateUnderTest.getStackClearer(global); const clearStack = jasmineUnderTest.getClearStack(global);
clearStack(function() {}); clearStack(function() {});
clearStack(function() {}); clearStack(function() {});
+55 -90
View File
@@ -17,7 +17,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -51,7 +51,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -88,7 +88,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -122,7 +122,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -154,7 +154,7 @@ describe('Clock', function() {
'delayedFunctionSchedulerFactory' 'delayedFunctionSchedulerFactory'
), ),
mockDate = {}, mockDate = {},
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
delayedFunctionSchedulerFactory, delayedFunctionSchedulerFactory,
mockDate mockDate
@@ -178,7 +178,7 @@ describe('Clock', function() {
'delayedFunctionSchedulerFactory' 'delayedFunctionSchedulerFactory'
), ),
mockDate = {}, mockDate = {},
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
delayedFunctionSchedulerFactory, delayedFunctionSchedulerFactory,
mockDate mockDate
@@ -202,7 +202,7 @@ describe('Clock', function() {
'delayedFunctionSchedulerFactory' 'delayedFunctionSchedulerFactory'
), ),
mockDate = {}, mockDate = {},
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
delayedFunctionSchedulerFactory, delayedFunctionSchedulerFactory,
mockDate mockDate
@@ -226,7 +226,7 @@ describe('Clock', function() {
'delayedFunctionSchedulerFactory' 'delayedFunctionSchedulerFactory'
), ),
mockDate = {}, mockDate = {},
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
delayedFunctionSchedulerFactory, delayedFunctionSchedulerFactory,
mockDate mockDate
@@ -263,7 +263,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -306,7 +306,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -366,7 +366,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -408,41 +408,6 @@ describe('Clock', function() {
expect(delayedFunctionScheduler.scheduleFunction).not.toHaveBeenCalled(); expect(delayedFunctionScheduler.scheduleFunction).not.toHaveBeenCalled();
}); });
it('identifies its timing functions', function() {
const fakeSetTimeout = jasmine.createSpy('global setTimeout');
const fakeGlobal = { setTimeout: fakeSetTimeout };
const delayedFunctionScheduler = jasmine.createSpyObj(
'delayedFunctionScheduler',
['scheduleFunction']
);
const mockDate = {
install: function() {},
tick: function() {},
uninstall: function() {}
};
const clock = new privateUnderTest.Clock(
fakeGlobal,
function() {
return delayedFunctionScheduler;
},
mockDate
);
clock.install();
expect(
fakeGlobal.setTimeout[privateUnderTest.Clock.IsMockClockTimingFn]
).toEqual(true);
expect(
fakeGlobal.clearTimeout[privateUnderTest.Clock.IsMockClockTimingFn]
).toEqual(true);
expect(
fakeGlobal.setInterval[privateUnderTest.Clock.IsMockClockTimingFn]
).toEqual(true);
expect(
fakeGlobal.clearInterval[privateUnderTest.Clock.IsMockClockTimingFn]
).toEqual(true);
});
describe('setTimeout', function() { describe('setTimeout', function() {
it('schedules the delayed function with the fake timer', function() { it('schedules the delayed function with the fake timer', function() {
const fakeSetTimeout = jasmine.createSpy('setTimeout'), const fakeSetTimeout = jasmine.createSpy('setTimeout'),
@@ -455,7 +420,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -500,7 +465,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -532,7 +497,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -562,7 +527,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -608,7 +573,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -640,7 +605,7 @@ describe('Clock', function() {
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
fakeGlobal, fakeGlobal,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -659,7 +624,7 @@ describe('Clock', function() {
}); });
it('gives you a friendly reminder if the Clock is not installed and you tick', function() { it('gives you a friendly reminder if the Clock is not installed and you tick', function() {
const clock = new privateUnderTest.Clock( const clock = new jasmineUnderTest.Clock(
{}, {},
jasmine.createSpyObj('delayedFunctionScheduler', ['tick']) jasmine.createSpyObj('delayedFunctionScheduler', ['tick'])
); );
@@ -675,13 +640,13 @@ describe('Clock (acceptance)', function() {
delayedFn2 = jasmine.createSpy('delayedFn2'), delayedFn2 = jasmine.createSpy('delayedFn2'),
delayedFn3 = jasmine.createSpy('delayedFn3'), delayedFn3 = jasmine.createSpy('delayedFn3'),
recurring1 = jasmine.createSpy('recurring1'), recurring1 = jasmine.createSpy('recurring1'),
delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
mockDate = { mockDate = {
install: function() {}, install: function() {},
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: setTimeout }, { setTimeout: setTimeout },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -736,7 +701,7 @@ describe('Clock (acceptance)', function() {
let clock; let clock;
beforeEach(() => { beforeEach(() => {
delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(); delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler();
mockDate = { mockDate = {
install: function() {}, install: function() {},
tick: function() {}, tick: function() {},
@@ -747,7 +712,7 @@ describe('Clock (acceptance)', function() {
typeof window !== 'undefined' ? setTimeout.bind(window) : setTimeout; typeof window !== 'undefined' ? setTimeout.bind(window) : setTimeout;
// passing a fake global allows us to preserve the real timing functions for use in tests // passing a fake global allows us to preserve the real timing functions for use in tests
const _global = { setTimeout: _setTimeout, setInterval: setInterval }; const _global = { setTimeout: _setTimeout, setInterval: setInterval };
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
_global, _global,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -885,13 +850,13 @@ describe('Clock (acceptance)', function() {
it('can clear a previously set timeout', function() { it('can clear a previously set timeout', function() {
const clearedFn = jasmine.createSpy('clearedFn'), const clearedFn = jasmine.createSpy('clearedFn'),
delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
mockDate = { mockDate = {
install: function() {}, install: function() {},
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: function() {} }, { setTimeout: function() {} },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -912,13 +877,13 @@ describe('Clock (acceptance)', function() {
it("can clear a previously set interval using that interval's handler", function() { it("can clear a previously set interval using that interval's handler", function() {
const spy = jasmine.createSpy('spy'), const spy = jasmine.createSpy('spy'),
delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
mockDate = { mockDate = {
install: function() {}, install: function() {},
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setInterval: function() {} }, { setInterval: function() {} },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -939,13 +904,13 @@ describe('Clock (acceptance)', function() {
it('correctly schedules functions after the Clock has advanced', function() { it('correctly schedules functions after the Clock has advanced', function() {
const delayedFn1 = jasmine.createSpy('delayedFn1'), const delayedFn1 = jasmine.createSpy('delayedFn1'),
delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
mockDate = { mockDate = {
install: function() {}, install: function() {},
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: function() {} }, { setTimeout: function() {} },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -966,13 +931,13 @@ describe('Clock (acceptance)', function() {
it('correctly schedules functions while the Clock is advancing', function() { it('correctly schedules functions while the Clock is advancing', function() {
const delayedFn1 = jasmine.createSpy('delayedFn1'), const delayedFn1 = jasmine.createSpy('delayedFn1'),
delayedFn2 = jasmine.createSpy('delayedFn2'), delayedFn2 = jasmine.createSpy('delayedFn2'),
delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
mockDate = { mockDate = {
install: function() {}, install: function() {},
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: function() {} }, { setTimeout: function() {} },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -997,13 +962,13 @@ describe('Clock (acceptance)', function() {
it('correctly calls functions scheduled while the Clock is advancing', function() { it('correctly calls functions scheduled while the Clock is advancing', function() {
const delayedFn1 = jasmine.createSpy('delayedFn1'), const delayedFn1 = jasmine.createSpy('delayedFn1'),
delayedFn2 = jasmine.createSpy('delayedFn2'), delayedFn2 = jasmine.createSpy('delayedFn2'),
delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
mockDate = { mockDate = {
install: function() {}, install: function() {},
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: function() {} }, { setTimeout: function() {} },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -1025,13 +990,13 @@ describe('Clock (acceptance)', function() {
it('correctly schedules functions scheduled while the Clock is advancing but after the Clock is uninstalled', function() { it('correctly schedules functions scheduled while the Clock is advancing but after the Clock is uninstalled', function() {
const delayedFn1 = jasmine.createSpy('delayedFn1'), const delayedFn1 = jasmine.createSpy('delayedFn1'),
delayedFn2 = jasmine.createSpy('delayedFn2'), delayedFn2 = jasmine.createSpy('delayedFn2'),
delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
mockDate = { mockDate = {
install: function() {}, install: function() {},
tick: function() {}, tick: function() {},
uninstall: function() {} uninstall: function() {}
}, },
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: function() {} }, { setTimeout: function() {} },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -1057,10 +1022,10 @@ describe('Clock (acceptance)', function() {
}); });
it('does not mock the Date object by default', function() { it('does not mock the Date object by default', function() {
const delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), const delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
global = { Date: Date }, global = { Date: Date },
mockDate = new privateUnderTest.MockDate(global), mockDate = new jasmineUnderTest.MockDate(global),
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: setTimeout }, { setTimeout: setTimeout },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -1080,10 +1045,10 @@ describe('Clock (acceptance)', function() {
}); });
it('mocks the Date object and sets it to current time', function() { it('mocks the Date object and sets it to current time', function() {
const delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), const delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
global = { Date: Date }, global = { Date: Date },
mockDate = new privateUnderTest.MockDate(global), mockDate = new jasmineUnderTest.MockDate(global),
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: setTimeout }, { setTimeout: setTimeout },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -1110,10 +1075,10 @@ describe('Clock (acceptance)', function() {
}); });
it('mocks the Date object and sets it to a given time', function() { it('mocks the Date object and sets it to a given time', function() {
const delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), const delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
global = { Date: Date }, global = { Date: Date },
mockDate = new privateUnderTest.MockDate(global), mockDate = new jasmineUnderTest.MockDate(global),
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: setTimeout }, { setTimeout: setTimeout },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -1143,10 +1108,10 @@ describe('Clock (acceptance)', function() {
}); });
it('throws mockDate is called with a non-Date', function() { it('throws mockDate is called with a non-Date', function() {
const delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), const delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
global = { Date: Date }, global = { Date: Date },
mockDate = new privateUnderTest.MockDate(global), mockDate = new jasmineUnderTest.MockDate(global),
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: setTimeout }, { setTimeout: setTimeout },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -1161,10 +1126,10 @@ describe('Clock (acceptance)', function() {
}); });
it('mocks the Date object and updates the date per delayed function', function() { it('mocks the Date object and updates the date per delayed function', function() {
const delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), const delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
global = { Date: Date }, global = { Date: Date },
mockDate = new privateUnderTest.MockDate(global), mockDate = new jasmineUnderTest.MockDate(global),
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
{ setTimeout: setTimeout }, { setTimeout: setTimeout },
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -1200,10 +1165,10 @@ describe('Clock (acceptance)', function() {
}); });
it('correctly clears a scheduled timeout while the Clock is advancing', function() { it('correctly clears a scheduled timeout while the Clock is advancing', function() {
const delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), const delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
global = { Date: Date, setTimeout: undefined }, global = { Date: Date, setTimeout: undefined },
mockDate = new privateUnderTest.MockDate(global), mockDate = new jasmineUnderTest.MockDate(global),
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
global, global,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -1225,10 +1190,10 @@ describe('Clock (acceptance)', function() {
}); });
it('correctly clears a scheduled interval while the Clock is advancing', function() { it('correctly clears a scheduled interval while the Clock is advancing', function() {
const delayedFunctionScheduler = new privateUnderTest.DelayedFunctionScheduler(), const delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
global = { Date: Date, setTimeout: undefined }, global = { Date: Date, setTimeout: undefined },
mockDate = new privateUnderTest.MockDate(global), mockDate = new jasmineUnderTest.MockDate(global),
clock = new privateUnderTest.Clock( clock = new jasmineUnderTest.Clock(
global, global,
function() { function() {
return delayedFunctionScheduler; return delayedFunctionScheduler;
@@ -2,7 +2,7 @@ describe('CompleteOnFirstErrorSkipPolicy', function() {
describe('#skipTo', function() { describe('#skipTo', function() {
describe('Before anything has errored', function() { describe('Before anything has errored', function() {
it('returns the next index', function() { it('returns the next index', function() {
const policy = new privateUnderTest.CompleteOnFirstErrorSkipPolicy( const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy(
arrayOfArbitraryFns(4), arrayOfArbitraryFns(4),
4 4
); );
@@ -15,7 +15,7 @@ describe('CompleteOnFirstErrorSkipPolicy', function() {
const fns = arrayOfArbitraryFns(4); const fns = arrayOfArbitraryFns(4);
fns[2].type = arbitraryCleanupType(); fns[2].type = arbitraryCleanupType();
fns[3].type = arbitraryCleanupType(); fns[3].type = arbitraryCleanupType();
const policy = new privateUnderTest.CompleteOnFirstErrorSkipPolicy(fns); const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy(fns);
policy.fnErrored(0); policy.fnErrored(0);
expect(policy.skipTo(0)).toEqual(2); expect(policy.skipTo(0)).toEqual(2);
@@ -27,7 +27,7 @@ describe('CompleteOnFirstErrorSkipPolicy', function() {
it(`does not skip ${type} fns`, function() { it(`does not skip ${type} fns`, function() {
const fns = arrayOfArbitraryFns(2); const fns = arrayOfArbitraryFns(2);
fns[1].type = type; fns[1].type = type;
const policy = new privateUnderTest.CompleteOnFirstErrorSkipPolicy( const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy(
fns fns
); );
@@ -58,7 +58,7 @@ describe('CompleteOnFirstErrorSkipPolicy', function() {
type: arbitraryCleanupType() type: arbitraryCleanupType()
} }
]; ];
const policy = new privateUnderTest.CompleteOnFirstErrorSkipPolicy( const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy(
fns fns
); );
@@ -90,7 +90,7 @@ describe('CompleteOnFirstErrorSkipPolicy', function() {
type: arbitraryCleanupType() type: arbitraryCleanupType()
} }
]; ];
const policy = new privateUnderTest.CompleteOnFirstErrorSkipPolicy( const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy(
fns fns
); );
@@ -107,7 +107,7 @@ describe('CompleteOnFirstErrorSkipPolicy', function() {
type: arbitraryCleanupType() type: arbitraryCleanupType()
} }
]; ];
const policy = new privateUnderTest.CompleteOnFirstErrorSkipPolicy(fns); const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy(fns);
policy.fnErrored(0); policy.fnErrored(0);
expect(policy.skipTo(0)).toEqual(1); expect(policy.skipTo(0)).toEqual(1);
+30 -38
View File
@@ -7,22 +7,21 @@ describe('Configuration', function() {
'hideDisabled', 'hideDisabled',
'autoCleanClosures', 'autoCleanClosures',
'forbidDuplicateNames', 'forbidDuplicateNames',
'detectLateRejectionHandling', 'detectLateRejectionHandling'
'verboseDeprecations'
]; ];
const allKeys = [ const allKeys = [
...standardBooleanKeys, ...standardBooleanKeys,
'seed', 'seed',
'specFilter', 'specFilter',
'verboseDeprecations',
'extraItStackFrames', 'extraItStackFrames',
'extraDescribeStackFrames', 'extraDescribeStackFrames'
'safariYieldStrategy'
]; ];
Object.freeze(standardBooleanKeys); Object.freeze(standardBooleanKeys);
Object.freeze(allKeys); Object.freeze(allKeys);
it('provides defaults', function() { it('provides defaults', function() {
const subject = new privateUnderTest.Configuration(); const subject = new jasmineUnderTest.Configuration();
expect(subject.random).toEqual(true); expect(subject.random).toEqual(true);
expect(subject.seed).toBeNull(); expect(subject.seed).toBeNull();
expect(subject.stopOnSpecFailure).toEqual(false); expect(subject.stopOnSpecFailure).toEqual(false);
@@ -32,17 +31,16 @@ describe('Configuration', function() {
expect(subject.specFilter()).toEqual(true); expect(subject.specFilter()).toEqual(true);
expect(subject.hideDisabled).toEqual(false); expect(subject.hideDisabled).toEqual(false);
expect(subject.autoCleanClosures).toEqual(true); expect(subject.autoCleanClosures).toEqual(true);
expect(subject.forbidDuplicateNames).toEqual(true); expect(subject.forbidDuplicateNames).toEqual(false);
expect(subject.verboseDeprecations).toEqual(false); expect(subject.verboseDeprecations).toEqual(false);
expect(subject.detectLateRejectionHandling).toEqual(false); expect(subject.detectLateRejectionHandling).toEqual(false);
expect(subject.extraItStackFrames).toEqual(0); expect(subject.extraItStackFrames).toEqual(0);
expect(subject.extraDescribeStackFrames).toEqual(0); expect(subject.extraDescribeStackFrames).toEqual(0);
expect(subject.safariYieldStrategy).toEqual('count');
}); });
describe('copy()', function() { describe('copy()', function() {
it('returns a copy of the configuration as a plain old JS object', function() { it('returns a copy of the configuration as a plain old JS object', function() {
const subject = new privateUnderTest.Configuration(); const subject = new jasmineUnderTest.Configuration();
const copy = subject.copy(); const copy = subject.copy();
@@ -57,7 +55,7 @@ describe('Configuration', function() {
describe('update()', function() { describe('update()', function() {
it('does not update properties that are absent from the parameter', function() { it('does not update properties that are absent from the parameter', function() {
const subject = new privateUnderTest.Configuration(); const subject = new jasmineUnderTest.Configuration();
const originalValues = subject.copy(); const originalValues = subject.copy();
subject.update({}); subject.update({});
@@ -66,7 +64,7 @@ describe('Configuration', function() {
function booleanPropertyBehavior(key) { function booleanPropertyBehavior(key) {
it('does not update the property if the specified value is undefined', function() { it('does not update the property if the specified value is undefined', function() {
const subject = new privateUnderTest.Configuration(); const subject = new jasmineUnderTest.Configuration();
const orig = subject[key]; const orig = subject[key];
subject.update({ [key]: undefined }); subject.update({ [key]: undefined });
@@ -75,7 +73,7 @@ describe('Configuration', function() {
}); });
it('updates the property if the specified value is not undefined', function() { it('updates the property if the specified value is not undefined', function() {
const subject = new privateUnderTest.Configuration(); const subject = new jasmineUnderTest.Configuration();
const orig = subject[key]; const orig = subject[key];
subject.update({ [key]: !orig }); subject.update({ [key]: !orig });
@@ -92,8 +90,25 @@ describe('Configuration', function() {
}); });
} }
// TODO: in the next major release, treat verboseDeprecations like other booleans
it('sets verboseDeprecations when present', function() {
const subject = new jasmineUnderTest.Configuration();
const orig = subject.verboseDeprecations;
subject.update({ verboseDeprecations: !orig });
expect(subject.verboseDeprecations).toEqual(!orig);
subject.update({ verboseDeprecations: orig });
expect(subject.verboseDeprecations).toEqual(orig);
// For backwards compatibility, explicitly setting to undefined should
// work. Undefined isn't officially valid but gets treated like false.
subject.update({ verboseDeprecations: undefined });
expect(subject.verboseDeprecations).toBeUndefined();
});
it('sets specFilter when truthy', function() { it('sets specFilter when truthy', function() {
const subject = new privateUnderTest.Configuration(); const subject = new jasmineUnderTest.Configuration();
const orig = subject.specFilter; const orig = subject.specFilter;
subject.update({ specFilter: undefined }); subject.update({ specFilter: undefined });
@@ -108,7 +123,7 @@ describe('Configuration', function() {
}); });
it('sets seed when not undefined', function() { it('sets seed when not undefined', function() {
const subject = new privateUnderTest.Configuration(); const subject = new jasmineUnderTest.Configuration();
subject.update({ seed: undefined }); subject.update({ seed: undefined });
expect(subject.seed).toBeNull(); expect(subject.seed).toBeNull();
@@ -121,7 +136,7 @@ describe('Configuration', function() {
}); });
it('sets extraItStackFrames when not undefined', function() { it('sets extraItStackFrames when not undefined', function() {
const subject = new privateUnderTest.Configuration(); const subject = new jasmineUnderTest.Configuration();
subject.update({ extraItStackFrames: undefined }); subject.update({ extraItStackFrames: undefined });
expect(subject.extraItStackFrames).toEqual(0); expect(subject.extraItStackFrames).toEqual(0);
@@ -131,7 +146,7 @@ describe('Configuration', function() {
}); });
it('sets extraDescribeStackFrames when not undefined', function() { it('sets extraDescribeStackFrames when not undefined', function() {
const subject = new privateUnderTest.Configuration(); const subject = new jasmineUnderTest.Configuration();
subject.update({ extraDescribeStackFrames: undefined }); subject.update({ extraDescribeStackFrames: undefined });
expect(subject.extraDescribeStackFrames).toEqual(0); expect(subject.extraDescribeStackFrames).toEqual(0);
@@ -139,28 +154,5 @@ describe('Configuration', function() {
subject.update({ extraDescribeStackFrames: 100000 }); subject.update({ extraDescribeStackFrames: 100000 });
expect(subject.extraDescribeStackFrames).toEqual(100000); expect(subject.extraDescribeStackFrames).toEqual(100000);
}); });
it('sets safariYieldStrategy when valid', function() {
const subject = new privateUnderTest.Configuration();
subject.update({ safariYieldStrategy: undefined });
expect(subject.safariYieldStrategy).toEqual('count');
subject.update({ safariYieldStrategy: 'time' });
expect(subject.safariYieldStrategy).toEqual('time');
subject.update({ safariYieldStrategy: 'count' });
expect(subject.safariYieldStrategy).toEqual('count');
});
it('rejcts invalid safariYieldStrategy values', function() {
const subject = new privateUnderTest.Configuration();
expect(function() {
subject.update({ safariYieldStrategy: 'thyme' });
}).toThrowError(
"Invalid safariYieldStrategy value. Valid values are 'count' and 'time'."
);
});
}); });
}); });
+27 -28
View File
@@ -1,8 +1,6 @@
describe('DelayedFunctionScheduler', function() { describe('DelayedFunctionScheduler', function() {
'use strict';
it('schedules a function for later execution', function() { it('schedules a function for later execution', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'); fn = jasmine.createSpy('fn');
scheduler.scheduleFunction(fn, 0); scheduler.scheduleFunction(fn, 0);
@@ -14,18 +12,19 @@ describe('DelayedFunctionScheduler', function() {
expect(fn).toHaveBeenCalled(); expect(fn).toHaveBeenCalled();
}); });
it('throws if a string is passed', function() { it('schedules a string for later execution', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(); const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
strfn = 'horrible = true;';
expect(function() { scheduler.scheduleFunction(strfn, 0);
scheduler.scheduleFunction('horrible = true;', 0);
}).toThrowError( scheduler.tick(0);
'The mock clock does not support the eval form of setTimeout and setInterval. Pass a function instead of a string.'
); expect(horrible).toEqual(true);
}); });
it('#tick defaults to 0', function() { it('#tick defaults to 0', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'); fn = jasmine.createSpy('fn');
scheduler.scheduleFunction(fn, 0); scheduler.scheduleFunction(fn, 0);
@@ -38,7 +37,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('defaults delay to 0', function() { it('defaults delay to 0', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'); fn = jasmine.createSpy('fn');
scheduler.scheduleFunction(fn); scheduler.scheduleFunction(fn);
@@ -51,7 +50,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('optionally passes params to scheduled functions', function() { it('optionally passes params to scheduled functions', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'); fn = jasmine.createSpy('fn');
scheduler.scheduleFunction(fn, 0, ['foo', 'bar']); scheduler.scheduleFunction(fn, 0, ['foo', 'bar']);
@@ -64,7 +63,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('scheduled fns can optionally reoccur', function() { it('scheduled fns can optionally reoccur', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'); fn = jasmine.createSpy('fn');
scheduler.scheduleFunction(fn, 20, [], true); scheduler.scheduleFunction(fn, 20, [], true);
@@ -85,7 +84,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('increments scheduled fns ids unless one is passed', function() { it('increments scheduled fns ids unless one is passed', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(); const scheduler = new jasmineUnderTest.DelayedFunctionScheduler();
const initial = scheduler.scheduleFunction(function() {}, 0); const initial = scheduler.scheduleFunction(function() {}, 0);
expect(scheduler.scheduleFunction(function() {}, 0)).toBe(initial + 1); expect(scheduler.scheduleFunction(function() {}, 0)).toBe(initial + 1);
@@ -97,7 +96,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('#removeFunctionWithId removes a previously scheduled function with a given id', function() { it('#removeFunctionWithId removes a previously scheduled function with a given id', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'), fn = jasmine.createSpy('fn'),
timeoutKey = scheduler.scheduleFunction(fn, 0); timeoutKey = scheduler.scheduleFunction(fn, 0);
@@ -111,7 +110,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('executes recurring functions interleaved with regular functions in the correct order', function() { it('executes recurring functions interleaved with regular functions in the correct order', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(); const scheduler = new jasmineUnderTest.DelayedFunctionScheduler();
const fn = jasmine.createSpy('fn'); const fn = jasmine.createSpy('fn');
let recurringCallCount = 0; let recurringCallCount = 0;
const recurring = jasmine.createSpy('recurring').and.callFake(function() { const recurring = jasmine.createSpy('recurring').and.callFake(function() {
@@ -132,7 +131,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('schedules a function for later execution during a tick', function() { it('schedules a function for later execution during a tick', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'), fn = jasmine.createSpy('fn'),
fnDelay = 10; fnDelay = 10;
@@ -148,7 +147,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('#removeFunctionWithId removes a previously scheduled function with a given id during a tick', function() { it('#removeFunctionWithId removes a previously scheduled function with a given id during a tick', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'), fn = jasmine.createSpy('fn'),
fnDelay = 10; fnDelay = 10;
let timeoutKey; let timeoutKey;
@@ -166,7 +165,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('executes recurring functions interleaved with regular functions and functions scheduled during a tick in the correct order', function() { it('executes recurring functions interleaved with regular functions and functions scheduled during a tick in the correct order', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(); const scheduler = new jasmineUnderTest.DelayedFunctionScheduler();
const fn = jasmine.createSpy('fn'); const fn = jasmine.createSpy('fn');
let recurringCallCount = 0; let recurringCallCount = 0;
const recurring = jasmine.createSpy('recurring').and.callFake(function() { const recurring = jasmine.createSpy('recurring').and.callFake(function() {
@@ -199,7 +198,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('executes recurring functions after rescheduling them', function() { it('executes recurring functions after rescheduling them', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
recurring = function() { recurring = function() {
expect(scheduler.scheduleFunction).toHaveBeenCalled(); expect(scheduler.scheduleFunction).toHaveBeenCalled();
}; };
@@ -212,7 +211,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('removes functions during a tick that runs the function', function() { it('removes functions during a tick that runs the function', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
spy = jasmine.createSpy('fn'), spy = jasmine.createSpy('fn'),
spyAndRemove = jasmine.createSpy('fn'), spyAndRemove = jasmine.createSpy('fn'),
fnDelay = 10; fnDelay = 10;
@@ -233,7 +232,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('removes functions during the first tick that runs the function', function() { it('removes functions during the first tick that runs the function', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'), fn = jasmine.createSpy('fn'),
fnDelay = 10; fnDelay = 10;
let timeoutKey; let timeoutKey;
@@ -252,7 +251,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it("does not remove a function that hasn't been added yet", function() { it("does not remove a function that hasn't been added yet", function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'), fn = jasmine.createSpy('fn'),
fnDelay = 10; fnDelay = 10;
@@ -267,7 +266,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('runs the next scheduled funtion', function() { it('runs the next scheduled funtion', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(); const scheduler = new jasmineUnderTest.DelayedFunctionScheduler();
const fn = jasmine.createSpy('fn'); const fn = jasmine.createSpy('fn');
const tickSpy = jasmine.createSpy('tick'); const tickSpy = jasmine.createSpy('tick');
@@ -282,7 +281,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('runs the only a single scheduled funtion in a time slot', function() { it('runs the only a single scheduled funtion in a time slot', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(); const scheduler = new jasmineUnderTest.DelayedFunctionScheduler();
const fn1 = jasmine.createSpy('fn'); const fn1 = jasmine.createSpy('fn');
const fn2 = jasmine.createSpy('fn2'); const fn2 = jasmine.createSpy('fn2');
const tickSpy = jasmine.createSpy('tick'); const tickSpy = jasmine.createSpy('tick');
@@ -303,7 +302,7 @@ describe('DelayedFunctionScheduler', function() {
}); });
it('updates the mockDate per scheduled time', function() { it('updates the mockDate per scheduled time', function() {
const scheduler = new privateUnderTest.DelayedFunctionScheduler(), const scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
tickDate = jasmine.createSpy('tickDate'); tickDate = jasmine.createSpy('tickDate');
scheduler.scheduleFunction(function() {}); scheduler.scheduleFunction(function() {});
@@ -325,7 +324,7 @@ describe('DelayedFunctionScheduler', function() {
} }
const nativeTimeoutId = setTimeout(function() {}, 100); const nativeTimeoutId = setTimeout(function() {}, 100);
const scheduler = new privateUnderTest.DelayedFunctionScheduler(); const scheduler = new jasmineUnderTest.DelayedFunctionScheduler();
const fn = jasmine.createSpy('fn'); const fn = jasmine.createSpy('fn');
for (let i = 0; i < nativeTimeoutId; i++) { for (let i = 0; i < nativeTimeoutId; i++) {
+14 -14
View File
@@ -7,7 +7,7 @@ describe('Deprecator', function() {
it('logs the mesage without context when the runnable is the top suite', function() { it('logs the mesage without context when the runnable is the top suite', function() {
const runnable = { addDeprecationWarning: function() {} }; const runnable = { addDeprecationWarning: function() {} };
const deprecator = new privateUnderTest.Deprecator(runnable); const deprecator = new jasmineUnderTest.Deprecator(runnable);
deprecator.verboseDeprecations(true); deprecator.verboseDeprecations(true);
deprecator.addDeprecationWarning(runnable, 'the message', { deprecator.addDeprecationWarning(runnable, 'the message', {
@@ -25,7 +25,7 @@ describe('Deprecator', function() {
}, },
children: [] children: []
}; };
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
deprecator.verboseDeprecations(true); deprecator.verboseDeprecations(true);
deprecator.addDeprecationWarning(runnable, 'the message', { deprecator.addDeprecationWarning(runnable, 'the message', {
@@ -44,7 +44,7 @@ describe('Deprecator', function() {
return 'the spec'; return 'the spec';
} }
}; };
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
deprecator.verboseDeprecations(true); deprecator.verboseDeprecations(true);
deprecator.addDeprecationWarning(runnable, 'the message', { deprecator.addDeprecationWarning(runnable, 'the message', {
@@ -61,7 +61,7 @@ describe('Deprecator', function() {
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
]); ]);
const deprecator = new privateUnderTest.Deprecator(topSuite); const deprecator = new jasmineUnderTest.Deprecator(topSuite);
const runnable = jasmine.createSpyObj('spec', [ const runnable = jasmine.createSpyObj('spec', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
@@ -105,7 +105,7 @@ describe('Deprecator', function() {
}); });
it('emits the deprecation only once when verboseDeprecations is not set', function() { it('emits the deprecation only once when verboseDeprecations is not set', function() {
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
const runnable1 = jasmine.createSpyObj('runnable1', [ const runnable1 = jasmine.createSpyObj('runnable1', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
@@ -124,7 +124,7 @@ describe('Deprecator', function() {
}); });
it('emits the deprecation only once when verboseDeprecations is false', function() { it('emits the deprecation only once when verboseDeprecations is false', function() {
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
const runnable1 = jasmine.createSpyObj('runnable1', [ const runnable1 = jasmine.createSpyObj('runnable1', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
@@ -144,7 +144,7 @@ describe('Deprecator', function() {
}); });
it('emits the deprecation for each call when verboseDeprecations is true', function() { it('emits the deprecation for each call when verboseDeprecations is true', function() {
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
const runnable1 = jasmine.createSpyObj('runnable1', [ const runnable1 = jasmine.createSpyObj('runnable1', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
@@ -164,7 +164,7 @@ describe('Deprecator', function() {
}); });
it('includes a note about verboseDeprecations', function() { it('includes a note about verboseDeprecations', function() {
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
const runnable = jasmine.createSpyObj('runnable', [ const runnable = jasmine.createSpyObj('runnable', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
@@ -183,7 +183,7 @@ describe('Deprecator', function() {
}); });
it('omits the note about verboseDeprecations when verboseDeprecations is true', function() { it('omits the note about verboseDeprecations when verboseDeprecations is true', function() {
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
const runnable = jasmine.createSpyObj('runnable', [ const runnable = jasmine.createSpyObj('runnable', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
@@ -207,7 +207,7 @@ describe('Deprecator', function() {
// to report their own deprecations through Jasmine. See // to report their own deprecations through Jasmine. See
// <https://github.com/jasmine/jasmine/pull/1498>. // <https://github.com/jasmine/jasmine/pull/1498>.
it('passes the error through unchanged', function() { it('passes the error through unchanged', function() {
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
const runnable = jasmine.createSpyObj('runnable', [ const runnable = jasmine.createSpyObj('runnable', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
@@ -238,7 +238,7 @@ describe('Deprecator', function() {
}); });
it('reports the deprecation every time, regardless of config.verboseDeprecations', function() { it('reports the deprecation every time, regardless of config.verboseDeprecations', function() {
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
const runnable = jasmine.createSpyObj('runnable', [ const runnable = jasmine.createSpyObj('runnable', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
@@ -259,7 +259,7 @@ describe('Deprecator', function() {
}); });
it('omits the note about verboseDeprecations', function() { it('omits the note about verboseDeprecations', function() {
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
const runnable = jasmine.createSpyObj('runnable', [ const runnable = jasmine.createSpyObj('runnable', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
@@ -293,7 +293,7 @@ describe('Deprecator', function() {
} }
function testStackTrace(options) { function testStackTrace(options) {
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
const runnable = jasmine.createSpyObj('runnable', [ const runnable = jasmine.createSpyObj('runnable', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
@@ -311,7 +311,7 @@ describe('Deprecator', function() {
} }
function testNoStackTrace(options) { function testNoStackTrace(options) {
const deprecator = new privateUnderTest.Deprecator({}); const deprecator = new jasmineUnderTest.Deprecator({});
const runnable = jasmine.createSpyObj('runnable', [ const runnable = jasmine.createSpyObj('runnable', [
'addDeprecationWarning', 'addDeprecationWarning',
'getFullName' 'getFullName'
+46 -46
View File
@@ -1,7 +1,7 @@
describe('Env', function() { describe('Env', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
}); });
afterEach(function() { afterEach(function() {
@@ -12,14 +12,14 @@ describe('Env', function() {
it('throws the Pending Spec exception', function() { it('throws the Pending Spec exception', function() {
expect(function() { expect(function() {
env.pending(); env.pending();
}).toThrow(privateUnderTest.Spec.pendingSpecExceptionMessage); }).toThrow(jasmineUnderTest.Spec.pendingSpecExceptionMessage);
}); });
it('throws the Pending Spec exception with a custom message', function() { it('throws the Pending Spec exception with a custom message', function() {
expect(function() { expect(function() {
env.pending('custom message'); env.pending('custom message');
}).toThrow( }).toThrow(
privateUnderTest.Spec.pendingSpecExceptionMessage + 'custom message' jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'custom message'
); );
}); });
}); });
@@ -37,24 +37,24 @@ describe('Env', function() {
}); });
const suite = env.topSuite(); const suite = env.topSuite();
expect(suite).not.toBeInstanceOf(privateUnderTest.Suite); expect(suite).not.toBeInstanceOf(jasmineUnderTest.Suite);
expect(suite.description).toEqual('Jasmine__TopLevel__Suite'); expect(suite.description).toEqual('Jasmine__TopLevel__Suite');
expect(suite.getFullName()).toEqual(''); expect(suite.getFullName()).toEqual('');
expect(suite.children.length).toEqual(2); expect(suite.children.length).toEqual(2);
expect(suite.children[0]).not.toBeInstanceOf(privateUnderTest.Spec); expect(suite.children[0]).not.toBeInstanceOf(jasmineUnderTest.Spec);
expect(suite.children[0].description).toEqual('a top level spec'); expect(suite.children[0].description).toEqual('a top level spec');
expect(suite.children[0].getFullName()).toEqual('a top level spec'); expect(suite.children[0].getFullName()).toEqual('a top level spec');
expect(suite.children[0].children).toBeFalsy(); expect(suite.children[0].children).toBeFalsy();
expect(suite.children[1]).not.toBeInstanceOf(privateUnderTest.Suite); expect(suite.children[1]).not.toBeInstanceOf(jasmineUnderTest.Suite);
expect(suite.children[1].description).toEqual('a suite'); expect(suite.children[1].description).toEqual('a suite');
expect(suite.children[1].getFullName()).toEqual('a suite'); expect(suite.children[1].getFullName()).toEqual('a suite');
expect(suite.children[1].parentSuite).toBe(suite); expect(suite.children[1].parentSuite).toBe(suite);
expect(suite.children[1].children.length).toEqual(2); expect(suite.children[1].children.length).toEqual(2);
expect(suite.children[1].children[0]).not.toBeInstanceOf( expect(suite.children[1].children[0]).not.toBeInstanceOf(
privateUnderTest.Spec jasmineUnderTest.Spec
); );
expect(suite.children[1].children[0].description).toEqual('a spec'); expect(suite.children[1].children[0].description).toEqual('a spec');
expect(suite.children[1].children[0].getFullName()).toEqual( expect(suite.children[1].children[0].getFullName()).toEqual(
@@ -101,9 +101,9 @@ describe('Env', function() {
it('can configure specs to throw errors on expectation failures', function() { it('can configure specs to throw errors on expectation failures', function() {
env.configure({ stopSpecOnExpectationFailure: true }); env.configure({ stopSpecOnExpectationFailure: true });
spyOn(privateUnderTest, 'Spec').and.callThrough(); spyOn(jasmineUnderTest, 'Spec').and.callThrough();
env.it('foo', function() {}); env.it('foo', function() {});
expect(privateUnderTest.Spec).toHaveBeenCalledWith( expect(jasmineUnderTest.Spec).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
throwOnExpectationFailure: true throwOnExpectationFailure: true
}) })
@@ -113,9 +113,9 @@ describe('Env', function() {
it('can configure suites to throw errors on expectation failures', function() { it('can configure suites to throw errors on expectation failures', function() {
env.configure({ stopSpecOnExpectationFailure: true }); env.configure({ stopSpecOnExpectationFailure: true });
spyOn(privateUnderTest, 'Suite'); spyOn(jasmineUnderTest, 'Suite');
env.describe('foo', function() {}); env.describe('foo', function() {});
expect(privateUnderTest.Suite).toHaveBeenCalledWith( expect(jasmineUnderTest.Suite).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
throwOnExpectationFailure: true throwOnExpectationFailure: true
}) })
@@ -149,9 +149,9 @@ describe('Env', function() {
}); });
it('defaults to multiple failures for specs', function() { it('defaults to multiple failures for specs', function() {
spyOn(privateUnderTest, 'Spec').and.callThrough(); spyOn(jasmineUnderTest, 'Spec').and.callThrough();
env.it('bar', function() {}); env.it('bar', function() {});
expect(privateUnderTest.Spec).toHaveBeenCalledWith( expect(jasmineUnderTest.Spec).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
throwOnExpectationFailure: false throwOnExpectationFailure: false
}) })
@@ -159,9 +159,9 @@ describe('Env', function() {
}); });
it('defaults to multiple failures for suites', function() { it('defaults to multiple failures for suites', function() {
spyOn(privateUnderTest, 'Suite'); spyOn(jasmineUnderTest, 'Suite');
env.describe('foo', function() {}); env.describe('foo', function() {});
expect(privateUnderTest.Suite).toHaveBeenCalledWith( expect(jasmineUnderTest.Suite).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
throwOnExpectationFailure: false throwOnExpectationFailure: false
}) })
@@ -378,7 +378,7 @@ describe('Env', function() {
it('calls spec.exclude with "Temporarily disabled with xit"', function() { it('calls spec.exclude with "Temporarily disabled with xit"', function() {
const excludeSpy = jasmine.createSpy(); const excludeSpy = jasmine.createSpy();
spyOn(privateUnderTest.SuiteBuilder.prototype, 'it_').and.returnValue({ spyOn(jasmineUnderTest.SuiteBuilder.prototype, 'it_').and.returnValue({
exclude: excludeSpy exclude: excludeSpy
}); });
env.xit('foo', function() {}); env.xit('foo', function() {});
@@ -387,9 +387,9 @@ describe('Env', function() {
it('calls spec.pend with "Temporarily disabled with xit"', function() { it('calls spec.pend with "Temporarily disabled with xit"', function() {
const pendSpy = jasmine.createSpy(); const pendSpy = jasmine.createSpy();
const realExclude = privateUnderTest.Spec.prototype.exclude; const realExclude = jasmineUnderTest.Spec.prototype.exclude;
spyOn(privateUnderTest.SuiteBuilder.prototype, 'it_').and.returnValue({ spyOn(jasmineUnderTest.SuiteBuilder.prototype, 'it_').and.returnValue({
exclude: realExclude, exclude: realExclude,
pend: pendSpy pend: pendSpy
}); });
@@ -528,14 +528,14 @@ describe('Env', function() {
it('does not throw an error when called in a describe', function() { it('does not throw an error when called in a describe', function() {
env.setParallelLoadingState('helpers'); env.setParallelLoadingState('helpers');
check(1); check();
env.setParallelLoadingState('specs'); env.setParallelLoadingState('specs');
check(2); check();
function check(disambiguator) { function check() {
let done = false; let done = false;
env.describe('a suite ' + disambiguator, function() { env.describe('a suite', function() {
expect(function() { expect(function() {
env.it('a spec'); env.it('a spec');
env.beforeAll(function() {}); env.beforeAll(function() {});
@@ -635,14 +635,14 @@ describe('Env', function() {
it('does not throw an error when called in a describe', function() { it('does not throw an error when called in a describe', function() {
env.setParallelLoadingState('helpers'); env.setParallelLoadingState('helpers');
check(1); check();
env.setParallelLoadingState('specs'); env.setParallelLoadingState('specs');
check(2); check();
function check(disambiguator) { function check() {
let done = false; let done = false;
env.describe('a suite ' + disambiguator, function() { env.describe('a suite', function() {
expect(function() { expect(function() {
env.it('a spec'); env.it('a spec');
env.afterAll(function() {}); env.afterAll(function() {});
@@ -667,7 +667,7 @@ describe('Env', function() {
'removeOverrideListener' 'removeOverrideListener'
]); ]);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ env = new jasmineUnderTest.Env({
GlobalErrors: function() { GlobalErrors: function() {
return globalErrors; return globalErrors;
} }
@@ -686,7 +686,7 @@ describe('Env', function() {
'removeOverrideListener' 'removeOverrideListener'
]); ]);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ env = new jasmineUnderTest.Env({
suppressLoadErrors: true, suppressLoadErrors: true,
GlobalErrors: function() { GlobalErrors: function() {
return globalErrors; return globalErrors;
@@ -702,12 +702,12 @@ describe('Env', function() {
function customEqualityTester() {} function customEqualityTester() {}
function customObjectFormatter() {} function customObjectFormatter() {}
function prettyPrinter() {} function prettyPrinter() {}
const RealSpec = privateUnderTest.Spec; const RealSpec = jasmineUnderTest.Spec;
let specInstance; let specInstance;
let expectationFactory; let expectationFactory;
spyOn(privateUnderTest, 'MatchersUtil'); spyOn(jasmineUnderTest, 'MatchersUtil');
spyOn(privateUnderTest, 'makePrettyPrinter').and.returnValue(prettyPrinter); spyOn(jasmineUnderTest, 'makePrettyPrinter').and.returnValue(prettyPrinter);
spyOn(privateUnderTest, 'Spec').and.callFake(function(options) { spyOn(jasmineUnderTest, 'Spec').and.callFake(function(options) {
expectationFactory = options.expectationFactory; expectationFactory = options.expectationFactory;
specInstance = new RealSpec(options); specInstance = new RealSpec(options);
return specInstance; return specInstance;
@@ -720,10 +720,10 @@ describe('Env', function() {
}); });
await env.execute(); await env.execute();
expect(privateUnderTest.makePrettyPrinter).toHaveBeenCalledWith([ expect(jasmineUnderTest.makePrettyPrinter).toHaveBeenCalledWith([
customObjectFormatter customObjectFormatter
]); ]);
expect(privateUnderTest.MatchersUtil).toHaveBeenCalledWith({ expect(jasmineUnderTest.MatchersUtil).toHaveBeenCalledWith({
customTesters: [customEqualityTester], customTesters: [customEqualityTester],
pp: prettyPrinter pp: prettyPrinter
}); });
@@ -733,12 +733,12 @@ describe('Env', function() {
function customEqualityTester() {} function customEqualityTester() {}
function customObjectFormatter() {} function customObjectFormatter() {}
function prettyPrinter() {} function prettyPrinter() {}
const RealSpec = privateUnderTest.Spec; const RealSpec = jasmineUnderTest.Spec;
let specInstance; let specInstance;
let asyncExpectationFactory; let asyncExpectationFactory;
spyOn(privateUnderTest, 'MatchersUtil'); spyOn(jasmineUnderTest, 'MatchersUtil');
spyOn(privateUnderTest, 'makePrettyPrinter').and.returnValue(prettyPrinter); spyOn(jasmineUnderTest, 'makePrettyPrinter').and.returnValue(prettyPrinter);
spyOn(privateUnderTest, 'Spec').and.callFake(function(options) { spyOn(jasmineUnderTest, 'Spec').and.callFake(function(options) {
asyncExpectationFactory = options.asyncExpectationFactory; asyncExpectationFactory = options.asyncExpectationFactory;
specInstance = new RealSpec(options); specInstance = new RealSpec(options);
return specInstance; return specInstance;
@@ -752,10 +752,10 @@ describe('Env', function() {
await env.execute(); await env.execute();
expect(privateUnderTest.makePrettyPrinter).toHaveBeenCalledWith([ expect(jasmineUnderTest.makePrettyPrinter).toHaveBeenCalledWith([
customObjectFormatter customObjectFormatter
]); ]);
expect(privateUnderTest.MatchersUtil).toHaveBeenCalledWith({ expect(jasmineUnderTest.MatchersUtil).toHaveBeenCalledWith({
customTesters: [customEqualityTester], customTesters: [customEqualityTester],
pp: prettyPrinter pp: prettyPrinter
}); });
@@ -770,7 +770,7 @@ describe('Env', function() {
env.it('has a spec'); env.it('has a spec');
}); });
expect(suiteThis).not.toBeInstanceOf(privateUnderTest.Suite); expect(suiteThis).not.toBeInstanceOf(jasmineUnderTest.Suite);
}); });
describe('#execute', function() { describe('#execute', function() {
@@ -779,7 +779,7 @@ describe('Env', function() {
}); });
it('should reset the topSuite when run twice', function() { it('should reset the topSuite when run twice', function() {
spyOn(privateUnderTest.Suite.prototype, 'reset'); spyOn(jasmineUnderTest.Suite.prototype, 'reset');
return env return env
.execute() // 1 .execute() // 1
.then(function() { .then(function() {
@@ -787,9 +787,9 @@ describe('Env', function() {
}) })
.then(function() { .then(function() {
expect( expect(
privateUnderTest.Suite.prototype.reset jasmineUnderTest.Suite.prototype.reset
).toHaveBeenCalledOnceWith(); ).toHaveBeenCalledOnceWith();
const id = privateUnderTest.Suite.prototype.reset.calls.thisFor(0).id; const id = jasmineUnderTest.Suite.prototype.reset.calls.thisFor(0).id;
expect(id).toBeTruthy(); expect(id).toBeTruthy();
expect(id).toEqual(env.topSuite().id); expect(id).toEqual(env.topSuite().id);
}); });
@@ -798,9 +798,9 @@ describe('Env', function() {
it('should not reset the topSuite if parallelReset was called since the last run', async function() { it('should not reset the topSuite if parallelReset was called since the last run', async function() {
await env.execute(); await env.execute();
env.parallelReset(); env.parallelReset();
spyOn(privateUnderTest.Suite.prototype, 'reset'); spyOn(jasmineUnderTest.Suite.prototype, 'reset');
await env.execute(); await env.execute();
expect(privateUnderTest.Suite.prototype.reset).not.toHaveBeenCalled(); expect(jasmineUnderTest.Suite.prototype.reset).not.toHaveBeenCalled();
}); });
describe('In parallel mode', function() { describe('In parallel mode', function() {
+24 -24
View File
@@ -7,7 +7,7 @@ describe('ExceptionFormatter', function() {
message: 'you got your foo in my bar', message: 'you got your foo in my bar',
name: 'A Classic Mistake' name: 'A Classic Mistake'
}, },
exceptionFormatter = new privateUnderTest.ExceptionFormatter(), exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(sampleFirefoxException); message = exceptionFormatter.message(sampleFirefoxException);
expect(message).toEqual( expect(message).toEqual(
@@ -22,7 +22,7 @@ describe('ExceptionFormatter', function() {
message: 'you got your foo in my bar', message: 'you got your foo in my bar',
name: 'A Classic Mistake' name: 'A Classic Mistake'
}, },
exceptionFormatter = new privateUnderTest.ExceptionFormatter(), exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(sampleWebkitException); message = exceptionFormatter.message(sampleWebkitException);
expect(message).toEqual( expect(message).toEqual(
@@ -35,7 +35,7 @@ describe('ExceptionFormatter', function() {
message: 'you got your foo in my bar', message: 'you got your foo in my bar',
name: 'A Classic Mistake' name: 'A Classic Mistake'
}, },
exceptionFormatter = new privateUnderTest.ExceptionFormatter(), exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(sampleV8); message = exceptionFormatter.message(sampleV8);
expect(message).toEqual('A Classic Mistake: you got your foo in my bar'); expect(message).toEqual('A Classic Mistake: you got your foo in my bar');
@@ -44,7 +44,7 @@ describe('ExceptionFormatter', function() {
it('formats unnamed exceptions with message', function() { it('formats unnamed exceptions with message', function() {
const unnamedError = { message: 'This is an unnamed error message.' }; const unnamedError = { message: 'This is an unnamed error message.' };
const exceptionFormatter = new privateUnderTest.ExceptionFormatter(), const exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(unnamedError); message = exceptionFormatter.message(unnamedError);
expect(message).toEqual('This is an unnamed error message.'); expect(message).toEqual('This is an unnamed error message.');
@@ -57,7 +57,7 @@ describe('ExceptionFormatter', function() {
}; };
const emptyError = new EmptyError(); const emptyError = new EmptyError();
const exceptionFormatter = new privateUnderTest.ExceptionFormatter(), const exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(emptyError); message = exceptionFormatter.message(emptyError);
expect(message).toEqual('[EmptyError] thrown'); expect(message).toEqual('[EmptyError] thrown');
@@ -65,7 +65,7 @@ describe('ExceptionFormatter', function() {
it("formats thrown exceptions that aren't errors", function() { it("formats thrown exceptions that aren't errors", function() {
const thrown = 'crazy error', const thrown = 'crazy error',
exceptionFormatter = new privateUnderTest.ExceptionFormatter(), exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(thrown); message = exceptionFormatter.message(thrown);
expect(message).toEqual('crazy error thrown'); expect(message).toEqual('crazy error thrown');
@@ -76,7 +76,7 @@ describe('ExceptionFormatter', function() {
it('formats stack traces', function() { it('formats stack traces', function() {
const error = new Error('an error'); const error = new Error('an error');
expect(new privateUnderTest.ExceptionFormatter().stack(error)).toMatch( expect(new jasmineUnderTest.ExceptionFormatter().stack(error)).toMatch(
/ExceptionFormatterSpec\.js.*\d+/ /ExceptionFormatterSpec\.js.*\d+/
); );
}); });
@@ -96,7 +96,7 @@ describe('ExceptionFormatter', function() {
' at fn3 (C:\\__jasmine__\\lib\\jasmine-core\\jasmine.js:7575:25)\n' + ' at fn3 (C:\\__jasmine__\\lib\\jasmine-core\\jasmine.js:7575:25)\n' +
' at fn4 (node:internal/timers:462:21)\n' ' at fn4 (node:internal/timers:462:21)\n'
}; };
const subject = new privateUnderTest.ExceptionFormatter({ const subject = new jasmineUnderTest.ExceptionFormatter({
jasmineFile: 'C:\\__jasmine__\\lib\\jasmine-core\\jasmine.js' jasmineFile: 'C:\\__jasmine__\\lib\\jasmine-core\\jasmine.js'
}); });
const result = subject.stack(error); const result = subject.stack(error);
@@ -122,7 +122,7 @@ describe('ExceptionFormatter', function() {
' at fn3 (http://localhost:8888/__jasmine__/jasmine.js:4320:20)\n' + ' at fn3 (http://localhost:8888/__jasmine__/jasmine.js:4320:20)\n' +
' at fn4 (http://localhost:8888/__spec__/core/UtilSpec.js:110:19)\n' ' at fn4 (http://localhost:8888/__spec__/core/UtilSpec.js:110:19)\n'
}; };
const subject = new privateUnderTest.ExceptionFormatter({ const subject = new jasmineUnderTest.ExceptionFormatter({
jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js' jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js'
}); });
const result = subject.stack(error); const result = subject.stack(error);
@@ -142,7 +142,7 @@ describe('ExceptionFormatter', function() {
'fn2@http://localhost:8888/__jasmine__/jasmine.js:4320:27\n' + 'fn2@http://localhost:8888/__jasmine__/jasmine.js:4320:27\n' +
'http://localhost:8888/__spec__/core/UtilSpec.js:115:28' 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28'
}; };
const subject = new privateUnderTest.ExceptionFormatter({ const subject = new jasmineUnderTest.ExceptionFormatter({
jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js' jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js'
}); });
const result = subject.stack(error); const result = subject.stack(error);
@@ -161,7 +161,7 @@ describe('ExceptionFormatter', function() {
'setTimeout handler*fn2@http://localhost:8888/__jasmine__/jasmine.js:4320:27\n' + 'setTimeout handler*fn2@http://localhost:8888/__jasmine__/jasmine.js:4320:27\n' +
'http://localhost:8888/__spec__/core/UtilSpec.js:115:28' 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28'
}; };
const subject = new privateUnderTest.ExceptionFormatter({ const subject = new jasmineUnderTest.ExceptionFormatter({
jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js' jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js'
}); });
const result = subject.stack(error); const result = subject.stack(error);
@@ -174,8 +174,8 @@ describe('ExceptionFormatter', function() {
it('filters Jasmine stack frames in this environment', function() { it('filters Jasmine stack frames in this environment', function() {
const error = new Error('an error'); const error = new Error('an error');
const subject = new privateUnderTest.ExceptionFormatter({ const subject = new jasmineUnderTest.ExceptionFormatter({
jasmineFile: jasmine.private.util.jasmineFile() jasmineFile: jasmine.util.jasmineFile()
}); });
const result = subject.stack(error); const result = subject.stack(error);
jasmine.debugLog('Original stack trace: ' + error.stack); jasmine.debugLog('Original stack trace: ' + error.stack);
@@ -202,8 +202,8 @@ describe('ExceptionFormatter', function() {
if (error.stack.indexOf(msg) === -1) { if (error.stack.indexOf(msg) === -1) {
pending("Stack traces don't have messages in this environment"); pending("Stack traces don't have messages in this environment");
} }
const subject = new privateUnderTest.ExceptionFormatter({ const subject = new jasmineUnderTest.ExceptionFormatter({
jasmineFile: jasmine.private.util.jasmineFile() jasmineFile: jasmine.util.jasmineFile()
}); });
const result = subject.stack(error); const result = subject.stack(error);
const lines = result.split('\n'); const lines = result.split('\n');
@@ -215,14 +215,14 @@ describe('ExceptionFormatter', function() {
}); });
it('returns null if no Error provided', function() { it('returns null if no Error provided', function() {
expect(new privateUnderTest.ExceptionFormatter().stack()).toBeNull(); expect(new jasmineUnderTest.ExceptionFormatter().stack()).toBeNull();
}); });
it("includes the error's own properties in stack", function() { it("includes the error's own properties in stack", function() {
const error = new Error('an error'); const error = new Error('an error');
error.someProperty = 'hello there'; error.someProperty = 'hello there';
const result = new privateUnderTest.ExceptionFormatter().stack(error); const result = new jasmineUnderTest.ExceptionFormatter().stack(error);
expect(result).toMatch(/error properties:.*someProperty.*hello there/); expect(result).toMatch(/error properties:.*someProperty.*hello there/);
}); });
@@ -236,7 +236,7 @@ describe('ExceptionFormatter', function() {
CustomError.prototype.anInheritedProp = 'something'; CustomError.prototype.anInheritedProp = 'something';
const error = new CustomError('nope'); const error = new CustomError('nope');
const result = new privateUnderTest.ExceptionFormatter().stack(error); const result = new jasmineUnderTest.ExceptionFormatter().stack(error);
expect(result).not.toContain('anInheritedProp'); expect(result).not.toContain('anInheritedProp');
}); });
@@ -251,7 +251,7 @@ describe('ExceptionFormatter', function() {
' at fn3 (http://localhost:8888/__jasmine__/jasmine.js:4320:20)\n' + ' at fn3 (http://localhost:8888/__jasmine__/jasmine.js:4320:20)\n' +
' at fn4 (http://localhost:8888/__spec__/core/UtilSpec.js:110:19)\n' ' at fn4 (http://localhost:8888/__spec__/core/UtilSpec.js:110:19)\n'
}; };
const subject = new privateUnderTest.ExceptionFormatter({ const subject = new jasmineUnderTest.ExceptionFormatter({
jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js' jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js'
}); });
const result = subject.stack(error, { omitMessage: true }); const result = subject.stack(error, { omitMessage: true });
@@ -270,7 +270,7 @@ describe('ExceptionFormatter', function() {
'fn2@http://localhost:8888/__jasmine__/jasmine.js:4320:27\n' + 'fn2@http://localhost:8888/__jasmine__/jasmine.js:4320:27\n' +
'http://localhost:8888/__spec__/core/UtilSpec.js:115:28' 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28'
}; };
const subject = new privateUnderTest.ExceptionFormatter({ const subject = new jasmineUnderTest.ExceptionFormatter({
jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js' jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js'
}); });
const result = subject.stack(error, { omitMessage: true }); const result = subject.stack(error, { omitMessage: true });
@@ -283,8 +283,8 @@ describe('ExceptionFormatter', function() {
it('ensures that stack traces do not include the message in this environment', function() { it('ensures that stack traces do not include the message in this environment', function() {
const error = new Error('an error'); const error = new Error('an error');
const subject = new privateUnderTest.ExceptionFormatter({ const subject = new jasmineUnderTest.ExceptionFormatter({
jasmineFile: jasmine.private.util.jasmineFile() jasmineFile: jasmine.util.jasmineFile()
}); });
const result = subject.stack(error, { omitMessage: true }); const result = subject.stack(error, { omitMessage: true });
expect(result).not.toContain('an error'); expect(result).not.toContain('an error');
@@ -293,7 +293,7 @@ describe('ExceptionFormatter', function() {
describe('when the error has a cause property', function() { describe('when the error has a cause property', function() {
it('recursively includes the cause in the stack trace in this environment', function() { it('recursively includes the cause in the stack trace in this environment', function() {
const subject = new privateUnderTest.ExceptionFormatter(); const subject = new jasmineUnderTest.ExceptionFormatter();
const rootCause = new Error('root cause'); const rootCause = new Error('root cause');
const proximateCause = new Error('proximate cause', { const proximateCause = new Error('proximate cause', {
cause: rootCause cause: rootCause
@@ -327,7 +327,7 @@ describe('ExceptionFormatter', function() {
}); });
it('does not throw if cause is a non Error', function() { it('does not throw if cause is a non Error', function() {
const formatter = new privateUnderTest.ExceptionFormatter(); const formatter = new jasmineUnderTest.ExceptionFormatter();
expect(function() { expect(function() {
formatter.stack( formatter.stack(
+1 -1
View File
@@ -2,7 +2,7 @@ describe('Exceptions:', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
}); });
afterEach(function() { afterEach(function() {
+8 -8
View File
@@ -3,7 +3,7 @@ describe('ExpectationFilterChain', function() {
it('returns a new filter chain with the added filter', function() { it('returns a new filter chain with the added filter', function() {
const first = jasmine.createSpy('first'), const first = jasmine.createSpy('first'),
second = jasmine.createSpy('second'), second = jasmine.createSpy('second'),
orig = new privateUnderTest.ExpectationFilterChain({ orig = new jasmineUnderTest.ExpectationFilterChain({
modifyFailureMessage: first modifyFailureMessage: first
}), }),
added = orig.addFilter({ selectComparisonFunc: second }); added = orig.addFilter({ selectComparisonFunc: second });
@@ -15,7 +15,7 @@ describe('ExpectationFilterChain', function() {
}); });
it('does not modify the original filter chain', function() { it('does not modify the original filter chain', function() {
const orig = new privateUnderTest.ExpectationFilterChain({}), const orig = new jasmineUnderTest.ExpectationFilterChain({}),
f = jasmine.createSpy('f'); f = jasmine.createSpy('f');
orig.addFilter({ selectComparisonFunc: f }); orig.addFilter({ selectComparisonFunc: f });
@@ -28,7 +28,7 @@ describe('ExpectationFilterChain', function() {
describe('#selectComparisonFunc', function() { describe('#selectComparisonFunc', function() {
describe('When no filters have #selectComparisonFunc', function() { describe('When no filters have #selectComparisonFunc', function() {
it('returns undefined', function() { it('returns undefined', function() {
const chain = new privateUnderTest.ExpectationFilterChain(); const chain = new jasmineUnderTest.ExpectationFilterChain();
chain.addFilter({}); chain.addFilter({});
expect(chain.selectComparisonFunc()).toBeUndefined(); expect(chain.selectComparisonFunc()).toBeUndefined();
}); });
@@ -38,7 +38,7 @@ describe('ExpectationFilterChain', function() {
it('calls the first filter that has #selectComparisonFunc', function() { it('calls the first filter that has #selectComparisonFunc', function() {
const first = jasmine.createSpy('first').and.returnValue('first'), const first = jasmine.createSpy('first').and.returnValue('first'),
second = jasmine.createSpy('second').and.returnValue('second'), second = jasmine.createSpy('second').and.returnValue('second'),
chain = new privateUnderTest.ExpectationFilterChain() chain = new jasmineUnderTest.ExpectationFilterChain()
.addFilter({ selectComparisonFunc: first }) .addFilter({ selectComparisonFunc: first })
.addFilter({ selectComparisonFunc: second }), .addFilter({ selectComparisonFunc: second }),
matcher = {}, matcher = {},
@@ -54,7 +54,7 @@ describe('ExpectationFilterChain', function() {
describe('#buildFailureMessage', function() { describe('#buildFailureMessage', function() {
describe('When no filters have #buildFailureMessage', function() { describe('When no filters have #buildFailureMessage', function() {
it('returns undefined', function() { it('returns undefined', function() {
const chain = new privateUnderTest.ExpectationFilterChain(); const chain = new jasmineUnderTest.ExpectationFilterChain();
chain.addFilter({}); chain.addFilter({});
expect(chain.buildFailureMessage()).toBeUndefined(); expect(chain.buildFailureMessage()).toBeUndefined();
}); });
@@ -64,7 +64,7 @@ describe('ExpectationFilterChain', function() {
it('calls the first filter that has #buildFailureMessage', function() { it('calls the first filter that has #buildFailureMessage', function() {
const first = jasmine.createSpy('first').and.returnValue('first'), const first = jasmine.createSpy('first').and.returnValue('first'),
second = jasmine.createSpy('second').and.returnValue('second'), second = jasmine.createSpy('second').and.returnValue('second'),
chain = new privateUnderTest.ExpectationFilterChain() chain = new jasmineUnderTest.ExpectationFilterChain()
.addFilter({ buildFailureMessage: first }) .addFilter({ buildFailureMessage: first })
.addFilter({ buildFailureMessage: second }), .addFilter({ buildFailureMessage: second }),
matcherResult = { pass: false }, matcherResult = { pass: false },
@@ -94,7 +94,7 @@ describe('ExpectationFilterChain', function() {
describe('#modifyFailureMessage', function() { describe('#modifyFailureMessage', function() {
describe('When no filters have #modifyFailureMessage', function() { describe('When no filters have #modifyFailureMessage', function() {
it('returns the original message', function() { it('returns the original message', function() {
const chain = new privateUnderTest.ExpectationFilterChain(); const chain = new jasmineUnderTest.ExpectationFilterChain();
chain.addFilter({}); chain.addFilter({});
expect(chain.modifyFailureMessage('msg')).toEqual('msg'); expect(chain.modifyFailureMessage('msg')).toEqual('msg');
}); });
@@ -104,7 +104,7 @@ describe('ExpectationFilterChain', function() {
it('calls the first filter that has #modifyFailureMessage', function() { it('calls the first filter that has #modifyFailureMessage', function() {
const first = jasmine.createSpy('first').and.returnValue('first'), const first = jasmine.createSpy('first').and.returnValue('first'),
second = jasmine.createSpy('second').and.returnValue('second'), second = jasmine.createSpy('second').and.returnValue('second'),
chain = new privateUnderTest.ExpectationFilterChain() chain = new jasmineUnderTest.ExpectationFilterChain()
.addFilter({ modifyFailureMessage: first }) .addFilter({ modifyFailureMessage: first })
.addFilter({ modifyFailureMessage: second }), .addFilter({ modifyFailureMessage: second }),
result = chain.modifyFailureMessage('original'); result = chain.modifyFailureMessage('original');
+59 -30
View File
@@ -4,7 +4,7 @@ describe('Expectation', function() {
toFoo: function() {}, toFoo: function() {},
toBar: function() {} toBar: function() {}
}, },
expectation = privateUnderTest.Expectation.factory({ expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers customMatchers: matchers
}); });
@@ -17,9 +17,9 @@ describe('Expectation', function() {
toQuux: function() {} toQuux: function() {}
}; };
privateUnderTest.Expectation.addCoreMatchers(coreMatchers); jasmineUnderTest.Expectation.addCoreMatchers(coreMatchers);
const expectation = privateUnderTest.Expectation.factory({}); const expectation = jasmineUnderTest.Expectation.factory({});
expect(expectation.toQuux).toBeDefined(); expect(expectation.toQuux).toBeDefined();
}); });
@@ -39,7 +39,7 @@ describe('Expectation', function() {
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
@@ -67,7 +67,7 @@ describe('Expectation', function() {
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
@@ -94,7 +94,7 @@ describe('Expectation', function() {
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
actual: 'an actual', actual: 'an actual',
@@ -108,6 +108,8 @@ describe('Expectation', function() {
passed: true, passed: true,
message: '', message: '',
error: undefined, error: undefined,
expected: 'hello',
actual: 'an actual',
errorForStack: undefined errorForStack: undefined
}); });
}); });
@@ -129,7 +131,7 @@ describe('Expectation', function() {
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
actual: 'an actual', actual: 'an actual',
@@ -141,6 +143,8 @@ describe('Expectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: '', message: '',
error: undefined, error: undefined,
errorForStack: undefined errorForStack: undefined
@@ -162,7 +166,7 @@ describe('Expectation', function() {
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
actual: 'an actual', actual: 'an actual',
customMatchers: matchers, customMatchers: matchers,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -173,6 +177,8 @@ describe('Expectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message', message: 'I am a custom message',
error: undefined, error: undefined,
errorForStack: undefined errorForStack: undefined
@@ -196,7 +202,7 @@ describe('Expectation', function() {
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -207,6 +213,8 @@ describe('Expectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message', message: 'I am a custom message',
error: undefined, error: undefined,
errorForStack: undefined errorForStack: undefined
@@ -223,9 +231,10 @@ describe('Expectation', function() {
}; };
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = 'an actual';
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -238,6 +247,8 @@ describe('Expectation', function() {
passed: true, passed: true,
message: '', message: '',
error: undefined, error: undefined,
expected: 'hello',
actual: actual,
errorForStack: undefined errorForStack: undefined
}); });
}); });
@@ -257,9 +268,10 @@ describe('Expectation', function() {
return 'default message'; return 'default message';
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = 'an actual';
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
@@ -271,6 +283,8 @@ describe('Expectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: actual,
message: 'default message', message: 'default message',
error: undefined, error: undefined,
errorForStack: undefined errorForStack: undefined
@@ -290,9 +304,10 @@ describe('Expectation', function() {
}; };
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = 'an actual';
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -303,6 +318,8 @@ describe('Expectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: actual,
message: 'I am a custom message', message: 'I am a custom message',
error: undefined, error: undefined,
errorForStack: undefined errorForStack: undefined
@@ -322,9 +339,10 @@ describe('Expectation', function() {
}; };
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = 'an actual';
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -335,6 +353,8 @@ describe('Expectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(true, { expect(addExpectationResult).toHaveBeenCalledWith(true, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: true, passed: true,
expected: 'hello',
actual: actual,
message: '', message: '',
error: undefined, error: undefined,
errorForStack: undefined errorForStack: undefined
@@ -357,9 +377,10 @@ describe('Expectation', function() {
}; };
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = 'an actual';
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -370,6 +391,8 @@ describe('Expectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: actual,
message: "I'm a custom message", message: "I'm a custom message",
error: undefined, error: undefined,
errorForStack: undefined errorForStack: undefined
@@ -393,7 +416,7 @@ describe('Expectation', function() {
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
actual: 'an actual', actual: 'an actual',
customMatchers: matchers, customMatchers: matchers,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -404,6 +427,8 @@ describe('Expectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message', message: 'I am a custom message',
error: customError, error: customError,
errorForStack: undefined errorForStack: undefined
@@ -427,7 +452,7 @@ describe('Expectation', function() {
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
actual: 'an actual', actual: 'an actual',
customMatchers: matchers, customMatchers: matchers,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -438,6 +463,8 @@ describe('Expectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message', message: 'I am a custom message',
error: customError, error: customError,
errorForStack: undefined errorForStack: undefined
@@ -463,7 +490,7 @@ describe('Expectation', function() {
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'); addExpectationResult = jasmine.createSpy('addExpectationResult');
const expectation = privateUnderTest.Expectation.factory({ const expectation = jasmineUnderTest.Expectation.factory({
actual: 'an actual', actual: 'an actual',
customMatchers: matchers, customMatchers: matchers,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -474,6 +501,8 @@ describe('Expectation', function() {
expect(addExpectationResult).toHaveBeenCalledWith(false, { expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo', matcherName: 'toFoo',
passed: false, passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message', message: 'I am a custom message',
error: customError, error: customError,
errorForStack: undefined errorForStack: undefined
@@ -497,7 +526,7 @@ describe('Expectation', function() {
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = privateUnderTest.Expectation.factory({ expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
matchersUtil: matchersUtil, matchersUtil: matchersUtil,
actual: 'an actual', actual: 'an actual',
@@ -525,7 +554,7 @@ describe('Expectation', function() {
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = privateUnderTest.Expectation.factory({ expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -552,7 +581,7 @@ describe('Expectation', function() {
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = privateUnderTest.Expectation.factory({ expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -582,7 +611,7 @@ describe('Expectation', function() {
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = privateUnderTest.Expectation.factory({ expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
@@ -609,10 +638,10 @@ describe('Expectation', function() {
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
pp = privateUnderTest.makePrettyPrinter(), pp = jasmineUnderTest.makePrettyPrinter(),
expectation = privateUnderTest.Expectation.factory({ expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
matchersUtil: new privateUnderTest.MatchersUtil({ pp: pp }), matchersUtil: new jasmineUnderTest.MatchersUtil({ pp: pp }),
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
}); });
@@ -645,7 +674,7 @@ describe('Expectation', function() {
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = privateUnderTest.Expectation.factory({ expectation = jasmineUnderTest.Expectation.factory({
actual: 'an actual', actual: 'an actual',
customMatchers: matchers, customMatchers: matchers,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
+68 -73
View File
@@ -2,7 +2,7 @@ describe('GlobalErrors', function() {
it('calls the added handler on error', function() { it('calls the added handler on error', function() {
const globals = browserGlobals(); const globals = browserGlobals();
const handler = jasmine.createSpy('errorHandler'); const handler = jasmine.createSpy('errorHandler');
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -13,13 +13,16 @@ describe('GlobalErrors', function() {
const error = new Error('nope'); const error = new Error('nope');
dispatchEvent(globals.listeners, 'error', { error }); dispatchEvent(globals.listeners, 'error', { error });
expect(handler).toHaveBeenCalledWith(jasmine.is(error)); expect(handler).toHaveBeenCalledWith(
jasmine.is(error),
jasmine.objectContaining({ error: jasmine.is(error) })
);
}); });
it('is not affected by overriding global.onerror', function() { it('is not affected by overriding global.onerror', function() {
const globals = browserGlobals(); const globals = browserGlobals();
const handler = jasmine.createSpy('errorHandler'); const handler = jasmine.createSpy('errorHandler');
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -32,14 +35,17 @@ describe('GlobalErrors', function() {
const error = new Error('nope'); const error = new Error('nope');
dispatchEvent(globals.listeners, 'error', { error }); dispatchEvent(globals.listeners, 'error', { error });
expect(handler).toHaveBeenCalledWith(jasmine.is(error)); expect(handler).toHaveBeenCalledWith(
jasmine.is(error),
jasmine.objectContaining({ error: jasmine.is(error) })
);
}); });
it('only calls the most recent handler', function() { it('only calls the most recent handler', function() {
const globals = browserGlobals(); const globals = browserGlobals();
const handler1 = jasmine.createSpy('errorHandler1'); const handler1 = jasmine.createSpy('errorHandler1');
const handler2 = jasmine.createSpy('errorHandler2'); const handler2 = jasmine.createSpy('errorHandler2');
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -52,14 +58,17 @@ describe('GlobalErrors', function() {
dispatchEvent(globals.listeners, 'error', { error }); dispatchEvent(globals.listeners, 'error', { error });
expect(handler1).not.toHaveBeenCalled(); expect(handler1).not.toHaveBeenCalled();
expect(handler2).toHaveBeenCalledWith(jasmine.is(error)); expect(handler2).toHaveBeenCalledWith(
jasmine.is(error),
jasmine.objectContaining({ error: jasmine.is(error) })
);
}); });
it('calls previous handlers when one is removed', function() { it('calls previous handlers when one is removed', function() {
const globals = browserGlobals(); const globals = browserGlobals();
const handler1 = jasmine.createSpy('errorHandler1'); const handler1 = jasmine.createSpy('errorHandler1');
const handler2 = jasmine.createSpy('errorHandler2'); const handler2 = jasmine.createSpy('errorHandler2');
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -73,12 +82,15 @@ describe('GlobalErrors', function() {
const error = new Error('nope'); const error = new Error('nope');
dispatchEvent(globals.listeners, 'error', { error }); dispatchEvent(globals.listeners, 'error', { error });
expect(handler1).toHaveBeenCalledWith(jasmine.is(error)); expect(handler1).toHaveBeenCalledWith(
jasmine.is(error),
jasmine.objectContaining({ error: jasmine.is(error) })
);
expect(handler2).not.toHaveBeenCalled(); expect(handler2).not.toHaveBeenCalled();
}); });
it('throws when no listener is passed to #popListener', function() { it('throws when no listener is passed to #popListener', function() {
const errors = new privateUnderTest.GlobalErrors({}); const errors = new jasmineUnderTest.GlobalErrors({});
expect(function() { expect(function() {
errors.popListener(); errors.popListener();
}).toThrowError('popListener expects a listener'); }).toThrowError('popListener expects a listener');
@@ -86,7 +98,7 @@ describe('GlobalErrors', function() {
it('uninstalls itself', function() { it('uninstalls itself', function() {
const globals = browserGlobals(); const globals = browserGlobals();
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -101,7 +113,7 @@ describe('GlobalErrors', function() {
it('rethrows the original error when there is no handler', function() { it('rethrows the original error when there is no handler', function() {
const globals = browserGlobals(); const globals = browserGlobals();
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -118,35 +130,9 @@ describe('GlobalErrors', function() {
errors.uninstall(); errors.uninstall();
}); });
it("reports browser error events that don't have errors", function() {
const globals = browserGlobals();
const handler = jasmine.createSpy('errorHandler');
const errors = new privateUnderTest.GlobalErrors(
globals.global,
() => ({})
);
errors.install();
errors.pushListener(handler);
const event = {
message: 'Uncaught SyntaxError: Unexpected end of input',
error: undefined,
filename: 'borkenSpec.js',
lineno: 42
};
dispatchEvent(globals.listeners, 'error', event);
expect(handler).toHaveBeenCalledWith({
message: 'Uncaught SyntaxError: Unexpected end of input',
filename: 'borkenSpec.js',
lineno: 42,
stack: '@borkenSpec.js:42'
});
});
it('reports uncaught exceptions in node.js', function() { it('reports uncaught exceptions in node.js', function() {
const globals = nodeGlobals(); const globals = nodeGlobals();
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -166,7 +152,7 @@ describe('GlobalErrors', function() {
dispatchEvent(globals.listeners, 'uncaughtException', new Error('bar')); dispatchEvent(globals.listeners, 'uncaughtException', new Error('bar'));
expect(handler).toHaveBeenCalledWith(new Error('bar')); expect(handler).toHaveBeenCalledWith(new Error('bar'), undefined);
expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe( expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe(
'Uncaught exception: Error: bar' 'Uncaught exception: Error: bar'
); );
@@ -179,7 +165,7 @@ describe('GlobalErrors', function() {
describe('Reporting unhandled promise rejections in node.js', function() { describe('Reporting unhandled promise rejections in node.js', function() {
it('reports rejections with `Error` reasons', function() { it('reports rejections with `Error` reasons', function() {
const globals = nodeGlobals(); const globals = nodeGlobals();
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -199,7 +185,7 @@ describe('GlobalErrors', function() {
dispatchEvent(globals.listeners, 'unhandledRejection', new Error('bar')); dispatchEvent(globals.listeners, 'unhandledRejection', new Error('bar'));
expect(handler).toHaveBeenCalledWith(new Error('bar')); expect(handler).toHaveBeenCalledWith(new Error('bar'), undefined);
expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe( expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe(
'Unhandled promise rejection: Error: bar' 'Unhandled promise rejection: Error: bar'
); );
@@ -211,7 +197,7 @@ describe('GlobalErrors', function() {
it('reports rejections with non-`Error` reasons', function() { it('reports rejections with non-`Error` reasons', function() {
const globals = nodeGlobals(); const globals = nodeGlobals();
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -227,13 +213,14 @@ describe('GlobalErrors', function() {
'Unhandled promise rejection: 17\n' + 'Unhandled promise rejection: 17\n' +
'(Tip: to get a useful stack trace, use ' + '(Tip: to get a useful stack trace, use ' +
'Promise.reject(new Error(...)) instead of Promise.reject(...).)' 'Promise.reject(new Error(...)) instead of Promise.reject(...).)'
) ),
undefined
); );
}); });
it('reports rejections with no reason provided', function() { it('reports rejections with no reason provided', function() {
const globals = nodeGlobals(); const globals = nodeGlobals();
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -249,7 +236,8 @@ describe('GlobalErrors', function() {
'Unhandled promise rejection with no error or message\n' + 'Unhandled promise rejection with no error or message\n' +
'(Tip: to get a useful stack trace, use ' + '(Tip: to get a useful stack trace, use ' +
'Promise.reject(new Error(...)) instead of Promise.reject().)' 'Promise.reject(new Error(...)) instead of Promise.reject().)'
) ),
undefined
); );
}); });
@@ -258,7 +246,7 @@ describe('GlobalErrors', function() {
beforeEach(function() { beforeEach(function() {
globals = nodeGlobals(); globals = nodeGlobals();
errors = new privateUnderTest.GlobalErrors(globals.global, () => ({ errors = new jasmineUnderTest.GlobalErrors(globals.global, () => ({
detectLateRejectionHandling: true detectLateRejectionHandling: true
})); }));
}); });
@@ -293,7 +281,7 @@ describe('GlobalErrors', function() {
undefined undefined
); );
expect(handler).toHaveBeenCalledWith(new Error('nope')); expect(handler).toHaveBeenCalledWith(new Error('nope'), undefined);
expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe( expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe(
'Unhandled promise rejection: Error: nope' 'Unhandled promise rejection: Error: nope'
); );
@@ -336,7 +324,7 @@ describe('GlobalErrors', function() {
); );
errors.reportUnhandledRejections(); errors.reportUnhandledRejections();
expect(handler).toHaveBeenCalledWith(new Error('nope')); expect(handler).toHaveBeenCalledWith(new Error('nope'), undefined);
expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe( expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe(
'Unhandled promise rejection: Error: nope' 'Unhandled promise rejection: Error: nope'
); );
@@ -391,7 +379,7 @@ describe('GlobalErrors', function() {
describe('Reporting unhandled promise rejections in the browser', function() { describe('Reporting unhandled promise rejections in the browser', function() {
it('subscribes and unsubscribes from the unhandledrejection event', function() { it('subscribes and unsubscribes from the unhandledrejection event', function() {
const globals = browserGlobals(); const globals = browserGlobals();
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -408,7 +396,7 @@ describe('GlobalErrors', function() {
it('reports rejections whose reason is a string', function() { it('reports rejections whose reason is a string', function() {
const globals = browserGlobals(); const globals = browserGlobals();
const handler = jasmine.createSpy('errorHandler'); const handler = jasmine.createSpy('errorHandler');
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -419,13 +407,16 @@ describe('GlobalErrors', function() {
const event = { reason: 'nope' }; const event = { reason: 'nope' };
dispatchEvent(globals.listeners, 'unhandledrejection', event); dispatchEvent(globals.listeners, 'unhandledrejection', event);
expect(handler).toHaveBeenCalledWith('Unhandled promise rejection: nope'); expect(handler).toHaveBeenCalledWith(
'Unhandled promise rejection: nope',
event
);
}); });
it('reports rejections whose reason is an Error', function() { it('reports rejections whose reason is an Error', function() {
const globals = browserGlobals(); const globals = browserGlobals();
const handler = jasmine.createSpy('errorHandler'); const handler = jasmine.createSpy('errorHandler');
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -437,15 +428,13 @@ describe('GlobalErrors', function() {
const event = { reason }; const event = { reason };
dispatchEvent(globals.listeners, 'unhandledrejection', event); dispatchEvent(globals.listeners, 'unhandledrejection', event);
expect(handler).toHaveBeenCalledTimes(1); expect(handler).toHaveBeenCalledWith(
const received = handler.calls.argsFor(0)[0];
expect(received).toBeInstanceOf(Error);
expect(received).toEqual(
jasmine.objectContaining({ jasmine.objectContaining({
jasmineMessage: 'Unhandled promise rejection: Error: bar', jasmineMessage: 'Unhandled promise rejection: Error: bar',
message: reason.message, message: reason.message,
stack: reason.stack stack: reason.stack
}) }),
event
); );
}); });
@@ -454,7 +443,7 @@ describe('GlobalErrors', function() {
beforeEach(function() { beforeEach(function() {
globals = browserGlobals(); globals = browserGlobals();
errors = new privateUnderTest.GlobalErrors(globals.global, () => ({ errors = new jasmineUnderTest.GlobalErrors(globals.global, () => ({
detectLateRejectionHandling: true detectLateRejectionHandling: true
})); }));
}); });
@@ -480,7 +469,8 @@ describe('GlobalErrors', function() {
dispatchEvent(globals.listeners, 'unhandledrejection', event); dispatchEvent(globals.listeners, 'unhandledrejection', event);
expect(handler).toHaveBeenCalledWith( expect(handler).toHaveBeenCalledWith(
'Unhandled promise rejection: nope' 'Unhandled promise rejection: nope',
event
); );
}); });
}); });
@@ -517,7 +507,8 @@ describe('GlobalErrors', function() {
errors.reportUnhandledRejections(); errors.reportUnhandledRejections();
expect(handler).toHaveBeenCalledWith( expect(handler).toHaveBeenCalledWith(
'Unhandled promise rejection: nope' 'Unhandled promise rejection: nope',
{ reason: 'nope', promise }
); );
}); });
@@ -565,7 +556,7 @@ describe('GlobalErrors', function() {
describe('Reporting uncaught exceptions in node.js', function() { describe('Reporting uncaught exceptions in node.js', function() {
it('prepends a descriptive message when the error is not an `Error`', function() { it('prepends a descriptive message when the error is not an `Error`', function() {
const globals = nodeGlobals(); const globals = nodeGlobals();
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -576,12 +567,15 @@ describe('GlobalErrors', function() {
dispatchEvent(globals.listeners, 'uncaughtException', 17); dispatchEvent(globals.listeners, 'uncaughtException', 17);
expect(handler).toHaveBeenCalledWith(new Error('Uncaught exception: 17')); expect(handler).toHaveBeenCalledWith(
new Error('Uncaught exception: 17'),
undefined
);
}); });
it('substitutes a descriptive message when the error is falsy', function() { it('substitutes a descriptive message when the error is falsy', function() {
const globals = nodeGlobals(); const globals = nodeGlobals();
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -593,7 +587,8 @@ describe('GlobalErrors', function() {
dispatchEvent(globals.listeners, 'uncaughtException', undefined); dispatchEvent(globals.listeners, 'uncaughtException', undefined);
expect(handler).toHaveBeenCalledWith( expect(handler).toHaveBeenCalledWith(
new Error('Uncaught exception with no error or message') new Error('Uncaught exception with no error or message'),
undefined
); );
}); });
}); });
@@ -604,7 +599,7 @@ describe('GlobalErrors', function() {
const handler0 = jasmine.createSpy('handler0'); const handler0 = jasmine.createSpy('handler0');
const handler1 = jasmine.createSpy('handler1'); const handler1 = jasmine.createSpy('handler1');
const overrideHandler = jasmine.createSpy('overrideHandler'); const overrideHandler = jasmine.createSpy('overrideHandler');
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -624,7 +619,7 @@ describe('GlobalErrors', function() {
const event = { error: 'baz' }; const event = { error: 'baz' };
dispatchEvent(globals.listeners, 'error', event); dispatchEvent(globals.listeners, 'error', event);
expect(overrideHandler).not.toHaveBeenCalledWith('baz'); expect(overrideHandler).not.toHaveBeenCalledWith('baz');
expect(handler1).toHaveBeenCalledWith('baz'); expect(handler1).toHaveBeenCalledWith('baz', event);
}); });
it('overrides the existing handlers in Node until removed', function() { it('overrides the existing handlers in Node until removed', function() {
@@ -632,7 +627,7 @@ describe('GlobalErrors', function() {
const handler0 = jasmine.createSpy('handler0'); const handler0 = jasmine.createSpy('handler0');
const handler1 = jasmine.createSpy('handler1'); const handler1 = jasmine.createSpy('handler1');
const overrideHandler = jasmine.createSpy('overrideHandler'); const overrideHandler = jasmine.createSpy('overrideHandler');
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -653,14 +648,14 @@ describe('GlobalErrors', function() {
dispatchEvent(globals.listeners, 'uncaughtException', new Error('bar')); dispatchEvent(globals.listeners, 'uncaughtException', new Error('bar'));
expect(overrideHandler).not.toHaveBeenCalled(); expect(overrideHandler).not.toHaveBeenCalled();
expect(handler1).toHaveBeenCalledWith(new Error('bar')); expect(handler1).toHaveBeenCalledWith(new Error('bar'), undefined);
}); });
it('handles unhandled promise rejections in browsers', function() { it('handles unhandled promise rejections in browsers', function() {
const globals = browserGlobals(); const globals = browserGlobals();
const handler = jasmine.createSpy('handler'); const handler = jasmine.createSpy('handler');
const overrideHandler = jasmine.createSpy('overrideHandler'); const overrideHandler = jasmine.createSpy('overrideHandler');
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -688,7 +683,7 @@ describe('GlobalErrors', function() {
const handler0 = jasmine.createSpy('handler0'); const handler0 = jasmine.createSpy('handler0');
const handler1 = jasmine.createSpy('handler1'); const handler1 = jasmine.createSpy('handler1');
const overrideHandler = jasmine.createSpy('overrideHandler'); const overrideHandler = jasmine.createSpy('overrideHandler');
const errors = new privateUnderTest.GlobalErrors( const errors = new jasmineUnderTest.GlobalErrors(
globals.global, globals.global,
() => ({}) () => ({})
); );
@@ -706,7 +701,7 @@ describe('GlobalErrors', function() {
}); });
it('throws if there is already an override handler', function() { it('throws if there is already an override handler', function() {
const errors = new privateUnderTest.GlobalErrors(browserGlobals().global); const errors = new jasmineUnderTest.GlobalErrors(browserGlobals().global);
errors.setOverrideListener(() => {}, () => {}); errors.setOverrideListener(() => {}, () => {});
expect(function() { expect(function() {
@@ -718,7 +713,7 @@ describe('GlobalErrors', function() {
describe('#removeOverrideListener', function() { describe('#removeOverrideListener', function() {
it("calls the handler's onRemove callback", function() { it("calls the handler's onRemove callback", function() {
const onRemove = jasmine.createSpy('onRemove'); const onRemove = jasmine.createSpy('onRemove');
const errors = new privateUnderTest.GlobalErrors(browserGlobals().global); const errors = new jasmineUnderTest.GlobalErrors(browserGlobals().global);
errors.setOverrideListener(() => {}, onRemove); errors.setOverrideListener(() => {}, onRemove);
errors.removeOverrideListener(); errors.removeOverrideListener();
@@ -727,7 +722,7 @@ describe('GlobalErrors', function() {
}); });
it('does not throw if there is no handler', function() { it('does not throw if there is no handler', function() {
const errors = new privateUnderTest.GlobalErrors(browserGlobals().global); const errors = new jasmineUnderTest.GlobalErrors(browserGlobals().global);
expect(() => errors.removeOverrideListener()).not.toThrow(); expect(() => errors.removeOverrideListener()).not.toThrow();
}); });
+12 -12
View File
@@ -1,6 +1,6 @@
describe('JsApiReporter', function() { describe('JsApiReporter', function() {
it('knows when a full environment is started', function() { it('knows when a full environment is started', function() {
const reporter = new privateUnderTest.JsApiReporter({}); const reporter = new jasmineUnderTest.JsApiReporter({});
expect(reporter.started).toBe(false); expect(reporter.started).toBe(false);
expect(reporter.finished).toBe(false); expect(reporter.finished).toBe(false);
@@ -12,7 +12,7 @@ describe('JsApiReporter', function() {
}); });
it('knows when a full environment is done', function() { it('knows when a full environment is done', function() {
const reporter = new privateUnderTest.JsApiReporter({}); const reporter = new jasmineUnderTest.JsApiReporter({});
expect(reporter.started).toBe(false); expect(reporter.started).toBe(false);
expect(reporter.finished).toBe(false); expect(reporter.finished).toBe(false);
@@ -24,13 +24,13 @@ describe('JsApiReporter', function() {
}); });
it("defaults to 'loaded' status", function() { it("defaults to 'loaded' status", function() {
const reporter = new privateUnderTest.JsApiReporter({}); const reporter = new jasmineUnderTest.JsApiReporter({});
expect(reporter.status()).toEqual('loaded'); expect(reporter.status()).toEqual('loaded');
}); });
it("reports 'started' when Jasmine has started", function() { it("reports 'started' when Jasmine has started", function() {
const reporter = new privateUnderTest.JsApiReporter({}); const reporter = new jasmineUnderTest.JsApiReporter({});
reporter.jasmineStarted(); reporter.jasmineStarted();
@@ -38,7 +38,7 @@ describe('JsApiReporter', function() {
}); });
it("reports 'done' when Jasmine is done", function() { it("reports 'done' when Jasmine is done", function() {
const reporter = new privateUnderTest.JsApiReporter({}); const reporter = new jasmineUnderTest.JsApiReporter({});
reporter.jasmineDone({}); reporter.jasmineDone({});
@@ -46,7 +46,7 @@ describe('JsApiReporter', function() {
}); });
it('tracks a suite', function() { it('tracks a suite', function() {
const reporter = new privateUnderTest.JsApiReporter({}); const reporter = new jasmineUnderTest.JsApiReporter({});
reporter.suiteStarted({ reporter.suiteStarted({
id: 123, id: 123,
@@ -71,7 +71,7 @@ describe('JsApiReporter', function() {
describe('#specResults', function() { describe('#specResults', function() {
let reporter, specResult1, specResult2; let reporter, specResult1, specResult2;
beforeEach(function() { beforeEach(function() {
reporter = new privateUnderTest.JsApiReporter({}); reporter = new jasmineUnderTest.JsApiReporter({});
specResult1 = { specResult1 = {
id: 1, id: 1,
description: 'A spec' description: 'A spec'
@@ -101,7 +101,7 @@ describe('JsApiReporter', function() {
describe('#suiteResults', function() { describe('#suiteResults', function() {
let reporter, suiteStarted1, suiteResult1, suiteResult2; let reporter, suiteStarted1, suiteResult1, suiteResult2;
beforeEach(function() { beforeEach(function() {
reporter = new privateUnderTest.JsApiReporter({}); reporter = new jasmineUnderTest.JsApiReporter({});
suiteStarted1 = { suiteStarted1 = {
id: 1 id: 1
}; };
@@ -138,7 +138,7 @@ describe('JsApiReporter', function() {
describe('#executionTime', function() { describe('#executionTime', function() {
it('should start the timer when jasmine starts', function() { it('should start the timer when jasmine starts', function() {
const timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']), const timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']),
reporter = new privateUnderTest.JsApiReporter({ reporter = new jasmineUnderTest.JsApiReporter({
timer: timerSpy timer: timerSpy
}); });
@@ -148,7 +148,7 @@ describe('JsApiReporter', function() {
it('should return the time it took the specs to run, in ms', function() { it('should return the time it took the specs to run, in ms', function() {
const timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']), const timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']),
reporter = new privateUnderTest.JsApiReporter({ reporter = new jasmineUnderTest.JsApiReporter({
timer: timerSpy timer: timerSpy
}); });
@@ -160,7 +160,7 @@ describe('JsApiReporter', function() {
describe("when the specs haven't finished being run", function() { describe("when the specs haven't finished being run", function() {
it('should return undefined', function() { it('should return undefined', function() {
const timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']), const timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']),
reporter = new privateUnderTest.JsApiReporter({ reporter = new jasmineUnderTest.JsApiReporter({
timer: timerSpy timer: timerSpy
}); });
@@ -171,7 +171,7 @@ describe('JsApiReporter', function() {
describe('#runDetails', function() { describe('#runDetails', function() {
it('should have details about the run', function() { it('should have details about the run', function() {
const reporter = new privateUnderTest.JsApiReporter({}); const reporter = new jasmineUnderTest.JsApiReporter({});
reporter.jasmineDone({ some: { run: 'details' } }); reporter.jasmineDone({ some: { run: 'details' } });
expect(reporter.runDetails).toEqual({ some: { run: 'details' } }); expect(reporter.runDetails).toEqual({ some: { run: 'details' } });
}); });
+13 -13
View File
@@ -1,7 +1,7 @@
describe('FakeDate', function() { describe('FakeDate', function() {
it('does not fail if no global date is found', function() { it('does not fail if no global date is found', function() {
const fakeGlobal = {}, const fakeGlobal = {},
mockDate = new privateUnderTest.MockDate(fakeGlobal); mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
expect(function() { expect(function() {
mockDate.install(); mockDate.install();
@@ -19,7 +19,7 @@ describe('FakeDate', function() {
}; };
}), }),
fakeGlobal = { Date: globalDate }, fakeGlobal = { Date: globalDate },
mockDate = new privateUnderTest.MockDate(fakeGlobal); mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
expect(fakeGlobal.Date).toEqual(globalDate); expect(fakeGlobal.Date).toEqual(globalDate);
mockDate.install(); mockDate.install();
@@ -36,7 +36,7 @@ describe('FakeDate', function() {
}; };
}), }),
fakeGlobal = { Date: globalDate }, fakeGlobal = { Date: globalDate },
mockDate = new privateUnderTest.MockDate(fakeGlobal); mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
mockDate.install(); mockDate.install();
mockDate.uninstall(); mockDate.uninstall();
@@ -55,7 +55,7 @@ describe('FakeDate', function() {
}; };
}), }),
fakeGlobal = { Date: globalDate }, fakeGlobal = { Date: globalDate },
mockDate = new privateUnderTest.MockDate(fakeGlobal); mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
mockDate.install(); mockDate.install();
@@ -66,7 +66,7 @@ describe('FakeDate', function() {
it('can accept a date as time base when installing', function() { it('can accept a date as time base when installing', function() {
const fakeGlobal = { Date: Date }, const fakeGlobal = { Date: Date },
mockDate = new privateUnderTest.MockDate(fakeGlobal), mockDate = new jasmineUnderTest.MockDate(fakeGlobal),
baseDate = new Date(); baseDate = new Date();
spyOn(baseDate, 'getTime').and.returnValue(123); spyOn(baseDate, 'getTime').and.returnValue(123);
@@ -77,7 +77,7 @@ describe('FakeDate', function() {
it('makes real dates', function() { it('makes real dates', function() {
const fakeGlobal = { Date: Date }, const fakeGlobal = { Date: Date },
mockDate = new privateUnderTest.MockDate(fakeGlobal); mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
mockDate.install(); mockDate.install();
expect(new fakeGlobal.Date()).toEqual(jasmine.any(Date)); expect(new fakeGlobal.Date()).toEqual(jasmine.any(Date));
@@ -97,7 +97,7 @@ describe('FakeDate', function() {
fakeGlobal = { Date: globalDate }; fakeGlobal = { Date: globalDate };
globalDate.now = function() {}; globalDate.now = function() {};
const mockDate = new privateUnderTest.MockDate(fakeGlobal); const mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
mockDate.install(); mockDate.install();
@@ -117,7 +117,7 @@ describe('FakeDate', function() {
fakeGlobal = { Date: globalDate }; fakeGlobal = { Date: globalDate };
globalDate.now = function() {}; globalDate.now = function() {};
const mockDate = new privateUnderTest.MockDate(fakeGlobal); const mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
mockDate.install(); mockDate.install();
@@ -143,7 +143,7 @@ describe('FakeDate', function() {
fakeGlobal = { Date: globalDate }; fakeGlobal = { Date: globalDate };
globalDate.now = function() {}; globalDate.now = function() {};
const mockDate = new privateUnderTest.MockDate(fakeGlobal); const mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
mockDate.install(); mockDate.install();
@@ -156,7 +156,7 @@ describe('FakeDate', function() {
it('allows creation of a Date in a different time than the mocked time', function() { it('allows creation of a Date in a different time than the mocked time', function() {
const fakeGlobal = { Date: Date }, const fakeGlobal = { Date: Date },
mockDate = new privateUnderTest.MockDate(fakeGlobal); mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
mockDate.install(); mockDate.install();
@@ -168,7 +168,7 @@ describe('FakeDate', function() {
it("allows creation of a Date that isn't fully specified", function() { it("allows creation of a Date that isn't fully specified", function() {
const fakeGlobal = { Date: Date }, const fakeGlobal = { Date: Date },
mockDate = new privateUnderTest.MockDate(fakeGlobal); mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
mockDate.install(); mockDate.install();
@@ -178,7 +178,7 @@ describe('FakeDate', function() {
it('allows creation of a Date with millis', function() { it('allows creation of a Date with millis', function() {
const fakeGlobal = { Date: Date }, const fakeGlobal = { Date: Date },
mockDate = new privateUnderTest.MockDate(fakeGlobal), mockDate = new jasmineUnderTest.MockDate(fakeGlobal),
now = new Date(2014, 3, 15).getTime(); now = new Date(2014, 3, 15).getTime();
mockDate.install(); mockDate.install();
@@ -189,7 +189,7 @@ describe('FakeDate', function() {
it('copies all Date properties to the mocked date', function() { it('copies all Date properties to the mocked date', function() {
const fakeGlobal = { Date: Date }, const fakeGlobal = { Date: Date },
mockDate = new privateUnderTest.MockDate(fakeGlobal); mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
mockDate.install(); mockDate.install();
+53 -53
View File
@@ -1,12 +1,12 @@
describe('PrettyPrinter', function() { describe('PrettyPrinter', function() {
it('should wrap strings in single quotes', function() { it('should wrap strings in single quotes', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp('some string')).toEqual("'some string'"); expect(pp('some string')).toEqual("'some string'");
expect(pp("som' string")).toEqual("'som' string'"); expect(pp("som' string")).toEqual("'som' string'");
}); });
it('stringifies empty string primitives and objects recognizably', function() { it('stringifies empty string primitives and objects recognizably', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(new String(''))).toEqual(pp('')); expect(pp(new String(''))).toEqual(pp(''));
expect(pp(new String(''))).toEqual("''"); expect(pp(new String(''))).toEqual("''");
expect(pp([new String('')])).toEqual(pp([''])); expect(pp([new String('')])).toEqual(pp(['']));
@@ -14,7 +14,7 @@ describe('PrettyPrinter', function() {
}); });
it('should stringify primitives properly', function() { it('should stringify primitives properly', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(true)).toEqual('true'); expect(pp(true)).toEqual('true');
expect(pp(false)).toEqual('false'); expect(pp(false)).toEqual('false');
expect(pp(null)).toEqual('null'); expect(pp(null)).toEqual('null');
@@ -29,7 +29,7 @@ describe('PrettyPrinter', function() {
const set = new Set(); const set = new Set();
set.add(1); set.add(1);
set.add(2); set.add(2);
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(set)).toEqual('Set( 1, 2 )'); expect(pp(set)).toEqual('Set( 1, 2 )');
}); });
@@ -42,7 +42,7 @@ describe('PrettyPrinter', function() {
set.add('a'); set.add('a');
set.add('b'); set.add('b');
set.add('c'); set.add('c');
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(set)).toEqual("Set( 'a', 'b', ... )"); expect(pp(set)).toEqual("Set( 'a', 'b', ... )");
} finally { } finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize; jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize;
@@ -54,7 +54,7 @@ describe('PrettyPrinter', function() {
it('should stringify maps properly', function() { it('should stringify maps properly', function() {
const map = new Map(); const map = new Map();
map.set(1, 2); map.set(1, 2);
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(map)).toEqual('Map( [ 1, 2 ] )'); expect(pp(map)).toEqual('Map( [ 1, 2 ] )');
}); });
@@ -67,7 +67,7 @@ describe('PrettyPrinter', function() {
map.set('a', 1); map.set('a', 1);
map.set('b', 2); map.set('b', 2);
map.set('c', 3); map.set('c', 3);
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(map)).toEqual("Map( [ 'a', 1 ], [ 'b', 2 ], ... )"); expect(pp(map)).toEqual("Map( [ 'a', 1 ], [ 'b', 2 ], ... )");
} finally { } finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize; jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize;
@@ -77,7 +77,7 @@ describe('PrettyPrinter', function() {
describe('stringify arrays', function() { describe('stringify arrays', function() {
it('should stringify arrays properly', function() { it('should stringify arrays properly', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp([1, 2])).toEqual('[ 1, 2 ]'); expect(pp([1, 2])).toEqual('[ 1, 2 ]');
expect(pp([1, 'foo', {}, jasmine.undefined, null])).toEqual( expect(pp([1, 'foo', {}, jasmine.undefined, null])).toEqual(
"[ 1, 'foo', Object({ }), undefined, null ]" "[ 1, 'foo', Object({ }), undefined, null ]"
@@ -85,14 +85,14 @@ describe('PrettyPrinter', function() {
}); });
it('includes symbols', function() { it('includes symbols', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp([1, Symbol('foo'), 2])).toEqual('[ 1, Symbol(foo), 2 ]'); expect(pp([1, Symbol('foo'), 2])).toEqual('[ 1, Symbol(foo), 2 ]');
}); });
it('should truncate arrays that are longer than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() { it('should truncate arrays that are longer than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() {
const originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; const originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH;
const array = [1, 2, 3]; const array = [1, 2, 3];
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
try { try {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2; jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2;
@@ -103,7 +103,7 @@ describe('PrettyPrinter', function() {
}); });
it('should stringify arrays with properties properly', function() { it('should stringify arrays with properties properly', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const arr = [1, 2]; const arr = [1, 2];
arr.foo = 'bar'; arr.foo = 'bar';
arr.baz = {}; arr.baz = {};
@@ -111,7 +111,7 @@ describe('PrettyPrinter', function() {
}); });
it('should stringify empty arrays with properties properly', function() { it('should stringify empty arrays with properties properly', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const empty = []; const empty = [];
empty.foo = 'bar'; empty.foo = 'bar';
empty.baz = {}; empty.baz = {};
@@ -119,7 +119,7 @@ describe('PrettyPrinter', function() {
}); });
it('should stringify long arrays with properties properly', function() { it('should stringify long arrays with properties properly', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; const originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH;
const long = [1, 2, 3]; const long = [1, 2, 3];
long.foo = 'bar'; long.foo = 'bar';
@@ -136,7 +136,7 @@ describe('PrettyPrinter', function() {
}); });
it('should indicate circular array references', function() { it('should indicate circular array references', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const array1 = [1, 2]; const array1 = [1, 2];
const array2 = [array1]; const array2 = [array1];
array1.push(array2); array1.push(array2);
@@ -144,14 +144,14 @@ describe('PrettyPrinter', function() {
}); });
it('should not indicate circular references incorrectly', function() { it('should not indicate circular references incorrectly', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const array = [[1]]; const array = [[1]];
expect(pp(array)).toEqual('[ [ 1 ] ]'); expect(pp(array)).toEqual('[ [ 1 ] ]');
}); });
}); });
it('should stringify objects properly', function() { it('should stringify objects properly', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp({ foo: 'bar' })).toEqual("Object({ foo: 'bar' })"); expect(pp({ foo: 'bar' })).toEqual("Object({ foo: 'bar' })");
expect( expect(
pp({ pp({
@@ -169,14 +169,14 @@ describe('PrettyPrinter', function() {
}); });
it('includes symbol keys in objects', function() { it('includes symbol keys in objects', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const obj = {}; const obj = {};
obj[Symbol('foo')] = 'bar'; obj[Symbol('foo')] = 'bar';
expect(pp(obj)).toEqual("Object({ Symbol(foo): 'bar' })"); expect(pp(obj)).toEqual("Object({ Symbol(foo): 'bar' })");
}); });
it('stringifies string and symbol keys differently', function() { it('stringifies string and symbol keys differently', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const symObj = {}; const symObj = {};
const strObj = {}; const strObj = {};
const k = 'foo'; const k = 'foo';
@@ -188,12 +188,12 @@ describe('PrettyPrinter', function() {
}); });
it('should stringify objects that almost look like DOM nodes', function() { it('should stringify objects that almost look like DOM nodes', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp({ nodeType: 1 })).toEqual('Object({ nodeType: 1 })'); expect(pp({ nodeType: 1 })).toEqual('Object({ nodeType: 1 })');
}); });
it('should truncate objects with too many keys', function() { it('should truncate objects with too many keys', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; const originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH;
const long = { a: 1, b: 2, c: 3 }; const long = { a: 1, b: 2, c: 3 };
@@ -217,7 +217,7 @@ describe('PrettyPrinter', function() {
} }
it('should truncate outputs that are too long', function() { it('should truncate outputs that are too long', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const big = [{ a: 1, b: 'a long string' }, {}]; const big = [{ a: 1, b: 'a long string' }, {}];
withMaxChars(34, function() { withMaxChars(34, function() {
@@ -246,7 +246,7 @@ describe('PrettyPrinter', function() {
.createSpy('d jasmineToString') .createSpy('d jasmineToString')
.and.returnValue('') .and.returnValue('')
}, },
pp = privateUnderTest.makePrettyPrinter(); pp = jasmineUnderTest.makePrettyPrinter();
withMaxChars(30, function() { withMaxChars(30, function() {
pp([{ a: a, b: b, c: c }, d]); pp([{ a: a, b: b, c: c }, d]);
@@ -256,13 +256,13 @@ describe('PrettyPrinter', function() {
}); });
it("should print 'null' as the constructor of an object with its own constructor property", function() { it("should print 'null' as the constructor of an object with its own constructor property", function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp({ constructor: function() {} })).toContain('null({'); expect(pp({ constructor: function() {} })).toContain('null({');
expect(pp({ constructor: 'foo' })).toContain('null({'); expect(pp({ constructor: 'foo' })).toContain('null({');
}); });
it('should not include inherited properties when stringifying an object', function() { it('should not include inherited properties when stringifying an object', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const SomeClass = function SomeClass() {}; const SomeClass = function SomeClass() {};
SomeClass.prototype.foo = 'inherited foo'; SomeClass.prototype.foo = 'inherited foo';
const instance = new SomeClass(); const instance = new SomeClass();
@@ -271,7 +271,7 @@ describe('PrettyPrinter', function() {
}); });
it('should not recurse objects and arrays more deeply than jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH', function() { it('should not recurse objects and arrays more deeply than jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const originalMaxDepth = jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH; const originalMaxDepth = jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH;
const nestedObject = { level1: { level2: { level3: { level4: 'leaf' } } } }; const nestedObject = { level1: { level2: { level3: { level4: 'leaf' } } } };
const nestedArray = [1, [2, [3, [4, 'leaf']]]]; const nestedArray = [1, [2, [3, [4, 'leaf']]]];
@@ -300,7 +300,7 @@ describe('PrettyPrinter', function() {
}); });
it('should stringify immutable circular objects', function() { it('should stringify immutable circular objects', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
let frozenObject = { foo: { bar: 'baz' } }; let frozenObject = { foo: { bar: 'baz' } };
frozenObject.circular = frozenObject; frozenObject.circular = frozenObject;
frozenObject = Object.freeze(frozenObject); frozenObject = Object.freeze(frozenObject);
@@ -310,12 +310,12 @@ describe('PrettyPrinter', function() {
}); });
it('should stringify RegExp objects properly', function() { it('should stringify RegExp objects properly', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(/x|y|z/)).toEqual('/x|y|z/'); expect(pp(/x|y|z/)).toEqual('/x|y|z/');
}); });
it('should indicate circular object references', function() { it('should indicate circular object references', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const sampleValue = { foo: 'hello' }; const sampleValue = { foo: 'hello' };
sampleValue.nested = sampleValue; sampleValue.nested = sampleValue;
expect(pp(sampleValue)).toEqual( expect(pp(sampleValue)).toEqual(
@@ -324,7 +324,7 @@ describe('PrettyPrinter', function() {
}); });
it('should use the return value of getters', function() { it('should use the return value of getters', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const sampleValue = { const sampleValue = {
id: 1, id: 1,
get calculatedValue() { get calculatedValue() {
@@ -337,19 +337,19 @@ describe('PrettyPrinter', function() {
}); });
it('should not do HTML escaping of strings', function() { it('should not do HTML escaping of strings', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp('some <b>html string</b> &', false)).toEqual( expect(pp('some <b>html string</b> &', false)).toEqual(
"'some <b>html string</b> &'" "'some <b>html string</b> &'"
); );
}); });
it('should abbreviate the global (usually window) object', function() { it('should abbreviate the global (usually window) object', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(jasmine.getGlobal())).toEqual('<global>'); expect(pp(jasmine.getGlobal())).toEqual('<global>');
}); });
it('should stringify Date objects properly', function() { it('should stringify Date objects properly', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const now = new Date(); const now = new Date();
expect(pp(now)).toEqual('Date(' + now.toString() + ')'); expect(pp(now)).toEqual('Date(' + now.toString() + ')');
}); });
@@ -358,8 +358,8 @@ describe('PrettyPrinter', function() {
let env, pp; let env, pp;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
pp = privateUnderTest.makePrettyPrinter(); pp = jasmineUnderTest.makePrettyPrinter();
}); });
afterEach(function() { afterEach(function() {
@@ -371,12 +371,12 @@ describe('PrettyPrinter', function() {
someFunction: function() {} someFunction: function() {}
}; };
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return []; return [];
}, },
createSpy: function(name, originalFn) { createSpy: function(name, originalFn) {
return privateUnderTest.Spy(name, originalFn); return jasmineUnderTest.Spy(name, originalFn);
} }
}); });
@@ -390,15 +390,15 @@ describe('PrettyPrinter', function() {
const TestObject = { const TestObject = {
someFunction: function() {} someFunction: function() {}
}, },
env = new privateUnderTest.Env(), env = new jasmineUnderTest.Env(),
pp = privateUnderTest.makePrettyPrinter(); pp = jasmineUnderTest.makePrettyPrinter();
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return []; return [];
}, },
createSpy: function(name, originalFn) { createSpy: function(name, originalFn) {
return privateUnderTest.Spy(name, originalFn); return jasmineUnderTest.Spy(name, originalFn);
} }
}); });
@@ -410,7 +410,7 @@ describe('PrettyPrinter', function() {
}); });
it('should stringify objects that implement jasmineToString', function() { it('should stringify objects that implement jasmineToString', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const obj = { const obj = {
jasmineToString: function() { jasmineToString: function() {
return 'strung'; return 'strung';
@@ -421,7 +421,7 @@ describe('PrettyPrinter', function() {
}); });
it('should pass itself to jasmineToString', function() { it('should pass itself to jasmineToString', function() {
const pp = privateUnderTest.makePrettyPrinter([]); const pp = jasmineUnderTest.makePrettyPrinter([]);
const obj = { const obj = {
jasmineToString: jasmine.createSpy('jasmineToString').and.returnValue('') jasmineToString: jasmine.createSpy('jasmineToString').and.returnValue('')
}; };
@@ -431,7 +431,7 @@ describe('PrettyPrinter', function() {
}); });
it('should stringify objects that implement custom toString', function() { it('should stringify objects that implement custom toString', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const obj = { const obj = {
toString: function() { toString: function() {
return 'my toString'; return 'my toString';
@@ -455,7 +455,7 @@ describe('PrettyPrinter', function() {
}); });
it("should stringify objects have have a toString that isn't a function", function() { it("should stringify objects have have a toString that isn't a function", function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const obj = { const obj = {
toString: 'foo' toString: 'foo'
}; };
@@ -464,7 +464,7 @@ describe('PrettyPrinter', function() {
}); });
it('should stringify objects from anonymous constructors with custom toString', function() { it('should stringify objects from anonymous constructors with custom toString', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const MyAnonymousConstructor = (function() { const MyAnonymousConstructor = (function() {
return function() {}; return function() {};
})(); })();
@@ -478,18 +478,18 @@ describe('PrettyPrinter', function() {
}); });
it('stringifies functions with names', function() { it('stringifies functions with names', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(foo)).toEqual("Function 'foo'"); expect(pp(foo)).toEqual("Function 'foo'");
function foo() {} function foo() {}
}); });
it('stringifies functions without names', function() { it('stringifies functions without names', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(function() {})).toEqual('Function'); expect(pp(function() {})).toEqual('Function');
}); });
it('should handle objects with null prototype', function() { it('should handle objects with null prototype', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const obj = Object.create(null); const obj = Object.create(null);
obj.foo = 'bar'; obj.foo = 'bar';
@@ -497,7 +497,7 @@ describe('PrettyPrinter', function() {
}); });
it('should gracefully handle objects with invalid toString implementations', function() { it('should gracefully handle objects with invalid toString implementations', function() {
const pp = privateUnderTest.makePrettyPrinter(); const pp = jasmineUnderTest.makePrettyPrinter();
const obj = { const obj = {
foo: { foo: {
toString: function() { toString: function() {
@@ -545,7 +545,7 @@ describe('PrettyPrinter', function() {
return '3rd: ' + obj.foo; return '3rd: ' + obj.foo;
} }
], ],
pp = privateUnderTest.makePrettyPrinter(customObjectFormatters), pp = jasmineUnderTest.makePrettyPrinter(customObjectFormatters),
obj = { foo: 'bar' }; obj = { foo: 'bar' };
expect(pp(obj)).toEqual('2nd: bar'); expect(pp(obj)).toEqual('2nd: bar');
@@ -557,7 +557,7 @@ describe('PrettyPrinter', function() {
return undefined; return undefined;
} }
], ],
pp = privateUnderTest.makePrettyPrinter(customObjectFormatters), pp = jasmineUnderTest.makePrettyPrinter(customObjectFormatters),
obj = { foo: 'bar' }; obj = { foo: 'bar' };
expect(pp(obj)).toEqual("Object({ foo: 'bar' })"); expect(pp(obj)).toEqual("Object({ foo: 'bar' })");
@@ -577,7 +577,7 @@ describe('PrettyPrinter', function() {
return '3rd: ' + obj.foo; return '3rd: ' + obj.foo;
} }
], ],
pp = privateUnderTest.makePrettyPrinter(customObjectFormatters), pp = jasmineUnderTest.makePrettyPrinter(customObjectFormatters),
obj = { foo: 'bar' }; obj = { foo: 'bar' };
expect(pp.customFormat_(obj)).toEqual('2nd: bar'); expect(pp.customFormat_(obj)).toEqual('2nd: bar');
@@ -589,7 +589,7 @@ describe('PrettyPrinter', function() {
return undefined; return undefined;
} }
], ],
pp = privateUnderTest.makePrettyPrinter(customObjectFormatters), pp = jasmineUnderTest.makePrettyPrinter(customObjectFormatters),
obj = { foo: 'bar' }; obj = { foo: 'bar' };
expect(pp.customFormat_(obj)).toBeUndefined(); expect(pp.customFormat_(obj)).toBeUndefined();
+115 -56
View File
@@ -1,7 +1,7 @@
describe('QueueRunner', function() { describe('QueueRunner', function() {
it('validates that queueableFns are truthy', function() { it('validates that queueableFns are truthy', function() {
expect(function() { expect(function() {
new privateUnderTest.QueueRunner({ new jasmineUnderTest.QueueRunner({
queueableFns: [undefined] queueableFns: [undefined]
}); });
}).toThrowError('Received a falsy queueableFn'); }).toThrowError('Received a falsy queueableFn');
@@ -9,7 +9,7 @@ describe('QueueRunner', function() {
it('validates that queueableFns have fn properties', function() { it('validates that queueableFns have fn properties', function() {
expect(function() { expect(function() {
new privateUnderTest.QueueRunner({ new jasmineUnderTest.QueueRunner({
queueableFns: [{ fn: undefined }] queueableFns: [{ fn: undefined }]
}); });
}).toThrowError('Received a queueableFn with no fn'); }).toThrowError('Received a queueableFn with no fn');
@@ -19,7 +19,7 @@ describe('QueueRunner', function() {
const calls = [], const calls = [],
queueableFn1 = { fn: jasmine.createSpy('fn1') }, queueableFn1 = { fn: jasmine.createSpy('fn1') },
queueableFn2 = { fn: jasmine.createSpy('fn2') }, queueableFn2 = { fn: jasmine.createSpy('fn2') },
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2] queueableFns: [queueableFn1, queueableFn2]
}); });
queueableFn1.fn.and.callFake(function() { queueableFn1.fn.and.callFake(function() {
@@ -44,14 +44,14 @@ describe('QueueRunner', function() {
done(); done();
} }
}, },
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2, queueableFn3] queueableFns: [queueableFn1, queueableFn2, queueableFn3]
}); });
queueRunner.execute(); queueRunner.execute();
const context = queueableFn1.fn.calls.first().object; const context = queueableFn1.fn.calls.first().object;
expect(context).toEqual(new privateUnderTest.UserContext()); expect(context).toEqual(new jasmineUnderTest.UserContext());
expect(queueableFn2.fn.calls.first().object).toBe(context); expect(queueableFn2.fn.calls.first().object).toBe(context);
expect(asyncContext).toBe(context); expect(asyncContext).toBe(context);
}); });
@@ -91,7 +91,7 @@ describe('QueueRunner', function() {
setTimeout(done, 100); setTimeout(done, 100);
} }
}, },
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2, queueableFn3], queueableFns: [queueableFn1, queueableFn2, queueableFn3],
onComplete: onComplete onComplete: onComplete
}); });
@@ -129,7 +129,7 @@ describe('QueueRunner', function() {
}, },
queueableFn2 = { fn: jasmine.createSpy('fn2') }, queueableFn2 = { fn: jasmine.createSpy('fn2') },
failFn = jasmine.createSpy('fail'), failFn = jasmine.createSpy('fail'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2], queueableFns: [queueableFn1, queueableFn2],
fail: failFn fail: failFn
}); });
@@ -157,7 +157,7 @@ describe('QueueRunner', function() {
}, },
queueableFn2 = { fn: jasmine.createSpy('fn2') }, queueableFn2 = { fn: jasmine.createSpy('fn2') },
failFn = jasmine.createSpy('fail'), failFn = jasmine.createSpy('fail'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2], queueableFns: [queueableFn1, queueableFn2],
fail: failFn fail: failFn
}); });
@@ -189,7 +189,7 @@ describe('QueueRunner', function() {
}, },
queueableFn2 = { fn: jasmine.createSpy('fn2') }, queueableFn2 = { fn: jasmine.createSpy('fn2') },
failFn = jasmine.createSpy('fail'), failFn = jasmine.createSpy('fail'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2], queueableFns: [queueableFn1, queueableFn2],
fail: failFn, fail: failFn,
onComplete: function() { onComplete: function() {
@@ -211,7 +211,7 @@ describe('QueueRunner', function() {
} }
}, },
failFn = jasmine.createSpy('fail'), failFn = jasmine.createSpy('fail'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1], queueableFns: [queueableFn1],
fail: failFn, fail: failFn,
onComplete: function() { onComplete: function() {
@@ -227,7 +227,7 @@ describe('QueueRunner', function() {
}); });
it('does not cause an explicit fail if execution is being stopped', function() { it('does not cause an explicit fail if execution is being stopped', function() {
const err = new privateUnderTest.StopExecutionError('foo'), const err = new jasmineUnderTest.StopExecutionError('foo'),
queueableFn1 = { queueableFn1 = {
fn: function(done) { fn: function(done) {
setTimeout(function() { setTimeout(function() {
@@ -237,7 +237,7 @@ describe('QueueRunner', function() {
}, },
queueableFn2 = { fn: jasmine.createSpy('fn2') }, queueableFn2 = { fn: jasmine.createSpy('fn2') },
failFn = jasmine.createSpy('fail'), failFn = jasmine.createSpy('fail'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2], queueableFns: [queueableFn1, queueableFn2],
fail: failFn fail: failFn
}); });
@@ -259,7 +259,7 @@ describe('QueueRunner', function() {
queueableFn = { fn: jasmine.createSpy('fn'), type: 'queueable' }, queueableFn = { fn: jasmine.createSpy('fn'), type: 'queueable' },
onComplete = jasmine.createSpy('onComplete'), onComplete = jasmine.createSpy('onComplete'),
onException = jasmine.createSpy('onException'), onException = jasmine.createSpy('onException'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [beforeFn, queueableFn], queueableFns: [beforeFn, queueableFn],
onComplete: onComplete, onComplete: onComplete,
onException: onException onException: onException
@@ -287,7 +287,7 @@ describe('QueueRunner', function() {
}; };
const onComplete = jasmine.createSpy('onComplete'); const onComplete = jasmine.createSpy('onComplete');
const onMultipleDone = jasmine.createSpy('onMultipleDone'); const onMultipleDone = jasmine.createSpy('onMultipleDone');
const queueRunner = new privateUnderTest.QueueRunner({ const queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn], queueableFns: [queueableFn],
onComplete: onComplete, onComplete: onComplete,
onMultipleDone: onMultipleDone onMultipleDone: onMultipleDone
@@ -306,7 +306,7 @@ describe('QueueRunner', function() {
queueableFn = { fn: jasmine.createSpy('fn') }, queueableFn = { fn: jasmine.createSpy('fn') },
onComplete = jasmine.createSpy('onComplete'), onComplete = jasmine.createSpy('onComplete'),
onException = jasmine.createSpy('onException'), onException = jasmine.createSpy('onException'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [beforeFn, queueableFn], queueableFns: [beforeFn, queueableFn],
onComplete: onComplete, onComplete: onComplete,
onException: onException onException: onException
@@ -330,7 +330,7 @@ describe('QueueRunner', function() {
}, },
onComplete = jasmine.createSpy('onComplete'), onComplete = jasmine.createSpy('onComplete'),
onException = jasmine.createSpy('onException'), onException = jasmine.createSpy('onException'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn], queueableFns: [queueableFn],
onComplete: onComplete, onComplete: onComplete,
onException: onException onException: onException
@@ -353,7 +353,7 @@ describe('QueueRunner', function() {
}, },
onComplete = jasmine.createSpy('onComplete'), onComplete = jasmine.createSpy('onComplete'),
onException = jasmine.createSpy('onException'), onException = jasmine.createSpy('onException'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn], queueableFns: [queueableFn],
onComplete: onComplete, onComplete: onComplete,
onException: onException onException: onException
@@ -377,7 +377,7 @@ describe('QueueRunner', function() {
}, },
nextQueueableFn = { fn: jasmine.createSpy('nextFn') }, nextQueueableFn = { fn: jasmine.createSpy('nextFn') },
onMultipleDone = jasmine.createSpy('onMultipleDone'), onMultipleDone = jasmine.createSpy('onMultipleDone'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn], queueableFns: [queueableFn, nextQueueableFn],
onMultipleDone: onMultipleDone onMultipleDone: onMultipleDone
}); });
@@ -396,7 +396,7 @@ describe('QueueRunner', function() {
} }
}, },
nextQueueableFn = { fn: jasmine.createSpy('nextFn') }, nextQueueableFn = { fn: jasmine.createSpy('nextFn') },
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn] queueableFns: [queueableFn, nextQueueableFn]
}); });
queueRunner.execute(); queueRunner.execute();
@@ -412,7 +412,7 @@ describe('QueueRunner', function() {
doneReturn = done(); doneReturn = done();
} }
}; };
const queueRunner = new privateUnderTest.QueueRunner({ const queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn] queueableFns: [queueableFn]
}); });
@@ -433,7 +433,7 @@ describe('QueueRunner', function() {
pushListener: jasmine.createSpy('pushListener'), pushListener: jasmine.createSpy('pushListener'),
popListener: jasmine.createSpy('popListener') popListener: jasmine.createSpy('popListener')
}, },
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn], queueableFns: [queueableFn, nextQueueableFn],
onException: onException, onException: onException,
globalErrors: globalErrors globalErrors: globalErrors
@@ -471,6 +471,31 @@ describe('QueueRunner', function() {
expect(nextQueueableFn.fn).toHaveBeenCalled(); expect(nextQueueableFn.fn).toHaveBeenCalled();
}); });
it('handles a global error event with a message but no error', function() {
const queueableFn = {
fn: function(done) {
const currentHandler = globalErrors.pushListener.calls.mostRecent()
.args[0];
currentHandler(undefined, { message: 'nope' });
},
timeout: 1
};
const onException = jasmine.createSpy('onException');
const globalErrors = {
pushListener: jasmine.createSpy('pushListener'),
popListener: jasmine.createSpy('popListener')
};
const queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn],
onException: onException,
globalErrors: globalErrors
});
queueRunner.execute();
expect(onException).toHaveBeenCalledWith('nope');
});
it('handles exceptions thrown while waiting for the stack to clear', function() { it('handles exceptions thrown while waiting for the stack to clear', function() {
const queueableFn = { const queueableFn = {
fn: function(done) { fn: function(done) {
@@ -486,9 +511,9 @@ describe('QueueRunner', function() {
errorListeners.pop(); errorListeners.pop();
} }
}, },
clearStack = jasmine.createSpyObj('clearStack', ['clearStack']), clearStack = jasmine.createSpy('clearStack'),
onException = jasmine.createSpy('onException'), onException = jasmine.createSpy('onException'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn], queueableFns: [queueableFn],
globalErrors: globalErrors, globalErrors: globalErrors,
clearStack: clearStack, clearStack: clearStack,
@@ -498,12 +523,46 @@ describe('QueueRunner', function() {
queueRunner.execute(); queueRunner.execute();
jasmine.clock().tick(); jasmine.clock().tick();
expect(clearStack.clearStack).toHaveBeenCalled(); expect(clearStack).toHaveBeenCalled();
expect(errorListeners.length).toEqual(1); expect(errorListeners.length).toEqual(1);
errorListeners[0](error); errorListeners[0](error);
clearStack.clearStack.calls.argsFor(0)[0](); clearStack.calls.argsFor(0)[0]();
expect(onException).toHaveBeenCalledWith(error); expect(onException).toHaveBeenCalledWith(error);
}); });
it('handles a global error event with no error while waiting for the stack to clear', function() {
const queueableFn = {
fn: function(done) {
done();
}
};
const errorListeners = [];
const globalErrors = {
pushListener: function(f) {
errorListeners.push(f);
},
popListener: function() {
errorListeners.pop();
}
};
const clearStack = jasmine.createSpy('clearStack');
const onException = jasmine.createSpy('onException');
const queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn],
globalErrors: globalErrors,
clearStack: clearStack,
onException: onException
});
queueRunner.execute();
jasmine.clock().tick();
expect(clearStack).toHaveBeenCalled();
expect(errorListeners.length).toEqual(1);
errorListeners[0](undefined, { message: 'nope' });
clearStack.calls.argsFor(0)[0]();
expect(onException).toHaveBeenCalledWith('nope');
});
}); });
describe('with a function that returns a promise', function() { describe('with a function that returns a promise', function() {
@@ -544,7 +603,7 @@ describe('QueueRunner', function() {
return p2; return p2;
} }
}, },
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2], queueableFns: [queueableFn1, queueableFn2],
onComplete: onComplete onComplete: onComplete
}); });
@@ -575,7 +634,7 @@ describe('QueueRunner', function() {
}, },
queueableFn2 = { fn: jasmine.createSpy('fn2') }, queueableFn2 = { fn: jasmine.createSpy('fn2') },
onExceptionCallback = jasmine.createSpy('on exception callback'), onExceptionCallback = jasmine.createSpy('on exception callback'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2], queueableFns: [queueableFn1, queueableFn2],
onException: onExceptionCallback onException: onExceptionCallback
}); });
@@ -598,7 +657,7 @@ describe('QueueRunner', function() {
} }
}, },
onException = jasmine.createSpy('onException'), onException = jasmine.createSpy('onException'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn], queueableFns: [queueableFn],
onException: onException onException: onException
}); });
@@ -619,7 +678,7 @@ describe('QueueRunner', function() {
it('issues a more specific error if the function is `async`', function() { it('issues a more specific error if the function is `async`', function() {
async function fn(done) {} async function fn(done) {}
const onException = jasmine.createSpy('onException'), const onException = jasmine.createSpy('onException'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [{ fn: fn }], queueableFns: [{ fn: fn }],
onException: onException onException: onException
}); });
@@ -640,7 +699,7 @@ describe('QueueRunner', function() {
it('passes final errors to exception handlers', function() { it('passes final errors to exception handlers', function() {
const error = new Error('fake error'), const error = new Error('fake error'),
onExceptionCallback = jasmine.createSpy('on exception callback'), onExceptionCallback = jasmine.createSpy('on exception callback'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
onException: onExceptionCallback onException: onExceptionCallback
}); });
@@ -658,7 +717,7 @@ describe('QueueRunner', function() {
} }
}, },
onExceptionCallback = jasmine.createSpy('on exception callback'), onExceptionCallback = jasmine.createSpy('on exception callback'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn], queueableFns: [queueableFn],
onException: onExceptionCallback onException: onExceptionCallback
}); });
@@ -675,7 +734,7 @@ describe('QueueRunner', function() {
} }
}, },
nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, nextQueueableFn = { fn: jasmine.createSpy('nextFunction') },
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn] queueableFns: [queueableFn, nextQueueableFn]
}); });
@@ -688,7 +747,7 @@ describe('QueueRunner', function() {
const SkipPolicy = jasmine.createSpy('SkipPolicy ctor'); const SkipPolicy = jasmine.createSpy('SkipPolicy ctor');
const queueableFns = [{ fn: () => {} }, { fn: () => {} }]; const queueableFns = [{ fn: () => {} }, { fn: () => {} }];
new privateUnderTest.QueueRunner({ new jasmineUnderTest.QueueRunner({
queueableFns, queueableFns,
SkipPolicy SkipPolicy
}); });
@@ -710,7 +769,7 @@ describe('QueueRunner', function() {
skipPolicy.skipTo.and.callFake(function(lastRanIx) { skipPolicy.skipTo.and.callFake(function(lastRanIx) {
return lastRanIx === 0 ? 2 : lastRanIx + 1; return lastRanIx === 0 ? 2 : lastRanIx + 1;
}); });
const queueRunner = new privateUnderTest.QueueRunner({ const queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns, queueableFns,
SkipPolicy: function() { SkipPolicy: function() {
return skipPolicy; return skipPolicy;
@@ -731,7 +790,7 @@ describe('QueueRunner', function() {
it('throws if the skip policy returns the current fn', function() { it('throws if the skip policy returns the current fn', function() {
const skipPolicy = { skipTo: i => i }; const skipPolicy = { skipTo: i => i };
const queueableFns = [{ fn: () => {} }]; const queueableFns = [{ fn: () => {} }];
const queueRunner = new privateUnderTest.QueueRunner({ const queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns, queueableFns,
SkipPolicy: function() { SkipPolicy: function() {
return skipPolicy; return skipPolicy;
@@ -757,17 +816,17 @@ describe('QueueRunner', function() {
type: 'specCleanup' type: 'specCleanup'
}, },
onComplete = jasmine.createSpy('onComplete'), onComplete = jasmine.createSpy('onComplete'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn, cleanupFn], queueableFns: [queueableFn, nextQueueableFn, cleanupFn],
onComplete: onComplete, onComplete: onComplete,
SkipPolicy: privateUnderTest.CompleteOnFirstErrorSkipPolicy SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy
}); });
queueRunner.execute(); queueRunner.execute();
expect(nextQueueableFn.fn).not.toHaveBeenCalled(); expect(nextQueueableFn.fn).not.toHaveBeenCalled();
expect(cleanupFn.fn).toHaveBeenCalled(); expect(cleanupFn.fn).toHaveBeenCalled();
expect(onComplete).toHaveBeenCalledWith( expect(onComplete).toHaveBeenCalledWith(
jasmine.any(privateUnderTest.StopExecutionError) jasmine.any(jasmineUnderTest.StopExecutionError)
); );
}); });
@@ -783,9 +842,9 @@ describe('QueueRunner', function() {
fn: jasmine.createSpy('cleanupFn2'), fn: jasmine.createSpy('cleanupFn2'),
type: 'afterEach' type: 'afterEach'
}, },
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, cleanupFn1, cleanupFn2], queueableFns: [queueableFn, cleanupFn1, cleanupFn2],
SkipPolicy: privateUnderTest.CompleteOnFirstErrorSkipPolicy SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy
}); });
queueRunner.execute(); queueRunner.execute();
@@ -814,7 +873,7 @@ describe('QueueRunner', function() {
fn: jasmine.createSpy('cleanup'), fn: jasmine.createSpy('cleanup'),
type: 'specCleanup' type: 'specCleanup'
}; };
const queueRunner = new privateUnderTest.QueueRunner({ const queueRunner = new jasmineUnderTest.QueueRunner({
globalErrors: { globalErrors: {
pushListener: function(f) { pushListener: function(f) {
errorListeners.push(f); errorListeners.push(f);
@@ -824,7 +883,7 @@ describe('QueueRunner', function() {
} }
}, },
queueableFns: [queueableFn, nextQueueableFn, cleanupFn], queueableFns: [queueableFn, nextQueueableFn, cleanupFn],
SkipPolicy: privateUnderTest.CompleteOnFirstErrorSkipPolicy SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy
}); });
queueRunner.execute(); queueRunner.execute();
@@ -843,9 +902,9 @@ describe('QueueRunner', function() {
}, },
nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, nextQueueableFn = { fn: jasmine.createSpy('nextFunction') },
cleanupFn = { fn: jasmine.createSpy('cleanup'), type: 'specCleanup' }, cleanupFn = { fn: jasmine.createSpy('cleanup'), type: 'specCleanup' },
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn, cleanupFn], queueableFns: [queueableFn, nextQueueableFn, cleanupFn],
SkipPolicy: privateUnderTest.CompleteOnFirstErrorSkipPolicy SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy
}); });
queueRunner.execute(); queueRunner.execute();
@@ -865,9 +924,9 @@ describe('QueueRunner', function() {
fn: jasmine.createSpy('cleanup'), fn: jasmine.createSpy('cleanup'),
type: 'specCleanup' type: 'specCleanup'
}, },
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn, cleanupFn], queueableFns: [queueableFn, nextQueueableFn, cleanupFn],
SkipPolicy: privateUnderTest.CompleteOnFirstErrorSkipPolicy SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy
}); });
queueRunner.execute(); queueRunner.execute();
@@ -881,7 +940,7 @@ describe('QueueRunner', function() {
it('calls a provided complete callback when done', function() { it('calls a provided complete callback when done', function() {
const queueableFn = { fn: jasmine.createSpy('fn') }, const queueableFn = { fn: jasmine.createSpy('fn') },
completeCallback = jasmine.createSpy('completeCallback'), completeCallback = jasmine.createSpy('completeCallback'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn], queueableFns: [queueableFn],
onComplete: completeCallback onComplete: completeCallback
}); });
@@ -908,22 +967,22 @@ describe('QueueRunner', function() {
}, },
afterFn = { fn: jasmine.createSpy('afterFn') }, afterFn = { fn: jasmine.createSpy('afterFn') },
completeCallback = jasmine.createSpy('completeCallback'), completeCallback = jasmine.createSpy('completeCallback'),
clearStack = jasmine.createSpyObj('clearStack', ['clearStack']), clearStack = jasmine.createSpy('clearStack'),
queueRunner = new privateUnderTest.QueueRunner({ queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [asyncFn, afterFn], queueableFns: [asyncFn, afterFn],
clearStack: clearStack, clearStack: clearStack,
onComplete: completeCallback onComplete: completeCallback
}); });
clearStack.clearStack.and.callFake(function(fn) { clearStack.and.callFake(function(fn) {
fn(); fn();
}); });
queueRunner.execute(); queueRunner.execute();
jasmine.clock().tick(); jasmine.clock().tick();
expect(afterFn.fn).toHaveBeenCalled(); expect(afterFn.fn).toHaveBeenCalled();
expect(clearStack.clearStack).toHaveBeenCalled(); expect(clearStack).toHaveBeenCalled();
clearStack.clearStack.calls.argsFor(0)[0](); clearStack.calls.argsFor(0)[0]();
expect(completeCallback).toHaveBeenCalled(); expect(completeCallback).toHaveBeenCalled();
}); });
}); });
@@ -933,7 +992,7 @@ describe('QueueRunner', function() {
const fn = jasmine.createSpy('fn1'); const fn = jasmine.createSpy('fn1');
this.fn = fn; this.fn = fn;
this.queueRunner = new privateUnderTest.QueueRunner({ this.queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [{ fn: fn }] queueableFns: [{ fn: fn }]
}); });
}); });
@@ -946,7 +1005,7 @@ describe('QueueRunner', function() {
this.queueRunner.execute(); this.queueRunner.execute();
expect(context.constructor).toBe(privateUnderTest.UserContext); expect(context.constructor).toBe(jasmineUnderTest.UserContext);
}); });
}); });
@@ -956,8 +1015,8 @@ describe('QueueRunner', function() {
let context; let context;
this.fn = fn; this.fn = fn;
this.context = context = new privateUnderTest.UserContext(); this.context = context = new jasmineUnderTest.UserContext();
this.queueRunner = new privateUnderTest.QueueRunner({ this.queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [{ fn: fn }], queueableFns: [{ fn: fn }],
userContext: context userContext: context
}); });
+21 -54
View File
@@ -1,6 +1,6 @@
describe('ReportDispatcher', function() { describe('ReportDispatcher', function() {
it('builds an interface of requested methods', function() { it('builds an interface of requested methods', function() {
const dispatcher = new privateUnderTest.ReportDispatcher([ const dispatcher = new jasmineUnderTest.ReportDispatcher([
'foo', 'foo',
'bar', 'bar',
'baz' 'baz'
@@ -13,7 +13,7 @@ describe('ReportDispatcher', function() {
it('dispatches requested methods to added reporters', function() { it('dispatches requested methods to added reporters', function() {
const runQueue = jasmine.createSpy('runQueue'), const runQueue = jasmine.createSpy('runQueue'),
dispatcher = new privateUnderTest.ReportDispatcher( dispatcher = new jasmineUnderTest.ReportDispatcher(
['foo', 'bar'], ['foo', 'bar'],
runQueue runQueue
), ),
@@ -23,7 +23,7 @@ describe('ReportDispatcher', function() {
dispatcher.addReporter(reporter); dispatcher.addReporter(reporter);
dispatcher.addReporter(anotherReporter); dispatcher.addReporter(anotherReporter);
dispatcher.foo({ an: 'event' }); dispatcher.foo(123, 456);
expect(runQueue).toHaveBeenCalledWith( expect(runQueue).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
@@ -37,16 +37,16 @@ describe('ReportDispatcher', function() {
let fns = runQueue.calls.mostRecent().args[0].queueableFns; let fns = runQueue.calls.mostRecent().args[0].queueableFns;
fns[0].fn(); fns[0].fn();
expect(reporter.foo).toHaveBeenCalledWith({ an: 'event' }); expect(reporter.foo).toHaveBeenCalledWith(123, 456);
expect(reporter.foo.calls.mostRecent().object).toBe(reporter); expect(reporter.foo.calls.mostRecent().object).toBe(reporter);
fns[1].fn(); fns[1].fn();
expect(anotherReporter.foo).toHaveBeenCalledWith({ an: 'event' }); expect(anotherReporter.foo).toHaveBeenCalledWith(123, 456);
expect(anotherReporter.foo.calls.mostRecent().object).toBe(anotherReporter); expect(anotherReporter.foo.calls.mostRecent().object).toBe(anotherReporter);
runQueue.calls.reset(); runQueue.calls.reset();
dispatcher.bar({ another: 'event' }); dispatcher.bar('a', 'b');
expect(runQueue).toHaveBeenCalledWith( expect(runQueue).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
@@ -60,48 +60,15 @@ describe('ReportDispatcher', function() {
fns = runQueue.calls.mostRecent().args[0].queueableFns; fns = runQueue.calls.mostRecent().args[0].queueableFns;
fns[0].fn(); fns[0].fn();
expect(reporter.bar).toHaveBeenCalledWith({ another: 'event' }); expect(reporter.bar).toHaveBeenCalledWith('a', 'b');
fns[1].fn(); fns[1].fn();
expect(anotherReporter.bar).toHaveBeenCalledWith({ another: 'event' }); expect(anotherReporter.bar).toHaveBeenCalledWith('a', 'b');
});
it('passes each reporter a separate deep copy of the event', function() {
const runQueue = jasmine.createSpy('runQueue');
const dispatcher = new privateUnderTest.ReportDispatcher(
['foo', 'bar'],
runQueue
);
const reporter = jasmine.createSpyObj('reporter', ['foo']);
const anotherReporter = jasmine.createSpyObj('anotherReporter', ['foo']);
const event = {
child: {
grandchild: 'something'
}
};
dispatcher.addReporter(reporter);
dispatcher.addReporter(anotherReporter);
dispatcher.foo(event);
for (const fn of runQueue.calls.mostRecent().args[0].queueableFns) {
fn.fn();
}
expect(reporter.foo).toHaveBeenCalledWith(event);
expect(anotherReporter.foo).toHaveBeenCalledWith(event);
const receivedEvents = [reporter, anotherReporter].map(function(reporter) {
return reporter.foo.calls.mostRecent().args[0];
});
expect(receivedEvents[0]).not.toBe(event);
expect(receivedEvents[0]).not.toBe(receivedEvents[1]);
expect(receivedEvents[0].child).not.toBe(event.child);
expect(receivedEvents[0].child).not.toBe(receivedEvents[1].child);
}); });
it("does not dispatch to a reporter if the reporter doesn't accept the method", function() { it("does not dispatch to a reporter if the reporter doesn't accept the method", function() {
const runQueue = jasmine.createSpy('runQueue'), const runQueue = jasmine.createSpy('runQueue'),
dispatcher = new privateUnderTest.ReportDispatcher(['foo'], runQueue), dispatcher = new jasmineUnderTest.ReportDispatcher(['foo'], runQueue),
reporter = jasmine.createSpyObj('reporter', ['baz']); reporter = jasmine.createSpyObj('reporter', ['baz']);
dispatcher.addReporter(reporter); dispatcher.addReporter(reporter);
@@ -116,14 +83,14 @@ describe('ReportDispatcher', function() {
it("allows providing a fallback reporter in case there's no other reporter", function() { it("allows providing a fallback reporter in case there's no other reporter", function() {
const runQueue = jasmine.createSpy('runQueue'), const runQueue = jasmine.createSpy('runQueue'),
dispatcher = new privateUnderTest.ReportDispatcher( dispatcher = new jasmineUnderTest.ReportDispatcher(
['foo', 'bar'], ['foo', 'bar'],
runQueue runQueue
), ),
reporter = jasmine.createSpyObj('reporter', ['foo', 'bar']); reporter = jasmine.createSpyObj('reporter', ['foo', 'bar']);
dispatcher.provideFallbackReporter(reporter); dispatcher.provideFallbackReporter(reporter);
dispatcher.foo({ an: 'event' }); dispatcher.foo(123, 456);
expect(runQueue).toHaveBeenCalledWith( expect(runQueue).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
@@ -134,12 +101,12 @@ describe('ReportDispatcher', function() {
const fns = runQueue.calls.mostRecent().args[0].queueableFns; const fns = runQueue.calls.mostRecent().args[0].queueableFns;
fns[0].fn(); fns[0].fn();
expect(reporter.foo).toHaveBeenCalledWith({ an: 'event' }); expect(reporter.foo).toHaveBeenCalledWith(123, 456);
}); });
it('does not call fallback reporting methods when another reporter is provided', function() { it('does not call fallback reporting methods when another reporter is provided', function() {
const runQueue = jasmine.createSpy('runQueue'), const runQueue = jasmine.createSpy('runQueue'),
dispatcher = new privateUnderTest.ReportDispatcher( dispatcher = new jasmineUnderTest.ReportDispatcher(
['foo', 'bar'], ['foo', 'bar'],
runQueue runQueue
), ),
@@ -148,7 +115,7 @@ describe('ReportDispatcher', function() {
dispatcher.provideFallbackReporter(fallbackReporter); dispatcher.provideFallbackReporter(fallbackReporter);
dispatcher.addReporter(reporter); dispatcher.addReporter(reporter);
dispatcher.foo({ an: 'event' }); dispatcher.foo(123, 456);
expect(runQueue).toHaveBeenCalledWith( expect(runQueue).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
@@ -159,13 +126,13 @@ describe('ReportDispatcher', function() {
const fns = runQueue.calls.mostRecent().args[0].queueableFns; const fns = runQueue.calls.mostRecent().args[0].queueableFns;
fns[0].fn(); fns[0].fn();
expect(reporter.foo).toHaveBeenCalledWith({ an: 'event' }); expect(reporter.foo).toHaveBeenCalledWith(123, 456);
expect(fallbackReporter.foo).not.toHaveBeenCalled(); expect(fallbackReporter.foo).not.toHaveBeenCalledWith(123, 456);
}); });
it('allows registered reporters to be cleared', function() { it('allows registered reporters to be cleared', function() {
const runQueue = jasmine.createSpy('runQueue'), const runQueue = jasmine.createSpy('runQueue'),
dispatcher = new privateUnderTest.ReportDispatcher( dispatcher = new jasmineUnderTest.ReportDispatcher(
['foo', 'bar'], ['foo', 'bar'],
runQueue runQueue
), ),
@@ -173,7 +140,7 @@ describe('ReportDispatcher', function() {
reporter2 = jasmine.createSpyObj('reporter2', ['foo', 'bar']); reporter2 = jasmine.createSpyObj('reporter2', ['foo', 'bar']);
dispatcher.addReporter(reporter1); dispatcher.addReporter(reporter1);
dispatcher.foo({ an: 'event' }); dispatcher.foo(123);
expect(runQueue).toHaveBeenCalledWith( expect(runQueue).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
queueableFns: [{ fn: jasmine.any(Function) }], queueableFns: [{ fn: jasmine.any(Function) }],
@@ -183,11 +150,11 @@ describe('ReportDispatcher', function() {
let fns = runQueue.calls.mostRecent().args[0].queueableFns; let fns = runQueue.calls.mostRecent().args[0].queueableFns;
fns[0].fn(); fns[0].fn();
expect(reporter1.foo).toHaveBeenCalledWith({ an: 'event' }); expect(reporter1.foo).toHaveBeenCalledWith(123);
dispatcher.clearReporters(); dispatcher.clearReporters();
dispatcher.addReporter(reporter2); dispatcher.addReporter(reporter2);
dispatcher.bar({ another: 'event' }); dispatcher.bar(456);
expect(runQueue).toHaveBeenCalledWith( expect(runQueue).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
@@ -199,6 +166,6 @@ describe('ReportDispatcher', function() {
fns = runQueue.calls.mostRecent().args[0].queueableFns; fns = runQueue.calls.mostRecent().args[0].queueableFns;
fns[0].fn(); fns[0].fn();
expect(reporter1.bar).not.toHaveBeenCalled(); expect(reporter1.bar).not.toHaveBeenCalled();
expect(reporter2.bar).toHaveBeenCalledWith({ another: 'event' }); expect(reporter2.bar).toHaveBeenCalledWith(456);
}); });
}); });
+45 -45
View File
@@ -38,7 +38,7 @@ describe('RunableResources', function() {
describe('#addCustomMatchers', function() { describe('#addCustomMatchers', function() {
it("adds all properties to the current runable's matchers", function() { it("adds all properties to the current runable's matchers", function() {
const currentRunableId = 1; const currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -70,7 +70,7 @@ describe('RunableResources', function() {
describe('#addCustomAsyncMatchers', function() { describe('#addCustomAsyncMatchers', function() {
it("adds all properties to the current runable's matchers", function() { it("adds all properties to the current runable's matchers", function() {
const currentRunableId = 1; const currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -95,7 +95,7 @@ describe('RunableResources', function() {
describe('#defaultSpyStrategy', function() { describe('#defaultSpyStrategy', function() {
it('returns undefined for a newly initialized resource', function() { it('returns undefined for a newly initialized resource', function() {
let currentRunableId = 1; let currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -106,7 +106,7 @@ describe('RunableResources', function() {
it('returns the value previously set by #setDefaultSpyStrategy', function() { it('returns the value previously set by #setDefaultSpyStrategy', function() {
let currentRunableId = 1; let currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -119,7 +119,7 @@ describe('RunableResources', function() {
it('is per-runable', function() { it('is per-runable', function() {
let currentRunableId = 1; let currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -132,7 +132,7 @@ describe('RunableResources', function() {
}); });
it('does not require a current runable', function() { it('does not require a current runable', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => null getCurrentRunableId: () => null
}); });
@@ -141,7 +141,7 @@ describe('RunableResources', function() {
it("inherits the parent runable's value", function() { it("inherits the parent runable's value", function() {
let currentRunableId = 1; let currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -157,7 +157,7 @@ describe('RunableResources', function() {
describe('#setDefaultSpyStrategy', function() { describe('#setDefaultSpyStrategy', function() {
it('throws a user-facing error when there is no current runable', function() { it('throws a user-facing error when there is no current runable', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => null getCurrentRunableId: () => null
}); });
@@ -171,21 +171,21 @@ describe('RunableResources', function() {
describe('#makePrettyPrinter', function() { describe('#makePrettyPrinter', function() {
it('returns a pretty printer configured with the current customObjectFormatters', function() { it('returns a pretty printer configured with the current customObjectFormatters', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => 1 getCurrentRunableId: () => 1
}); });
runableResources.initForRunable(1); runableResources.initForRunable(1);
function cof() {} function cof() {}
runableResources.customObjectFormatters().push(cof); runableResources.customObjectFormatters().push(cof);
spyOn(privateUnderTest, 'makePrettyPrinter').and.callThrough(); spyOn(jasmineUnderTest, 'makePrettyPrinter').and.callThrough();
const pp = runableResources.makePrettyPrinter(); const pp = runableResources.makePrettyPrinter();
expect(privateUnderTest.makePrettyPrinter).toHaveBeenCalledOnceWith([ expect(jasmineUnderTest.makePrettyPrinter).toHaveBeenCalledOnceWith([
cof cof
]); ]);
expect(pp).toBe( expect(pp).toBe(
privateUnderTest.makePrettyPrinter.calls.first().returnValue jasmineUnderTest.makePrettyPrinter.calls.first().returnValue
); );
}); });
}); });
@@ -193,7 +193,7 @@ describe('RunableResources', function() {
describe('#makeMatchersUtil', function() { describe('#makeMatchersUtil', function() {
describe('When there is a current runable', function() { describe('When there is a current runable', function() {
it('returns a MatchersUtil configured with the current resources', function() { it('returns a MatchersUtil configured with the current resources', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => 1 getCurrentRunableId: () => 1
}); });
@@ -204,26 +204,26 @@ describe('RunableResources', function() {
runableResources.customEqualityTesters().push(ceq); runableResources.customEqualityTesters().push(ceq);
const expectedPP = {}; const expectedPP = {};
const expectedMatchersUtil = {}; const expectedMatchersUtil = {};
spyOn(privateUnderTest, 'makePrettyPrinter').and.returnValue( spyOn(jasmineUnderTest, 'makePrettyPrinter').and.returnValue(
expectedPP expectedPP
); );
spyOn(privateUnderTest, 'MatchersUtil').and.returnValue( spyOn(jasmineUnderTest, 'MatchersUtil').and.returnValue(
expectedMatchersUtil expectedMatchersUtil
); );
const matchersUtil = runableResources.makeMatchersUtil(); const matchersUtil = runableResources.makeMatchersUtil();
expect(matchersUtil).toBe(expectedMatchersUtil); expect(matchersUtil).toBe(expectedMatchersUtil);
expect(privateUnderTest.makePrettyPrinter).toHaveBeenCalledOnceWith([ expect(jasmineUnderTest.makePrettyPrinter).toHaveBeenCalledOnceWith([
cof cof
]); ]);
// We need === equality on the pp passed to MatchersUtil // We need === equality on the pp passed to MatchersUtil
expect(privateUnderTest.MatchersUtil).toHaveBeenCalledOnceWith( expect(jasmineUnderTest.MatchersUtil).toHaveBeenCalledOnceWith(
jasmine.objectContaining({ jasmine.objectContaining({
customTesters: [ceq] customTesters: [ceq]
}) })
); );
expect(privateUnderTest.MatchersUtil.calls.argsFor(0)[0].pp).toBe( expect(jasmineUnderTest.MatchersUtil.calls.argsFor(0)[0].pp).toBe(
expectedPP expectedPP
); );
}); });
@@ -231,12 +231,12 @@ describe('RunableResources', function() {
describe('When there is no current runable', function() { describe('When there is no current runable', function() {
it('returns a MatchersUtil configured with defaults', function() { it('returns a MatchersUtil configured with defaults', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => null getCurrentRunableId: () => null
}); });
const expectedMatchersUtil = {}; const expectedMatchersUtil = {};
spyOn(privateUnderTest, 'MatchersUtil').and.returnValue( spyOn(jasmineUnderTest, 'MatchersUtil').and.returnValue(
expectedMatchersUtil expectedMatchersUtil
); );
@@ -244,12 +244,12 @@ describe('RunableResources', function() {
expect(matchersUtil).toBe(expectedMatchersUtil); expect(matchersUtil).toBe(expectedMatchersUtil);
// We need === equality on the pp passed to MatchersUtil // We need === equality on the pp passed to MatchersUtil
expect(privateUnderTest.MatchersUtil).toHaveBeenCalledTimes(1); expect(jasmineUnderTest.MatchersUtil).toHaveBeenCalledTimes(1);
expect(privateUnderTest.MatchersUtil.calls.argsFor(0)[0].pp).toBe( expect(jasmineUnderTest.MatchersUtil.calls.argsFor(0)[0].pp).toBe(
privateUnderTest.basicPrettyPrinter jasmineUnderTest.basicPrettyPrinter_
); );
expect( expect(
privateUnderTest.MatchersUtil.calls.argsFor(0)[0].customTesters jasmineUnderTest.MatchersUtil.calls.argsFor(0)[0].customTesters
).toBeUndefined(); ).toBeUndefined();
}); });
}); });
@@ -258,11 +258,11 @@ describe('RunableResources', function() {
describe('.spyFactory', function() { describe('.spyFactory', function() {
describe('When there is no current runable', function() { describe('When there is no current runable', function() {
it('is configured with default strategies and matchersUtil', function() { it('is configured with default strategies and matchersUtil', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => null getCurrentRunableId: () => null
}); });
spyOn(privateUnderTest, 'Spy'); spyOn(jasmineUnderTest, 'Spy');
const matchersUtil = {}; const matchersUtil = {};
spyOn(runableResources, 'makeMatchersUtil').and.returnValue( spyOn(runableResources, 'makeMatchersUtil').and.returnValue(
matchersUtil matchersUtil
@@ -270,7 +270,7 @@ describe('RunableResources', function() {
runableResources.spyFactory.createSpy('foo'); runableResources.spyFactory.createSpy('foo');
expect(privateUnderTest.Spy).toHaveBeenCalledWith( expect(jasmineUnderTest.Spy).toHaveBeenCalledWith(
'foo', 'foo',
is(matchersUtil), is(matchersUtil),
jasmine.objectContaining({ jasmine.objectContaining({
@@ -283,7 +283,7 @@ describe('RunableResources', function() {
describe('When there is a current runable', function() { describe('When there is a current runable', function() {
it("is configured with the current runable's strategies and matchersUtil", function() { it("is configured with the current runable's strategies and matchersUtil", function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => 1 getCurrentRunableId: () => 1
}); });
@@ -292,7 +292,7 @@ describe('RunableResources', function() {
function defaultStrategy() {} function defaultStrategy() {}
runableResources.customSpyStrategies().foo = customStrategy; runableResources.customSpyStrategies().foo = customStrategy;
runableResources.setDefaultSpyStrategy(defaultStrategy); runableResources.setDefaultSpyStrategy(defaultStrategy);
spyOn(privateUnderTest, 'Spy'); spyOn(jasmineUnderTest, 'Spy');
const matchersUtil = {}; const matchersUtil = {};
spyOn(runableResources, 'makeMatchersUtil').and.returnValue( spyOn(runableResources, 'makeMatchersUtil').and.returnValue(
matchersUtil matchersUtil
@@ -300,7 +300,7 @@ describe('RunableResources', function() {
runableResources.spyFactory.createSpy('foo'); runableResources.spyFactory.createSpy('foo');
expect(privateUnderTest.Spy).toHaveBeenCalledWith( expect(jasmineUnderTest.Spy).toHaveBeenCalledWith(
'foo', 'foo',
is(matchersUtil), is(matchersUtil),
jasmine.objectContaining({ jasmine.objectContaining({
@@ -325,7 +325,7 @@ describe('RunableResources', function() {
describe('.spyRegistry', function() { describe('.spyRegistry', function() {
it("writes to the current runable's spies", function() { it("writes to the current runable's spies", function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => 1 getCurrentRunableId: () => 1
}); });
@@ -348,7 +348,7 @@ describe('RunableResources', function() {
describe('#clearForRunable', function() { describe('#clearForRunable', function() {
it('removes resources for the specified runable', function() { it('removes resources for the specified runable', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => 1 getCurrentRunableId: () => 1
}); });
@@ -363,7 +363,7 @@ describe('RunableResources', function() {
}); });
it('clears spies', function() { it('clears spies', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => 1 getCurrentRunableId: () => 1
}); });
@@ -381,7 +381,7 @@ describe('RunableResources', function() {
const globalErrors = jasmine.createSpyObj('globalErrors', [ const globalErrors = jasmine.createSpyObj('globalErrors', [
'removeOverrideListener' 'removeOverrideListener'
]); ]);
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
getCurrentRunableId: () => 1, getCurrentRunableId: () => 1,
globalErrors globalErrors
}); });
@@ -392,7 +392,7 @@ describe('RunableResources', function() {
}); });
it('does not remove resources for other runables', function() { it('does not remove resources for other runables', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => 1 getCurrentRunableId: () => 1
}); });
@@ -411,7 +411,7 @@ describe('RunableResources', function() {
) { ) {
it('is initially empty', function() { it('is initially empty', function() {
const currentRunableId = 1; const currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -422,7 +422,7 @@ describe('RunableResources', function() {
it('is mutable', function() { it('is mutable', function() {
const currentRunableId = 1; const currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -434,7 +434,7 @@ describe('RunableResources', function() {
it('is per-runable', function() { it('is per-runable', function() {
let currentRunableId = 1; let currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -446,7 +446,7 @@ describe('RunableResources', function() {
}); });
it('throws a user-facing error when there is no current runable', function() { it('throws a user-facing error when there is no current runable', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => null getCurrentRunableId: () => null
}); });
@@ -458,7 +458,7 @@ describe('RunableResources', function() {
if (inherits) { if (inherits) {
it('inherits from the parent runable', function() { it('inherits from the parent runable', function() {
let currentRunableId = 1; let currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -480,7 +480,7 @@ describe('RunableResources', function() {
function behavesLikeAPerRunableMutableObject(methodName, errorMsg) { function behavesLikeAPerRunableMutableObject(methodName, errorMsg) {
it('is initially empty', function() { it('is initially empty', function() {
const currentRunableId = 1; const currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -491,7 +491,7 @@ describe('RunableResources', function() {
it('is mutable', function() { it('is mutable', function() {
const currentRunableId = 1; const currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -503,7 +503,7 @@ describe('RunableResources', function() {
it('is per-runable', function() { it('is per-runable', function() {
let currentRunableId = 1; let currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
@@ -515,7 +515,7 @@ describe('RunableResources', function() {
}); });
it('throws a user-facing error when there is no current runable', function() { it('throws a user-facing error when there is no current runable', function() {
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => null getCurrentRunableId: () => null
}); });
@@ -526,7 +526,7 @@ describe('RunableResources', function() {
it('inherits from the parent runable', function() { it('inherits from the parent runable', function() {
let currentRunableId = 1; let currentRunableId = 1;
const runableResources = new privateUnderTest.RunableResources({ const runableResources = new jasmineUnderTest.RunableResources({
globalErrors: stubGlobalErrors(), globalErrors: stubGlobalErrors(),
getCurrentRunableId: () => currentRunableId getCurrentRunableId: () => currentRunableId
}); });
+169 -45
View File
@@ -15,10 +15,10 @@ describe('Runner', function() {
globalErrors = 'the global errors instance'; globalErrors = 'the global errors instance';
reportDispatcher = jasmine.createSpyObj( reportDispatcher = jasmine.createSpyObj(
'reportDispatcher', 'reportDispatcher',
privateUnderTest.reporterEvents jasmineUnderTest.reporterEvents
); );
for (const k of privateUnderTest.reporterEvents) { for (const k of jasmineUnderTest.reporterEvents) {
reportDispatcher[k].and.returnValue(Promise.resolve()); reportDispatcher[k].and.returnValue(Promise.resolve());
} }
@@ -26,22 +26,25 @@ describe('Runner', function() {
failSpecWithNoExpectations = false; failSpecWithNoExpectations = false;
detectLateRejectionHandling = false; detectLateRejectionHandling = false;
spyOn(privateUnderTest.TreeRunner.prototype, '_executeSpec'); spyOn(jasmineUnderTest.TreeRunner.prototype, '_executeSpec');
}); });
function StubSuite(attrs) { function StubSuite(attrs) {
attrs = attrs || {}; attrs = attrs || {};
this.id = 'suite' + suiteNumber++; this.id = 'suite' + suiteNumber++;
this.children = attrs.children || []; this.children = attrs.children || [];
this.canBeReentered = function() {
return !attrs.noReenter;
};
this.markedPending = attrs.markedPending || false; this.markedPending = attrs.markedPending || false;
this.sharedUserContext = function() { this.sharedUserContext = function() {
return attrs.userContext || {}; return attrs.userContext || {};
}; };
this.startedEvent = jasmine.createSpy('startedEvent'); this.result = {
this.doneEvent = jasmine.createSpy('doneEvent'); id: this.id,
this.hasOwnFailedExpectations = jasmine.createSpy( failedExpectations: []
'hasOwnFailedExpectations' };
); this.getResult = jasmine.createSpy('getResult');
this.beforeAllFns = attrs.beforeAllFns || []; this.beforeAllFns = attrs.beforeAllFns || [];
this.afterAllFns = attrs.afterAllFns || []; this.afterAllFns = attrs.afterAllFns || [];
this.cleanupBeforeAfter = function() {}; this.cleanupBeforeAfter = function() {};
@@ -69,7 +72,7 @@ describe('Runner', function() {
}), }),
focusedRunables: () => [], focusedRunables: () => [],
totalSpecsDefined: () => 1, totalSpecsDefined: () => 1,
TreeProcessor: privateUnderTest.TreeProcessor, TreeProcessor: jasmineUnderTest.TreeProcessor,
runableResources: { runableResources: {
initForRunable: () => {}, initForRunable: () => {},
clearForRunable: () => {} clearForRunable: () => {}
@@ -78,7 +81,7 @@ describe('Runner', function() {
globalErrors, globalErrors,
runQueue runQueue
}; };
return new privateUnderTest.Runner({ return new jasmineUnderTest.Runner({
...defaultOptions, ...defaultOptions,
topSuite topSuite
}); });
@@ -87,7 +90,7 @@ describe('Runner', function() {
function arrayNotContaining(item) { function arrayNotContaining(item) {
return { return {
asymmetricMatch(other, matchersUtil) { asymmetricMatch(other, matchersUtil) {
if (!jasmine.private.isArray(other)) { if (!jasmine.isArray_(other)) {
return false; return false;
} }
@@ -102,9 +105,9 @@ describe('Runner', function() {
}; };
} }
// Precondition: privateUnderTest.TreeRunner.prototype._executeSpec is a spy // Precondition: jasmineUnderTest.TreeRunner.prototype._executeSpec is a spy
function verifyAndFinishSpec(spec, queueableFn, shouldBeExcluded) { function verifyAndFinishSpec(spec, queueableFn, shouldBeExcluded) {
const ex = privateUnderTest.TreeRunner.prototype._executeSpec; const ex = jasmineUnderTest.TreeRunner.prototype._executeSpec;
ex.withArgs(spec, 'onComplete').and.callThrough(); ex.withArgs(spec, 'onComplete').and.callThrough();
queueableFn.fn('onComplete'); queueableFn.fn('onComplete');
@@ -113,7 +116,7 @@ describe('Runner', function() {
expect(runQueue).toHaveBeenCalledWith( expect(runQueue).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
isLeaf: true, isLeaf: true,
SkipPolicy: privateUnderTest.CompleteOnFirstErrorSkipPolicy, SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy,
queueableFns: shouldBeExcluded queueableFns: shouldBeExcluded
? arrayNotContaining(spec.queueableFn) ? arrayNotContaining(spec.queueableFn)
: jasmine.arrayContaining([spec.queueableFn]) : jasmine.arrayContaining([spec.queueableFn])
@@ -127,7 +130,6 @@ describe('Runner', function() {
children: [spec], children: [spec],
userContext: { root: 'context' } userContext: { root: 'context' }
}); });
topSuite.doneEvent.and.returnValue({});
detectLateRejectionHandling = true; detectLateRejectionHandling = true;
const subject = makeRunner(topSuite); const subject = makeRunner(topSuite);
@@ -140,7 +142,7 @@ describe('Runner', function() {
userContext: { root: 'context' }, userContext: { root: 'context' },
queueableFns: [{ fn: jasmine.any(Function) }], queueableFns: [{ fn: jasmine.any(Function) }],
onMultipleDone: null, onMultipleDone: null,
SkipPolicy: privateUnderTest.SkipAfterBeforeAllErrorPolicy SkipPolicy: jasmineUnderTest.SkipAfterBeforeAllErrorPolicy
}); });
const runQueueArgs = runQueue.calls.mostRecent().args[0]; const runQueueArgs = runQueue.calls.mostRecent().args[0];
@@ -155,7 +157,6 @@ describe('Runner', function() {
children: [suite], children: [suite],
userContext: { for: 'topSuite' } userContext: { for: 'topSuite' }
}); });
topSuite.doneEvent.and.returnValue({});
suite.parentSuite = topSuite; suite.parentSuite = topSuite;
const subject = makeRunner(topSuite); const subject = makeRunner(topSuite);
@@ -168,7 +169,7 @@ describe('Runner', function() {
userContext: { for: 'topSuite' }, userContext: { for: 'topSuite' },
queueableFns: [{ fn: jasmine.any(Function) }], queueableFns: [{ fn: jasmine.any(Function) }],
onMultipleDone: null, onMultipleDone: null,
SkipPolicy: privateUnderTest.SkipAfterBeforeAllErrorPolicy SkipPolicy: jasmineUnderTest.SkipAfterBeforeAllErrorPolicy
}); });
const runQueueArgs = runQueue.calls.mostRecent().args[0]; const runQueueArgs = runQueue.calls.mostRecent().args[0];
@@ -181,16 +182,13 @@ describe('Runner', function() {
userContext: { for: 'suite' }, userContext: { for: 'suite' },
onException: jasmine.any(Function), onException: jasmine.any(Function),
onMultipleDone: null, onMultipleDone: null,
SkipPolicy: privateUnderTest.SkipAfterBeforeAllErrorPolicy SkipPolicy: jasmineUnderTest.SkipAfterBeforeAllErrorPolicy
}); });
suite.startedEvent.and.returnValue('suite started event');
runQueue.calls.mostRecent().args[0].queueableFns[0].fn('foo'); runQueue.calls.mostRecent().args[0].queueableFns[0].fn('foo');
expect(reportDispatcher.suiteStarted).toHaveBeenCalledWith( expect(reportDispatcher.suiteStarted).toHaveBeenCalledWith(suite.result);
'suite started event'
);
suite.doneEvent.and.returnValue({ my: 'result' }); suite.getResult.and.returnValue({ my: 'result' });
runQueue.calls.mostRecent().args[0].onComplete(); runQueue.calls.mostRecent().args[0].onComplete();
expect(reportDispatcher.suiteDone).toHaveBeenCalledWith({ my: 'result' }); expect(reportDispatcher.suiteDone).toHaveBeenCalledWith({ my: 'result' });
@@ -238,19 +236,14 @@ describe('Runner', function() {
queueableFns = runQueue.calls.mostRecent().args[0].queueableFns; queueableFns = runQueue.calls.mostRecent().args[0].queueableFns;
expect(queueableFns.length).toBe(2); expect(queueableFns.length).toBe(2);
parent.startedEvent.and.returnValue('parent suite started event');
queueableFns[0].fn(); queueableFns[0].fn();
expect(reportDispatcher.suiteStarted).toHaveBeenCalledWith( expect(reportDispatcher.suiteStarted).toHaveBeenCalledWith(parent.result);
'parent suite started event'
);
verifyAndFinishSpec(spec, queueableFns[1], true); verifyAndFinishSpec(spec, queueableFns[1], true);
parent.doneEvent.and.returnValue('parent suite done event'); parent.getResult.and.returnValue(parent.result);
runQueue.calls.argsFor(1)[0].onComplete(); runQueue.calls.argsFor(1)[0].onComplete();
expect(reportDispatcher.suiteDone).toHaveBeenCalledWith( expect(reportDispatcher.suiteDone).toHaveBeenCalledWith(parent.result);
'parent suite done event'
);
await expectAsync(promise).toBePending(); await expectAsync(promise).toBePending();
}); });
@@ -273,7 +266,7 @@ describe('Runner', function() {
queueableFns[1].fn('foo'); queueableFns[1].fn('foo');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec, 'foo'); ).toHaveBeenCalledWith(spec, 'foo');
await expectAsync(promise).toBePending(); await expectAsync(promise).toBePending();
@@ -369,16 +362,16 @@ describe('Runner', function() {
queueableFns[0].fn('done'); queueableFns[0].fn('done');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).not.toHaveBeenCalledWith(specs[0], jasmine.anything()); ).not.toHaveBeenCalledWith(specs[0], jasmine.anything());
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(specs[1], 'done'); ).toHaveBeenCalledWith(specs[1], 'done');
queueableFns[1].fn('done'); queueableFns[1].fn('done');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(specs[0], 'done'); ).toHaveBeenCalledWith(specs[0], 'done');
await expectAsync(promise).toBePending(); await expectAsync(promise).toBePending();
@@ -397,16 +390,16 @@ describe('Runner', function() {
queueableFns[0].fn('done'); queueableFns[0].fn('done');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).not.toHaveBeenCalledWith(nonSpecified, jasmine.anything()); ).not.toHaveBeenCalledWith(nonSpecified, jasmine.anything());
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(specified, 'done'); ).toHaveBeenCalledWith(specified, 'done');
queueableFns[1].fn('done'); queueableFns[1].fn('done');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(nonSpecified, 'done'); ).toHaveBeenCalledWith(nonSpecified, 'done');
await expectAsync(promise).toBePending(); await expectAsync(promise).toBePending();
@@ -431,12 +424,12 @@ describe('Runner', function() {
const nodeQueueableFns = runQueue.calls.mostRecent().args[0].queueableFns; const nodeQueueableFns = runQueue.calls.mostRecent().args[0].queueableFns;
nodeQueueableFns[1].fn('done'); nodeQueueableFns[1].fn('done');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(nonSpecifiedSpec, 'done'); ).toHaveBeenCalledWith(nonSpecifiedSpec, 'done');
queueableFns[1].fn('done'); queueableFns[1].fn('done');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(specifiedSpec, 'done'); ).toHaveBeenCalledWith(specifiedSpec, 'done');
await expectAsync(promise).toBePending(); await expectAsync(promise).toBePending();
@@ -458,7 +451,7 @@ describe('Runner', function() {
queueableFns[0].fn('done'); queueableFns[0].fn('done');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec1, 'done'); ).toHaveBeenCalledWith(spec1, 'done');
queueableFns[1].fn(); queueableFns[1].fn();
@@ -466,12 +459,143 @@ describe('Runner', function() {
expect(childFns.length).toBe(3); expect(childFns.length).toBe(3);
childFns[1].fn('done'); childFns[1].fn('done');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec2, 'done'); ).toHaveBeenCalledWith(spec2, 'done');
childFns[2].fn('done'); childFns[2].fn('done');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec3, 'done');
await expectAsync(promise).toBePending();
});
it('runs a suite multiple times if the order specified leaves and re-enters it', async function() {
const spec1 = new StubSpec();
const spec2 = new StubSpec();
const spec3 = new StubSpec();
const spec4 = new StubSpec();
const spec5 = new StubSpec();
const reentered = new StubSuite({ children: [spec1, spec2, spec3] });
const topSuite = new StubSuite({ children: [reentered, spec4, spec5] });
const subject = makeRunner(topSuite);
spyOn(jasmineUnderTest.getEnv(), 'deprecated');
const promise = subject.execute([
spec1.id,
spec4.id,
spec2.id,
spec5.id,
spec3.id
]);
await Promise.resolve();
expect(runQueue).toHaveBeenCalledTimes(1);
const queueableFns = runQueue.calls.mostRecent().args[0].queueableFns;
queueableFns[0].fn();
expect(runQueue.calls.mostRecent().args[0].queueableFns.length).toBe(2);
runQueue.calls.mostRecent().args[0].queueableFns[1].fn('done');
expect(
jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec1, 'done');
queueableFns[1].fn('done');
expect(
jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec4, 'done');
queueableFns[2].fn();
expect(runQueue.calls.count()).toBe(3);
expect(runQueue.calls.mostRecent().args[0].queueableFns.length).toBe(2);
runQueue.calls.mostRecent().args[0].queueableFns[1].fn('done');
expect(
jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec2, 'done');
queueableFns[3].fn('done');
expect(
jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec5, 'done');
queueableFns[4].fn();
expect(runQueue.calls.count()).toBe(4);
expect(runQueue.calls.mostRecent().args[0].queueableFns.length).toBe(2);
runQueue.calls.mostRecent().args[0].queueableFns[1].fn('done');
expect(
jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec3, 'done');
await expectAsync(promise).toBePending();
});
it('runs a parent of a suite with multiple segments correctly', async function() {
const spec1 = new StubSpec();
const spec2 = new StubSpec();
const spec3 = new StubSpec();
const spec4 = new StubSpec();
const spec5 = new StubSpec();
const parent = new StubSuite({ children: [spec1, spec2, spec3] });
const grandparent = new StubSuite({ children: [parent] });
const topSuite = new StubSuite({ children: [grandparent, spec4, spec5] });
const subject = makeRunner(topSuite);
spyOn(jasmineUnderTest.getEnv(), 'deprecated');
const promise = subject.execute([
spec1.id,
spec4.id,
spec2.id,
spec5.id,
spec3.id
]);
await Promise.resolve();
expect(runQueue).toHaveBeenCalledTimes(1);
const queueableFns = runQueue.calls.mostRecent().args[0].queueableFns;
expect(queueableFns.length).toBe(5);
queueableFns[0].fn();
expect(runQueue.calls.count()).toBe(2);
expect(runQueue.calls.mostRecent().args[0].queueableFns.length).toBe(2);
runQueue.calls.mostRecent().args[0].queueableFns[1].fn();
expect(runQueue.calls.count()).toBe(3);
runQueue.calls.mostRecent().args[0].queueableFns[1].fn('done');
expect(
jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec1, 'done');
queueableFns[1].fn('done');
expect(
jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec4, 'done');
queueableFns[2].fn();
expect(runQueue.calls.count()).toBe(4);
expect(runQueue.calls.mostRecent().args[0].queueableFns.length).toBe(2);
runQueue.calls.mostRecent().args[0].queueableFns[1].fn();
expect(runQueue.calls.count()).toBe(5);
runQueue.calls.mostRecent().args[0].queueableFns[1].fn('done');
expect(
jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec2, 'done');
queueableFns[3].fn('done');
expect(
jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec5, 'done');
queueableFns[4].fn();
expect(runQueue.calls.count()).toBe(6);
expect(runQueue.calls.mostRecent().args[0].queueableFns.length).toBe(2);
runQueue.calls.mostRecent().args[0].queueableFns[1].fn();
expect(runQueue.calls.count()).toBe(7);
runQueue.calls.mostRecent().args[0].queueableFns[1].fn('done');
expect(
jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(spec3, 'done'); ).toHaveBeenCalledWith(spec3, 'done');
await expectAsync(promise).toBePending(); await expectAsync(promise).toBePending();
@@ -496,7 +620,7 @@ describe('Runner', function() {
for (let i = 0; i < 11; i++) { for (let i = 0; i < 11; i++) {
queueableFns[i].fn('done'); queueableFns[i].fn('done');
expect( expect(
privateUnderTest.TreeRunner.prototype._executeSpec jasmineUnderTest.TreeRunner.prototype._executeSpec
).toHaveBeenCalledWith(specs[i], 'done'); ).toHaveBeenCalledWith(specs[i], 'done');
} }
@@ -2,7 +2,7 @@ describe('SkipAfterBeforeAllErrorPolicy', function() {
describe('#skipTo', function() { describe('#skipTo', function() {
describe('When nothing has errored', function() { describe('When nothing has errored', function() {
it('does not skip anything', function() { it('does not skip anything', function() {
const policy = new privateUnderTest.SkipAfterBeforeAllErrorPolicy( const policy = new jasmineUnderTest.SkipAfterBeforeAllErrorPolicy(
arrayOfArbitraryFns(4) arrayOfArbitraryFns(4)
); );
@@ -15,7 +15,7 @@ describe('SkipAfterBeforeAllErrorPolicy', function() {
describe('When anything but a beforeAll has errored', function() { describe('When anything but a beforeAll has errored', function() {
it('does not skip anything', function() { it('does not skip anything', function() {
const policy = new privateUnderTest.SkipAfterBeforeAllErrorPolicy( const policy = new jasmineUnderTest.SkipAfterBeforeAllErrorPolicy(
arrayOfArbitraryFns(4) arrayOfArbitraryFns(4)
); );
@@ -40,7 +40,7 @@ describe('SkipAfterBeforeAllErrorPolicy', function() {
{ type: 'afterAll', fn: () => {} }, { type: 'afterAll', fn: () => {} },
{ type: 'afterAll', fn: () => {} } { type: 'afterAll', fn: () => {} }
]; ];
const policy = new privateUnderTest.SkipAfterBeforeAllErrorPolicy(fns); const policy = new jasmineUnderTest.SkipAfterBeforeAllErrorPolicy(fns);
policy.fnErrored(0); policy.fnErrored(0);
expect(policy.skipTo(0)).toEqual(3); expect(policy.skipTo(0)).toEqual(3);
@@ -54,7 +54,7 @@ describe('SkipAfterBeforeAllErrorPolicy', function() {
it("sets the suite's hadBeforeAllFailure property to true", function() { it("sets the suite's hadBeforeAllFailure property to true", function() {
const suite = {}; const suite = {};
const fns = [{ type: 'beforeAll', fn: () => {}, suite }]; const fns = [{ type: 'beforeAll', fn: () => {}, suite }];
const policy = new privateUnderTest.SkipAfterBeforeAllErrorPolicy(fns); const policy = new jasmineUnderTest.SkipAfterBeforeAllErrorPolicy(fns);
policy.fnErrored(0); policy.fnErrored(0);
@@ -65,7 +65,7 @@ describe('SkipAfterBeforeAllErrorPolicy', function() {
describe('When the fn is not a beforeAll', function() { describe('When the fn is not a beforeAll', function() {
it('does not try to access the suite, which is probably not there', function() { it('does not try to access the suite, which is probably not there', function() {
const fns = [{ fn: () => {} /* no suite */ }]; const fns = [{ fn: () => {} /* no suite */ }];
const policy = new privateUnderTest.SkipAfterBeforeAllErrorPolicy(fns); const policy = new jasmineUnderTest.SkipAfterBeforeAllErrorPolicy(fns);
expect(() => policy.fnErrored(0)).not.toThrow(); expect(() => policy.fnErrored(0)).not.toThrow();
}); });
+60 -408
View File
@@ -1,24 +1,24 @@
describe('Spec', function() { describe('Spec', function() {
it('#isPendingSpecException returns true for a pending spec exception', function() { it('#isPendingSpecException returns true for a pending spec exception', function() {
const e = new Error(privateUnderTest.Spec.pendingSpecExceptionMessage); const e = new Error(jasmineUnderTest.Spec.pendingSpecExceptionMessage);
expect(privateUnderTest.Spec.isPendingSpecException(e)).toBe(true); expect(jasmineUnderTest.Spec.isPendingSpecException(e)).toBe(true);
}); });
it('#isPendingSpecException returns true for a pending spec exception (even when FF bug is present)', function() { it('#isPendingSpecException returns true for a pending spec exception (even when FF bug is present)', function() {
const fakeError = { const fakeError = {
toString: function() { toString: function() {
return 'Error: ' + privateUnderTest.Spec.pendingSpecExceptionMessage; return 'Error: ' + jasmineUnderTest.Spec.pendingSpecExceptionMessage;
} }
}; };
expect(privateUnderTest.Spec.isPendingSpecException(fakeError)).toBe(true); expect(jasmineUnderTest.Spec.isPendingSpecException(fakeError)).toBe(true);
}); });
it('#isPendingSpecException returns true for a pending spec exception with a custom message', function() { it('#isPendingSpecException returns true for a pending spec exception with a custom message', function() {
expect( expect(
privateUnderTest.Spec.isPendingSpecException( jasmineUnderTest.Spec.isPendingSpecException(
privateUnderTest.Spec.pendingSpecExceptionMessage + 'foo' jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'foo'
) )
).toBe(true); ).toBe(true);
}); });
@@ -26,16 +26,16 @@ describe('Spec', function() {
it('#isPendingSpecException returns false for not a pending spec exception', function() { it('#isPendingSpecException returns false for not a pending spec exception', function() {
const e = new Error('foo'); const e = new Error('foo');
expect(privateUnderTest.Spec.isPendingSpecException(e)).toBe(false); expect(jasmineUnderTest.Spec.isPendingSpecException(e)).toBe(false);
}); });
it("#isPendingSpecException returns false for thrown values that don't have toString", function() { it("#isPendingSpecException returns false for thrown values that don't have toString", function() {
expect(privateUnderTest.Spec.isPendingSpecException(void 0)).toBe(false); expect(jasmineUnderTest.Spec.isPendingSpecException(void 0)).toBe(false);
}); });
describe('#executionFinished', function() { describe('#executionFinished', function() {
it('removes the fn if autoCleanClosures is true', function() { it('removes the fn if autoCleanClosures is true', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} }, queueableFn: { fn: () => {} },
autoCleanClosures: true autoCleanClosures: true
}); });
@@ -45,7 +45,7 @@ describe('Spec', function() {
}); });
it('removes the fn after execution if autoCleanClosures is undefined', function() { it('removes the fn after execution if autoCleanClosures is undefined', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} }, queueableFn: { fn: () => {} },
autoCleanClosures: undefined autoCleanClosures: undefined
}); });
@@ -56,7 +56,7 @@ describe('Spec', function() {
it('does not remove the fn after execution if autoCleanClosures is false', function() { it('does not remove the fn after execution if autoCleanClosures is false', function() {
function originalFn() {} function originalFn() {}
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: originalFn }, queueableFn: { fn: originalFn },
autoCleanClosures: false autoCleanClosures: false
}); });
@@ -68,7 +68,7 @@ describe('Spec', function() {
describe('#getSpecProperty', function() { describe('#getSpecProperty', function() {
it('get the property value', function() { it('get the property value', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} } queueableFn: { fn: () => {} }
}); });
@@ -79,17 +79,17 @@ describe('Spec', function() {
describe('#setSpecProperty', function() { describe('#setSpecProperty', function() {
it('adds the property to the result', function() { it('adds the property to the result', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} } queueableFn: { fn: () => {} }
}); });
spec.setSpecProperty('a', 4); spec.setSpecProperty('a', 4);
expect(spec.doneEvent().properties).toEqual({ a: 4 }); expect(spec.result.properties).toEqual({ a: 4 });
}); });
it('replace the property result when it was previously set', function() { it('replace the property result when it was previously set', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} } queueableFn: { fn: () => {} }
}); });
@@ -97,180 +97,75 @@ describe('Spec', function() {
spec.setSpecProperty('b', 'original-value'); spec.setSpecProperty('b', 'original-value');
spec.setSpecProperty('a', 'new-value'); spec.setSpecProperty('a', 'new-value');
expect(spec.doneEvent().properties).toEqual({ expect(spec.result.properties).toEqual({
a: 'new-value', a: 'new-value',
b: 'original-value' b: 'original-value'
}); });
}); });
it('throws if the key is not a string', function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
expect(function() {
spec.setSpecProperty({}, '');
}).toThrowError('Key must be a string');
});
it('throws if the value is not structured-cloneable', function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
expect(function() {
spec.setSpecProperty('k', new Promise(() => {}));
}).toThrowError("Value can't be cloned");
});
it('throws if the value is not JSON-serializable', function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
expect(function() {
const v = {};
v.self = v;
spec.setSpecProperty('k', v);
}).toThrowError("Value can't be cloned");
});
}); });
describe('status', function() { describe('status', function() {
it('returns "passed" by default', function() { it('is "passed" by default', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} } queueableFn: { fn: () => {} }
}); });
expect(spec.status()) expect(spec.getResult().status).toBe('passed');
.withContext('status()')
.toBe('passed');
expect(spec.doneEvent().status)
.withContext('doneEvent().status')
.toBe('passed');
}); });
it('is "passed" if all expectations passed', function() { it('is "passed" if all expectations passed', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} } queueableFn: { fn: () => {} }
}); });
spec.addExpectationResult(true, {}); spec.addExpectationResult(true, {});
expect(spec.status()) expect(spec.getResult().status).toBe('passed');
.withContext('status()')
.toBe('passed');
expect(spec.doneEvent().status)
.withContext('doneEvent().status')
.toBe('passed');
}); });
it('is "failed" if any expectation failed', function() { it('is "failed" if any expectation failed', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} } queueableFn: { fn: () => {} }
}); });
spec.addExpectationResult(true, {}); spec.addExpectationResult(true, {});
spec.addExpectationResult(false, {}); spec.addExpectationResult(false, {});
expect(spec.status()) expect(spec.getResult().status).toBe('failed');
.withContext('status()')
.toBe('failed');
expect(spec.doneEvent().status)
.withContext('doneEvent().status')
.toBe('failed');
}); });
it('is "pending" if created without a function body', function() { it('is "pending" if created without a function body', function() {
const startCallback = jasmine.createSpy('startCallback'), const startCallback = jasmine.createSpy('startCallback'),
resultCallback = jasmine.createSpy('resultCallback'), resultCallback = jasmine.createSpy('resultCallback'),
spec = new privateUnderTest.Spec({ spec = new jasmineUnderTest.Spec({
onStart: startCallback, onStart: startCallback,
queueableFn: { fn: null }, queueableFn: { fn: null },
resultCallback: resultCallback resultCallback: resultCallback
}); });
expect(spec.status()) expect(spec.getResult().status).toBe('pending');
.withContext('status()')
.toBe('pending');
expect(spec.doneEvent().status)
.withContext('doneEvent().status')
.toBe('pending');
});
describe('after a call to executionFinished()', function() {
describe('with excluded true', function() {
it("is 'excluded'", function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
spec.executionFinished(true, false);
expect(spec.status())
.withContext('status()')
.toBe('excluded');
expect(spec.doneEvent().status)
.withContext('doneEvent().status')
.toBe('excluded');
});
});
describe('with failSpecWithNoExp true', function() {
it("is 'failed' if there were no expectations", function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
spec.executionFinished(false, true);
expect(spec.status())
.withContext('status()')
.toBe('failed');
expect(spec.doneEvent().status)
.withContext('doneEvent().status')
.toBe('failed');
});
});
});
describe('after a call to hadBeforeAllFailure()', function() {
it("is 'failed'", function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
spec.hadBeforeAllFailure();
expect(spec.status())
.withContext('status()')
.toBe('failed');
expect(spec.doneEvent().status)
.withContext('doneEvent().status')
.toBe('failed');
});
}); });
}); });
describe('#addExpectationResult', function() { describe('#addExpectationResult', function() {
it('keeps track of passed and failed expectations', function() { it('keeps track of passed and failed expectations', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} } queueableFn: { fn: () => {} }
}); });
spec.addExpectationResult(true, { message: 'expectation1' }); spec.addExpectationResult(true, { message: 'expectation1' });
spec.addExpectationResult(false, { message: 'expectation2' }); spec.addExpectationResult(false, { message: 'expectation2' });
expect(spec.doneEvent().passedExpectations).toEqual([ expect(spec.result.passedExpectations).toEqual([
jasmine.objectContaining({ message: 'expectation1' }) jasmine.objectContaining({ message: 'expectation1' })
]); ]);
expect(spec.doneEvent().failedExpectations).toEqual([ expect(spec.result.failedExpectations).toEqual([
jasmine.objectContaining({ message: 'expectation2' }) jasmine.objectContaining({ message: 'expectation2' })
]); ]);
}); });
describe("when 'throwOnExpectationFailure' is set", function() { describe("when 'throwOnExpectationFailure' is set", function() {
it('throws an ExpectationFailed error', function() { it('throws an ExpectationFailed error', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} }, queueableFn: { fn: () => {} },
throwOnExpectationFailure: true throwOnExpectationFailure: true
}); });
@@ -278,9 +173,9 @@ describe('Spec', function() {
spec.addExpectationResult(true, { message: 'passed' }); spec.addExpectationResult(true, { message: 'passed' });
expect(function() { expect(function() {
spec.addExpectationResult(false, { message: 'failed' }); spec.addExpectationResult(false, { message: 'failed' });
}).toThrowError(jasmineUnderTest.private.errors.ExpectationFailed); }).toThrowError(jasmineUnderTest.errors.ExpectationFailed);
expect(spec.doneEvent().failedExpectations).toEqual([ expect(spec.result.failedExpectations).toEqual([
jasmine.objectContaining({ message: 'failed' }) jasmine.objectContaining({ message: 'failed' })
]); ]);
}); });
@@ -288,13 +183,13 @@ describe('Spec', function() {
describe("when 'throwOnExpectationFailure' is not set", function() { describe("when 'throwOnExpectationFailure' is not set", function() {
it('does not throw', function() { it('does not throw', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} } queueableFn: { fn: () => {} }
}); });
spec.addExpectationResult(false, { message: 'failed' }); spec.addExpectationResult(false, { message: 'failed' });
expect(spec.doneEvent().failedExpectations).toEqual([ expect(spec.result.failedExpectations).toEqual([
jasmine.objectContaining({ message: 'failed' }) jasmine.objectContaining({ message: 'failed' })
]); ]);
}); });
@@ -303,7 +198,7 @@ describe('Spec', function() {
it('forwards late expectation failures to onLateError', function() { it('forwards late expectation failures to onLateError', function() {
const onLateError = jasmine.createSpy('onLateError'); const onLateError = jasmine.createSpy('onLateError');
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
onLateError, onLateError,
queueableFn: { fn: function() {} } queueableFn: { fn: function() {} }
}); });
@@ -323,12 +218,12 @@ describe('Spec', function() {
message: jasmine.stringMatching(/^Error: nope/) message: jasmine.stringMatching(/^Error: nope/)
}) })
); );
expect(spec.doneEvent().failedExpectations).toEqual([]); expect(spec.result.failedExpectations).toEqual([]);
}); });
it('does not forward non-late expectation failures to onLateError', function() { it('does not forward non-late expectation failures to onLateError', function() {
const onLateError = jasmine.createSpy('onLateError'); const onLateError = jasmine.createSpy('onLateError');
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
onLateError, onLateError,
queueableFn: { fn: function() {} } queueableFn: { fn: function() {} }
}); });
@@ -347,7 +242,7 @@ describe('Spec', function() {
it('forwards late handleException calls to onLateError', function() { it('forwards late handleException calls to onLateError', function() {
const onLateError = jasmine.createSpy('onLateError'); const onLateError = jasmine.createSpy('onLateError');
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
onLateError, onLateError,
queueableFn: { fn: function() {} } queueableFn: { fn: function() {} }
}); });
@@ -360,12 +255,12 @@ describe('Spec', function() {
message: jasmine.stringMatching(/^Error: oops/) message: jasmine.stringMatching(/^Error: oops/)
}) })
); );
expect(spec.doneEvent().failedExpectations).toEqual([]); expect(spec.result.failedExpectations).toEqual([]);
}); });
it('does not forward non-late handleException calls to onLateError', function() { it('does not forward non-late handleException calls to onLateError', function() {
const onLateError = jasmine.createSpy('onLateError'); const onLateError = jasmine.createSpy('onLateError');
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
onLateError, onLateError,
queueableFn: { fn: function() {} } queueableFn: { fn: function() {} }
}); });
@@ -374,11 +269,11 @@ describe('Spec', function() {
spec.handleException(error); spec.handleException(error);
expect(onLateError).not.toHaveBeenCalled(); expect(onLateError).not.toHaveBeenCalled();
expect(spec.doneEvent().failedExpectations.length).toEqual(1); expect(spec.result.failedExpectations.length).toEqual(1);
}); });
it('clears the reportedDone flag when reset', function() { it('clears the reportedDone flag when reset', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: function() {} } queueableFn: { fn: function() {} }
}); });
spec.reportedDone = true; spec.reportedDone = true;
@@ -390,7 +285,7 @@ describe('Spec', function() {
it('does not throw an ExpectationFailed error when handling an error', function() { it('does not throw an ExpectationFailed error when handling an error', function() {
const resultCallback = jasmine.createSpy('resultCallback'), const resultCallback = jasmine.createSpy('resultCallback'),
spec = new privateUnderTest.Spec({ spec = new jasmineUnderTest.Spec({
queueableFn: { fn: function() {} }, queueableFn: { fn: function() {} },
resultCallback: resultCallback, resultCallback: resultCallback,
throwOnExpectationFailure: true throwOnExpectationFailure: true
@@ -404,7 +299,7 @@ describe('Spec', function() {
.createSpy('getPath') .createSpy('getPath')
.and.returnValue(['expected', 'val']); .and.returnValue(['expected', 'val']);
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
getPath, getPath,
queueableFn: { fn: null } queueableFn: { fn: null }
}); });
@@ -418,7 +313,7 @@ describe('Spec', function() {
.createSpy('getPath') .createSpy('getPath')
.and.returnValue(['expected val']); .and.returnValue(['expected val']);
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
getPath, getPath,
queueableFn: { fn: null } queueableFn: { fn: null }
}); });
@@ -431,55 +326,54 @@ describe('Spec', function() {
describe('#handleException', function() { describe('#handleException', function() {
it('records a failure', function() { it('records a failure', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: {} queueableFn: {}
}); });
spec.handleException('foo'); spec.handleException('foo');
expect(spec.doneEvent().failedExpectations).toEqual([ expect(spec.result.failedExpectations).toEqual([
{ {
message: 'foo thrown', message: 'foo thrown',
matcherName: '', matcherName: '',
passed: false, passed: false,
stack: null, expected: '',
globalErrorType: undefined actual: '',
stack: null
} }
]); ]);
}); });
it('does not record an additional failure when the error is ExpectationFailed', function() { it('does not record an additional failure when the error is ExpectationFailed', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: {} queueableFn: {}
}); });
spec.handleException( spec.handleException(new jasmineUnderTest.errors.ExpectationFailed());
new jasmineUnderTest.private.errors.ExpectationFailed()
);
expect(spec.doneEvent().failedExpectations).toEqual([]); expect(spec.result.failedExpectations).toEqual([]);
}); });
}); });
describe('#debugLog', function() { describe('#debugLog', function() {
it('adds the messages to the result', function() { it('adds the messages to the result', function() {
const timer = jasmine.createSpyObj('timer', ['start', 'elapsed']); const timer = jasmine.createSpyObj('timer', ['start', 'elapsed']);
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} }, queueableFn: { fn: () => {} },
timer: timer timer: timer
}); });
const t1 = 123; const t1 = 123;
const t2 = 456; const t2 = 456;
expect(spec.doneEvent().debugLogs).toBeNull(); expect(spec.result.debugLogs).toBeNull();
timer.elapsed.and.returnValue(t1); timer.elapsed.and.returnValue(t1);
spec.debugLog('msg 1'); spec.debugLog('msg 1');
expect(spec.doneEvent().debugLogs).toEqual([ expect(spec.result.debugLogs).toEqual([
{ message: 'msg 1', timestamp: t1 } { message: 'msg 1', timestamp: t1 }
]); ]);
timer.elapsed.and.returnValue(t2); timer.elapsed.and.returnValue(t2);
spec.debugLog('msg 2'); spec.debugLog('msg 2');
expect(spec.doneEvent().debugLogs).toEqual([ expect(spec.result.debugLogs).toEqual([
{ message: 'msg 1', timestamp: t1 }, { message: 'msg 1', timestamp: t1 },
{ message: 'msg 2', timestamp: t2 } { message: 'msg 2', timestamp: t2 }
]); ]);
@@ -487,21 +381,21 @@ describe('Spec', function() {
describe('When the spec passes', function() { describe('When the spec passes', function() {
it('removes the logs from the result', function() { it('removes the logs from the result', function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} } queueableFn: { fn: () => {} }
}); });
spec.debugLog('msg'); spec.debugLog('msg');
spec.executionFinished(); spec.executionFinished();
expect(spec.doneEvent().debugLogs).toBeNull(); expect(spec.result.debugLogs).toBeNull();
}); });
}); });
describe('When the spec fails', function() { describe('When the spec fails', function() {
it('includes the messages in the result', function() { it('includes the messages in the result', function() {
const timer = jasmine.createSpyObj('timer', ['start', 'elapsed']); const timer = jasmine.createSpyObj('timer', ['start', 'elapsed']);
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn: () => {} }, queueableFn: { fn: () => {} },
timer: timer timer: timer
}); });
@@ -513,252 +407,10 @@ describe('Spec', function() {
spec.handleException(new Error('nope')); spec.handleException(new Error('nope'));
spec.executionFinished(); spec.executionFinished();
expect(spec.doneEvent().debugLogs).toEqual([ expect(spec.result.debugLogs).toEqual([
{ message: 'msg', timestamp: timestamp } { message: 'msg', timestamp: timestamp }
]); ]);
}); });
}); });
}); });
describe('#startedEvent', function() {
it('includes only properties that are known before execution', function() {
const spec = new privateUnderTest.Spec({
id: 'spec1',
parentSuiteId: 'suite1',
description: 'a spec',
filename: 'somefile.js',
getPath() {
return ['a suite', 'a spec'];
},
queueableFn: { fn: () => {} }
});
expect(spec.startedEvent()).toEqual({
id: 'spec1',
parentSuiteId: 'suite1',
description: 'a spec',
fullName: 'a suite a spec',
filename: 'somefile.js'
});
});
});
describe('#doneEvent', function() {
it('returns the event for a passed spec', function() {
const timer = {
start() {},
elapsed() {
return 123;
}
};
const spec = new privateUnderTest.Spec({
id: 'spec1',
parentSuiteId: 'suite1',
description: 'a spec',
filename: 'somefile.js',
getPath() {
return ['a suite', 'a spec'];
},
queueableFn: { fn: () => {} },
timer: timer
});
spec.addExpectationResult(true, {
matcherName: 'a passing expectation',
passed: true
});
spec.executionFinished(false, false);
expect(spec.doneEvent()).toEqual({
id: 'spec1',
parentSuiteId: 'suite1',
description: 'a spec',
fullName: 'a suite a spec',
filename: 'somefile.js',
status: 'passed',
passedExpectations: [
{
matcherName: 'a passing expectation',
passed: true,
message: 'Passed.',
stack: '',
globalErrorType: undefined
}
],
failedExpectations: [],
deprecationWarnings: [],
debugLogs: null, // TODO change to []
properties: null, // TODO change to {}
pendingReason: '',
duration: 123
});
});
it('returns the event for a failed spec', function() {
const timer = {
start() {},
elapsed() {
return 123;
}
};
const spec = new privateUnderTest.Spec({
id: 'spec1',
parentSuiteId: 'suite1',
description: 'a spec',
filename: 'somefile.js',
getPath() {
return ['a suite', 'a spec'];
},
queueableFn: { fn: () => {} },
timer: timer
});
spec.addExpectationResult(true, {
matcherName: 'a passing expectation',
passed: true
});
spec.addExpectationResult(false, {
matcherName: 'a failing expectation',
passed: false,
error: new Error('failed')
});
spec.executionFinished(false, false);
expect(spec.doneEvent()).toEqual({
id: 'spec1',
parentSuiteId: 'suite1',
description: 'a spec',
fullName: 'a suite a spec',
filename: 'somefile.js',
status: 'failed',
passedExpectations: [
{
matcherName: 'a passing expectation',
passed: true,
message: 'Passed.',
stack: '',
globalErrorType: undefined
}
],
failedExpectations: [
{
matcherName: 'a failing expectation',
passed: false,
message: jasmine.stringMatching(/^Error: failed/),
stack: jasmine.stringContaining('SpecSpec.js'),
globalErrorType: undefined
}
],
deprecationWarnings: [],
debugLogs: null, // TODO change to []
properties: null, // TODO change to {}
pendingReason: '',
duration: 123
});
});
it("reports a status of 'pending' for a declaratively pended spec", function() {
const spec = new privateUnderTest.Spec({
queueableFn: {}
});
spec.executionFinished(false, false);
const result = spec.doneEvent();
expect(result.status).toEqual('pending');
expect(result.pendingReason).toEqual('');
});
it("reports a status of 'pending' for a spec pended by #pend", function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
spec.pend('nope');
spec.executionFinished(false, false);
const result = spec.doneEvent();
expect(result.status).toEqual('pending');
expect(result.pendingReason).toEqual('nope');
});
it("reports a status of 'excluded' for an excluded spec", function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
spec.executionFinished(true, false);
expect(spec.doneEvent().status).toEqual('excluded');
});
describe('When failSpecWithNoExpectations is true', function() {
it("reports a status of 'failed' for a spec with no expectations", function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
spec.executionFinished(false, true);
expect(spec.doneEvent().status).toEqual('failed');
});
});
it('includes deprecation warnings', function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
spec.addDeprecationWarning('stop that');
expect(spec.doneEvent().deprecationWarnings).toEqual([
{
// TODO: remove irrelevant properties
message: 'stop that',
stack: jasmine.stringContaining('SpecSpec.js'),
matcherName: undefined,
passed: undefined,
globalErrorType: undefined
}
]);
});
it('includes debug logs', function() {
const timer = {
start() {},
elapsed() {
return 123;
}
};
const spec = new privateUnderTest.Spec({
timer,
queueableFn: { fn: () => {} }
});
spec.debugLog('maybe this will help');
expect(spec.doneEvent().debugLogs).toEqual([
{
message: 'maybe this will help',
timestamp: 123
}
]);
});
it('includes spec properties', function() {
const spec = new privateUnderTest.Spec({
queueableFn: { fn: () => {} }
});
spec.setSpecProperty('foo', 'bar');
spec.setSpecProperty('baz', { grault: ['wombat'] });
expect(spec.doneEvent().properties).toEqual({
foo: 'bar',
baz: { grault: ['wombat'] }
});
});
// it("excludes properties that aren't in the public API");
});
}); });
+174 -186
View File
@@ -1,11 +1,11 @@
describe('SpyRegistry', function() { describe('SpyRegistry', function() {
function createSpy(name, originalFn) { function createSpy(name, originalFn) {
return privateUnderTest.Spy(name, originalFn); return jasmineUnderTest.Spy(name, originalFn);
} }
describe('#spyOn', function() { describe('#spyOn', function() {
it('checks for the existence of the object', function() { it('checks for the existence of the object', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy createSpy: createSpy
}); });
expect(function() { expect(function() {
@@ -14,53 +14,53 @@ describe('SpyRegistry', function() {
}); });
it('checks that a method name was passed', function() { it('checks that a method name was passed', function() {
const spyRegistry = new privateUnderTest.SpyRegistry(), const spyRegistry = new jasmineUnderTest.SpyRegistry(),
target = {}; subject = {};
expect(function() { expect(function() {
spyRegistry.spyOn(target); spyRegistry.spyOn(subject);
}).toThrowError(/No method name supplied/); }).toThrowError(/No method name supplied/);
}); });
it('checks that the object is not `null`', function() { it('checks that the object is not `null`', function() {
const spyRegistry = new privateUnderTest.SpyRegistry(); const spyRegistry = new jasmineUnderTest.SpyRegistry();
expect(function() { expect(function() {
spyRegistry.spyOn(null, 'pants'); spyRegistry.spyOn(null, 'pants');
}).toThrowError(/could not find an object/); }).toThrowError(/could not find an object/);
}); });
it('checks that the method name is not `null`', function() { it('checks that the method name is not `null`', function() {
const spyRegistry = new privateUnderTest.SpyRegistry(), const spyRegistry = new jasmineUnderTest.SpyRegistry(),
target = {}; subject = {};
expect(function() { expect(function() {
spyRegistry.spyOn(target, null); spyRegistry.spyOn(subject, null);
}).toThrowError(/No method name supplied/); }).toThrowError(/No method name supplied/);
}); });
it('checks for the existence of the method', function() { it('checks for the existence of the method', function() {
const spyRegistry = new privateUnderTest.SpyRegistry(), const spyRegistry = new jasmineUnderTest.SpyRegistry(),
target = {}; subject = {};
expect(function() { expect(function() {
spyRegistry.spyOn(target, 'pants'); spyRegistry.spyOn(subject, 'pants');
}).toThrowError(/method does not exist/); }).toThrowError(/method does not exist/);
}); });
it('checks if it has already been spied upon', function() { it('checks if it has already been spied upon', function() {
const spies = [], const spies = [],
spyRegistry = new privateUnderTest.SpyRegistry({ spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return spies; return spies;
}, },
createSpy: createSpy createSpy: createSpy
}), }),
target = { spiedFunc: function() {} }; subject = { spiedFunc: function() {} };
spyRegistry.spyOn(target, 'spiedFunc'); spyRegistry.spyOn(subject, 'spiedFunc');
expect(function() { expect(function() {
spyRegistry.spyOn(target, 'spiedFunc'); spyRegistry.spyOn(subject, 'spiedFunc');
}).toThrowError(/has already been spied upon/); }).toThrowError(/has already been spied upon/);
}); });
@@ -78,19 +78,19 @@ describe('SpyRegistry', function() {
}); });
const spies = [], const spies = [],
spyRegistry = new privateUnderTest.SpyRegistry({ spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return spies; return spies;
} }
}), }),
target = { spiedFunc: scope.myFunc }; subject = { spiedFunc: scope.myFunc };
expect(function() { expect(function() {
spyRegistry.spyOn(scope, 'myFunc'); spyRegistry.spyOn(scope, 'myFunc');
}).toThrowError(/is not declared writable or has no setter/); }).toThrowError(/is not declared writable or has no setter/);
expect(function() { expect(function() {
spyRegistry.spyOn(target, 'spiedFunc'); spyRegistry.spyOn(subject, 'spiedFunc');
}).not.toThrowError(/is not declared writable or has no setter/); }).not.toThrowError(/is not declared writable or has no setter/);
}); });
@@ -108,7 +108,7 @@ describe('SpyRegistry', function() {
set() {} set() {}
}); });
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy createSpy: createSpy
}); });
expect(function() { expect(function() {
@@ -119,67 +119,55 @@ describe('SpyRegistry', function() {
}); });
it('overrides the method on the object and returns the spy', function() { it('overrides the method on the object and returns the spy', function() {
let originalFunctionWasCalled = false; const originalFunctionWasCalled = false,
const spyRegistry = new privateUnderTest.SpyRegistry({ spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy createSpy: createSpy
}); }),
const target = { subject = {
spiedFunc: function() { spiedFunc: function() {
originalFunctionWasCalled = true; originalFunctionWasCalled = true;
} }
}; };
const spy = spyRegistry.spyOn(target, 'spiedFunc'); const spy = spyRegistry.spyOn(subject, 'spiedFunc');
expect(target.spiedFunc).toEqual(spy); expect(subject.spiedFunc).toEqual(spy);
target.spiedFunc(); subject.spiedFunc();
expect(originalFunctionWasCalled).toBe(false); expect(originalFunctionWasCalled).toBe(false);
}); });
it('throws if the method is a mock clock method', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({
createSpy: createSpy
});
const target = { spiedFunc: function() {} };
target.spiedFunc[privateUnderTest.Clock.IsMockClockTimingFn] = true;
expect(function() {
spyRegistry.spyOn(target, 'spiedFunc');
}).toThrowError("Mock clock timing functions can't be spied on");
});
}); });
describe('#spyOnProperty', function() { describe('#spyOnProperty', function() {
it('checks for the existence of the object', function() { it('checks for the existence of the object', function() {
const spyRegistry = new privateUnderTest.SpyRegistry(); const spyRegistry = new jasmineUnderTest.SpyRegistry();
expect(function() { expect(function() {
spyRegistry.spyOnProperty(void 0, 'pants'); spyRegistry.spyOnProperty(void 0, 'pants');
}).toThrowError(/could not find an object/); }).toThrowError(/could not find an object/);
}); });
it('checks that a property name was passed', function() { it('checks that a property name was passed', function() {
const spyRegistry = new privateUnderTest.SpyRegistry(), const spyRegistry = new jasmineUnderTest.SpyRegistry(),
target = {}; subject = {};
expect(function() { expect(function() {
spyRegistry.spyOnProperty(target); spyRegistry.spyOnProperty(subject);
}).toThrowError(/No property name supplied/); }).toThrowError(/No property name supplied/);
}); });
it('checks for the existence of the method', function() { it('checks for the existence of the method', function() {
const spyRegistry = new privateUnderTest.SpyRegistry(), const spyRegistry = new jasmineUnderTest.SpyRegistry(),
target = {}; subject = {};
expect(function() { expect(function() {
spyRegistry.spyOnProperty(target, 'pants'); spyRegistry.spyOnProperty(subject, 'pants');
}).toThrowError(/property does not exist/); }).toThrowError(/property does not exist/);
}); });
it('checks for the existence of access type', function() { it('checks for the existence of access type', function() {
const spyRegistry = new privateUnderTest.SpyRegistry(), const spyRegistry = new jasmineUnderTest.SpyRegistry(),
target = {}; subject = {};
Object.defineProperty(target, 'pants', { Object.defineProperty(subject, 'pants', {
get: function() { get: function() {
return 1; return 1;
}, },
@@ -187,65 +175,65 @@ describe('SpyRegistry', function() {
}); });
expect(function() { expect(function() {
spyRegistry.spyOnProperty(target, 'pants', 'set'); spyRegistry.spyOnProperty(subject, 'pants', 'set');
}).toThrowError(/does not have access type/); }).toThrowError(/does not have access type/);
}); });
it('checks if it can be spied upon', function() { it('checks if it can be spied upon', function() {
const target = {}; const subject = {};
Object.defineProperty(target, 'myProp', { Object.defineProperty(subject, 'myProp', {
get: function() {} get: function() {}
}); });
Object.defineProperty(target, 'spiedProp', { Object.defineProperty(subject, 'spiedProp', {
get: function() {}, get: function() {},
configurable: true configurable: true
}); });
const spyRegistry = new privateUnderTest.SpyRegistry(); const spyRegistry = new jasmineUnderTest.SpyRegistry();
expect(function() { expect(function() {
spyRegistry.spyOnProperty(target, 'myProp'); spyRegistry.spyOnProperty(subject, 'myProp');
}).toThrowError(/is not declared configurable/); }).toThrowError(/is not declared configurable/);
expect(function() { expect(function() {
spyRegistry.spyOnProperty(target, 'spiedProp'); spyRegistry.spyOnProperty(subject, 'spiedProp');
}).not.toThrowError(/is not declared configurable/); }).not.toThrowError(/is not declared configurable/);
}); });
it('overrides the property getter on the object and returns the spy', function() { it('overrides the property getter on the object and returns the spy', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy createSpy: createSpy
}), }),
target = {}, subject = {},
returnValue = 1; returnValue = 1;
Object.defineProperty(target, 'spiedProperty', { Object.defineProperty(subject, 'spiedProperty', {
get: function() { get: function() {
return returnValue; return returnValue;
}, },
configurable: true configurable: true
}); });
expect(target.spiedProperty).toEqual(returnValue); expect(subject.spiedProperty).toEqual(returnValue);
const spy = spyRegistry.spyOnProperty(target, 'spiedProperty'); const spy = spyRegistry.spyOnProperty(subject, 'spiedProperty');
const getter = Object.getOwnPropertyDescriptor(target, 'spiedProperty') const getter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty')
.get; .get;
expect(getter).toEqual(spy); expect(getter).toEqual(spy);
expect(target.spiedProperty).toBeUndefined(); expect(subject.spiedProperty).toBeUndefined();
}); });
it('overrides the property setter on the object and returns the spy', function() { it('overrides the property setter on the object and returns the spy', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy createSpy: createSpy
}), }),
target = {}, subject = {},
returnValue = 1; returnValue = 1;
Object.defineProperty(target, 'spiedProperty', { Object.defineProperty(subject, 'spiedProperty', {
get: function() { get: function() {
return returnValue; return returnValue;
}, },
@@ -253,53 +241,53 @@ describe('SpyRegistry', function() {
configurable: true configurable: true
}); });
const spy = spyRegistry.spyOnProperty(target, 'spiedProperty', 'set'); const spy = spyRegistry.spyOnProperty(subject, 'spiedProperty', 'set');
const setter = Object.getOwnPropertyDescriptor(target, 'spiedProperty') const setter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty')
.set; .set;
expect(target.spiedProperty).toEqual(returnValue); expect(subject.spiedProperty).toEqual(returnValue);
expect(setter).toEqual(spy); expect(setter).toEqual(spy);
}); });
describe('when the property is already spied upon', function() { describe('when the property is already spied upon', function() {
it('throws an error if respy is not allowed', function() { it('throws an error if respy is not allowed', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy createSpy: createSpy
}), }),
target = {}; subject = {};
Object.defineProperty(target, 'spiedProp', { Object.defineProperty(subject, 'spiedProp', {
get: function() { get: function() {
return 1; return 1;
}, },
configurable: true configurable: true
}); });
spyRegistry.spyOnProperty(target, 'spiedProp'); spyRegistry.spyOnProperty(subject, 'spiedProp');
expect(function() { expect(function() {
spyRegistry.spyOnProperty(target, 'spiedProp'); spyRegistry.spyOnProperty(subject, 'spiedProp');
}).toThrowError(/spiedProp#get has already been spied upon/); }).toThrowError(/spiedProp#get has already been spied upon/);
}); });
it('returns the original spy if respy is allowed', function() { it('returns the original spy if respy is allowed', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy createSpy: createSpy
}), }),
target = {}; subject = {};
spyRegistry.allowRespy(true); spyRegistry.allowRespy(true);
Object.defineProperty(target, 'spiedProp', { Object.defineProperty(subject, 'spiedProp', {
get: function() { get: function() {
return 1; return 1;
}, },
configurable: true configurable: true
}); });
const originalSpy = spyRegistry.spyOnProperty(target, 'spiedProp'); const originalSpy = spyRegistry.spyOnProperty(subject, 'spiedProp');
expect(spyRegistry.spyOnProperty(target, 'spiedProp')).toBe( expect(spyRegistry.spyOnProperty(subject, 'spiedProp')).toBe(
originalSpy originalSpy
); );
}); });
@@ -308,14 +296,14 @@ describe('SpyRegistry', function() {
describe('#spyOnAllFunctions', function() { describe('#spyOnAllFunctions', function() {
it('checks for the existence of the object', function() { it('checks for the existence of the object', function() {
const spyRegistry = new privateUnderTest.SpyRegistry(); const spyRegistry = new jasmineUnderTest.SpyRegistry();
expect(function() { expect(function() {
spyRegistry.spyOnAllFunctions(void 0); spyRegistry.spyOnAllFunctions(void 0);
}).toThrowError(/spyOnAllFunctions could not find an object to spy upon/); }).toThrowError(/spyOnAllFunctions could not find an object to spy upon/);
}); });
it('overrides all writable and configurable functions of the object and its parents', function() { it('overrides all writable and configurable functions of the object and its parents', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() { createSpy: function() {
return 'I am a spy'; return 'I am a spy';
} }
@@ -334,21 +322,21 @@ describe('SpyRegistry', function() {
const parent = { const parent = {
parentSpied1: noop1 parentSpied1: noop1
}; };
const target = Object.create(parent); const subject = Object.create(parent);
Object.defineProperty(target, 'spied1', { Object.defineProperty(subject, 'spied1', {
value: noop1, value: noop1,
writable: true, writable: true,
configurable: true, configurable: true,
enumerable: true enumerable: true
}); });
Object.defineProperty(target, 'spied2', { Object.defineProperty(subject, 'spied2', {
value: noop2, value: noop2,
writable: true, writable: true,
configurable: true, configurable: true,
enumerable: true enumerable: true
}); });
let _spied3 = noop3; let _spied3 = noop3;
Object.defineProperty(target, 'spied3', { Object.defineProperty(subject, 'spied3', {
configurable: true, configurable: true,
set: function(val) { set: function(val) {
_spied3 = val; _spied3 = val;
@@ -358,20 +346,20 @@ describe('SpyRegistry', function() {
}, },
enumerable: true enumerable: true
}); });
target.spied4 = noop4; subject.spied4 = noop4;
Object.defineProperty(target, 'notSpied2', { Object.defineProperty(subject, 'notSpied2', {
value: noop2, value: noop2,
writable: false, writable: false,
configurable: true, configurable: true,
enumerable: true enumerable: true
}); });
Object.defineProperty(target, 'notSpied3', { Object.defineProperty(subject, 'notSpied3', {
value: noop3, value: noop3,
writable: true, writable: true,
configurable: false, configurable: false,
enumerable: true enumerable: true
}); });
Object.defineProperty(target, 'notSpied4', { Object.defineProperty(subject, 'notSpied4', {
configurable: false, configurable: false,
set: function() { set: function() {
/**/ /**/
@@ -381,31 +369,31 @@ describe('SpyRegistry', function() {
}, },
enumerable: true enumerable: true
}); });
Object.defineProperty(target, 'notSpied5', { Object.defineProperty(subject, 'notSpied5', {
value: noop5, value: noop5,
writable: true, writable: true,
configurable: true, configurable: true,
enumerable: false enumerable: false
}); });
target.notSpied6 = 6; subject.notSpied6 = 6;
const spiedObject = spyRegistry.spyOnAllFunctions(target); const spiedObject = spyRegistry.spyOnAllFunctions(subject);
expect(target.parentSpied1).toBe('I am a spy'); expect(subject.parentSpied1).toBe('I am a spy');
expect(target.notSpied2).toBe(noop2); expect(subject.notSpied2).toBe(noop2);
expect(target.notSpied3).toBe(noop3); expect(subject.notSpied3).toBe(noop3);
expect(target.notSpied4).toBe(noop4); expect(subject.notSpied4).toBe(noop4);
expect(target.notSpied5).toBe(noop5); expect(subject.notSpied5).toBe(noop5);
expect(target.notSpied6).toBe(6); expect(subject.notSpied6).toBe(6);
expect(target.spied1).toBe('I am a spy'); expect(subject.spied1).toBe('I am a spy');
expect(target.spied2).toBe('I am a spy'); expect(subject.spied2).toBe('I am a spy');
expect(target.spied3).toBe('I am a spy'); expect(subject.spied3).toBe('I am a spy');
expect(target.spied4).toBe('I am a spy'); expect(subject.spied4).toBe('I am a spy');
expect(spiedObject).toBe(target); expect(spiedObject).toBe(subject);
}); });
it('overrides prototype methods on the object', function() { it('overrides prototype methods on the object', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() { createSpy: function() {
return 'I am a spy'; return 'I am a spy';
} }
@@ -419,145 +407,145 @@ describe('SpyRegistry', function() {
}; };
MyClass.prototype.spied2 = noop2; MyClass.prototype.spied2 = noop2;
const target = new MyClass(); const subject = new MyClass();
spyRegistry.spyOnAllFunctions(target); spyRegistry.spyOnAllFunctions(subject);
expect(target.spied1).toBe('I am a spy'); expect(subject.spied1).toBe('I am a spy');
expect(target.spied2).toBe('I am a spy'); expect(subject.spied2).toBe('I am a spy');
expect(MyClass.prototype.spied2).toBe(noop2); expect(MyClass.prototype.spied2).toBe(noop2);
}); });
it('does not override non-enumerable properties (like Object.prototype methods)', function() { it('does not override non-enumerable properties (like Object.prototype methods)', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() { createSpy: function() {
return 'I am a spy'; return 'I am a spy';
} }
}); });
const target = { const subject = {
spied1: function() {} spied1: function() {}
}; };
spyRegistry.spyOnAllFunctions(target); spyRegistry.spyOnAllFunctions(subject);
expect(target.spied1).toBe('I am a spy'); expect(subject.spied1).toBe('I am a spy');
expect(target.toString).not.toBe('I am a spy'); expect(subject.toString).not.toBe('I am a spy');
expect(target.hasOwnProperty).not.toBe('I am a spy'); expect(subject.hasOwnProperty).not.toBe('I am a spy');
}); });
describe('when includeNonEnumerable is true', function() { describe('when includeNonEnumerable is true', function() {
it('does not override Object.prototype methods', function() { it('does not override Object.prototype methods', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() { createSpy: function() {
return 'I am a spy'; return 'I am a spy';
} }
}); });
const target = { const subject = {
spied1: function() {} spied1: function() {}
}; };
spyRegistry.spyOnAllFunctions(target, true); spyRegistry.spyOnAllFunctions(subject, true);
expect(target.spied1).toBe('I am a spy'); expect(subject.spied1).toBe('I am a spy');
expect(target.toString).not.toBe('I am a spy'); expect(subject.toString).not.toBe('I am a spy');
expect(target.hasOwnProperty).not.toBe('I am a spy'); expect(subject.hasOwnProperty).not.toBe('I am a spy');
}); });
it('overrides non-enumerable properties', function() { it('overrides non-enumerable properties', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() { createSpy: function() {
return 'I am a spy'; return 'I am a spy';
} }
}); });
const target = { const subject = {
spied1: function() {}, spied1: function() {},
spied2: function() {} spied2: function() {}
}; };
Object.defineProperty(target, 'spied2', { Object.defineProperty(subject, 'spied2', {
enumerable: false, enumerable: false,
writable: true, writable: true,
configurable: true configurable: true
}); });
spyRegistry.spyOnAllFunctions(target, true); spyRegistry.spyOnAllFunctions(subject, true);
expect(target.spied1).toBe('I am a spy'); expect(subject.spied1).toBe('I am a spy');
expect(target.spied2).toBe('I am a spy'); expect(subject.spied2).toBe('I am a spy');
}); });
it('should not spy on non-enumerable functions named constructor', function() { it('should not spy on non-enumerable functions named constructor', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() { createSpy: function() {
return 'I am a spy'; return 'I am a spy';
} }
}); });
const target = { const subject = {
constructor: function() {} constructor: function() {}
}; };
Object.defineProperty(target, 'constructor', { Object.defineProperty(subject, 'constructor', {
enumerable: false, enumerable: false,
writable: true, writable: true,
configurable: true configurable: true
}); });
spyRegistry.spyOnAllFunctions(target, true); spyRegistry.spyOnAllFunctions(subject, true);
expect(target.constructor).not.toBe('I am a spy'); expect(subject.constructor).not.toBe('I am a spy');
}); });
it('should spy on enumerable functions named constructor', function() { it('should spy on enumerable functions named constructor', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() { createSpy: function() {
return 'I am a spy'; return 'I am a spy';
} }
}); });
const target = { const subject = {
constructor: function() {} constructor: function() {}
}; };
spyRegistry.spyOnAllFunctions(target, true); spyRegistry.spyOnAllFunctions(subject, true);
expect(target.constructor).toBe('I am a spy'); expect(subject.constructor).toBe('I am a spy');
}); });
it('should not throw an exception if we try and access strict mode restricted properties', function() { it('should not throw an exception if we try and access strict mode restricted properties', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() { createSpy: function() {
return 'I am a spy'; return 'I am a spy';
} }
}); });
const target = function() {}; const subject = function() {};
const fn = function() { const fn = function() {
spyRegistry.spyOnAllFunctions(target, true); spyRegistry.spyOnAllFunctions(subject, true);
}; };
expect(fn).not.toThrow(); expect(fn).not.toThrow();
}); });
it('should not spy on properties which are more permissable further up the prototype chain', function() { it('should not spy on properties which are more permissable further up the prototype chain', function() {
const spyRegistry = new privateUnderTest.SpyRegistry({ const spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() { createSpy: function() {
return 'I am a spy'; return 'I am a spy';
} }
}); });
const targetParent = Object.defineProperty({}, 'sharedProp', { const subjectParent = Object.defineProperty({}, 'sharedProp', {
value: function() {}, value: function() {},
writable: true, writable: true,
configurable: true configurable: true
}); });
const target = Object.create(targetParent); const subject = Object.create(subjectParent);
Object.defineProperty(target, 'sharedProp', { Object.defineProperty(subject, 'sharedProp', {
value: function() {} value: function() {}
}); });
const fn = function() { const fn = function() {
spyRegistry.spyOnAllFunctions(target, true); spyRegistry.spyOnAllFunctions(subject, true);
}; };
expect(fn).not.toThrow(); expect(fn).not.toThrow();
expect(target).not.toBe('I am a spy'); expect(subject).not.toBe('I am a spy');
}); });
}); });
}); });
@@ -565,90 +553,90 @@ describe('SpyRegistry', function() {
describe('#clearSpies', function() { describe('#clearSpies', function() {
it('restores the original functions on the spied-upon objects', function() { it('restores the original functions on the spied-upon objects', function() {
const spies = [], const spies = [],
spyRegistry = new privateUnderTest.SpyRegistry({ spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return spies; return spies;
}, },
createSpy: createSpy createSpy: createSpy
}), }),
originalFunction = function() {}, originalFunction = function() {},
target = { spiedFunc: originalFunction }; subject = { spiedFunc: originalFunction };
spyRegistry.spyOn(target, 'spiedFunc'); spyRegistry.spyOn(subject, 'spiedFunc');
spyRegistry.clearSpies(); spyRegistry.clearSpies();
expect(target.spiedFunc).toBe(originalFunction); expect(subject.spiedFunc).toBe(originalFunction);
}); });
it('restores the original functions, even when that spy has been replace and re-spied upon', function() { it('restores the original functions, even when that spy has been replace and re-spied upon', function() {
const spies = [], const spies = [],
spyRegistry = new privateUnderTest.SpyRegistry({ spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return spies; return spies;
}, },
createSpy: createSpy createSpy: createSpy
}), }),
originalFunction = function() {}, originalFunction = function() {},
target = { spiedFunc: originalFunction }; subject = { spiedFunc: originalFunction };
spyRegistry.spyOn(target, 'spiedFunc'); spyRegistry.spyOn(subject, 'spiedFunc');
// replace the original spy with some other function // replace the original spy with some other function
target.spiedFunc = function() {}; subject.spiedFunc = function() {};
// spy on the function in that location again // spy on the function in that location again
spyRegistry.spyOn(target, 'spiedFunc'); spyRegistry.spyOn(subject, 'spiedFunc');
spyRegistry.clearSpies(); spyRegistry.clearSpies();
expect(target.spiedFunc).toBe(originalFunction); expect(subject.spiedFunc).toBe(originalFunction);
}); });
it("does not add a property that the spied-upon object didn't originally have", function() { it("does not add a property that the spied-upon object didn't originally have", function() {
const spies = [], const spies = [],
spyRegistry = new privateUnderTest.SpyRegistry({ spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return spies; return spies;
}, },
createSpy: createSpy createSpy: createSpy
}), }),
originalFunction = function() {}, originalFunction = function() {},
targetParent = { spiedFunc: originalFunction }; subjectParent = { spiedFunc: originalFunction };
const target = Object.create(targetParent); const subject = Object.create(subjectParent);
expect(target.hasOwnProperty('spiedFunc')).toBe(false); expect(subject.hasOwnProperty('spiedFunc')).toBe(false);
spyRegistry.spyOn(target, 'spiedFunc'); spyRegistry.spyOn(subject, 'spiedFunc');
spyRegistry.clearSpies(); spyRegistry.clearSpies();
expect(target.hasOwnProperty('spiedFunc')).toBe(false); expect(subject.hasOwnProperty('spiedFunc')).toBe(false);
expect(target.spiedFunc).toBe(originalFunction); expect(subject.spiedFunc).toBe(originalFunction);
}); });
it("restores the original function when it's inherited and cannot be deleted", function() { it("restores the original function when it's inherited and cannot be deleted", function() {
const spies = [], const spies = [],
spyRegistry = new privateUnderTest.SpyRegistry({ spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return spies; return spies;
}, },
createSpy: createSpy createSpy: createSpy
}), }),
originalFunction = function() {}, originalFunction = function() {},
targetParent = { spiedFunc: originalFunction }; subjectParent = { spiedFunc: originalFunction };
const target = Object.create(targetParent); const subject = Object.create(subjectParent);
spyRegistry.spyOn(target, 'spiedFunc'); spyRegistry.spyOn(subject, 'spiedFunc');
// simulate a spy that cannot be deleted // simulate a spy that cannot be deleted
Object.defineProperty(target, 'spiedFunc', { Object.defineProperty(subject, 'spiedFunc', {
configurable: false configurable: false
}); });
spyRegistry.clearSpies(); spyRegistry.clearSpies();
expect(jasmineUnderTest.isSpy(target.spiedFunc)).toBe(false); expect(jasmineUnderTest.isSpy(subject.spiedFunc)).toBe(false);
}); });
it('restores window.onerror by overwriting, not deleting', function() { it('restores window.onerror by overwriting, not deleting', function() {
@@ -657,7 +645,7 @@ describe('SpyRegistry', function() {
const spies = [], const spies = [],
global = new FakeWindow(), global = new FakeWindow(),
spyRegistry = new privateUnderTest.SpyRegistry({ spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return spies; return spies;
}, },
@@ -675,55 +663,55 @@ describe('SpyRegistry', function() {
describe('spying on properties', function() { describe('spying on properties', function() {
it('restores the original properties on the spied-upon objects', function() { it('restores the original properties on the spied-upon objects', function() {
const spies = [], const spies = [],
spyRegistry = new privateUnderTest.SpyRegistry({ spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return spies; return spies;
}, },
createSpy: createSpy createSpy: createSpy
}), }),
originalReturn = 1, originalReturn = 1,
target = {}; subject = {};
Object.defineProperty(target, 'spiedProp', { Object.defineProperty(subject, 'spiedProp', {
get: function() { get: function() {
return originalReturn; return originalReturn;
}, },
configurable: true configurable: true
}); });
spyRegistry.spyOnProperty(target, 'spiedProp'); spyRegistry.spyOnProperty(subject, 'spiedProp');
spyRegistry.clearSpies(); spyRegistry.clearSpies();
expect(target.spiedProp).toBe(originalReturn); expect(subject.spiedProp).toBe(originalReturn);
}); });
it("does not add a property that the spied-upon object didn't originally have", function() { it("does not add a property that the spied-upon object didn't originally have", function() {
const spies = [], const spies = [],
spyRegistry = new privateUnderTest.SpyRegistry({ spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
return spies; return spies;
}, },
createSpy: createSpy createSpy: createSpy
}), }),
originalReturn = 1, originalReturn = 1,
targetParent = {}; subjectParent = {};
Object.defineProperty(targetParent, 'spiedProp', { Object.defineProperty(subjectParent, 'spiedProp', {
get: function() { get: function() {
return originalReturn; return originalReturn;
}, },
configurable: true configurable: true
}); });
const target = Object.create(targetParent); const subject = Object.create(subjectParent);
expect(target.hasOwnProperty('spiedProp')).toBe(false); expect(subject.hasOwnProperty('spiedProp')).toBe(false);
spyRegistry.spyOnProperty(target, 'spiedProp'); spyRegistry.spyOnProperty(subject, 'spiedProp');
spyRegistry.clearSpies(); spyRegistry.clearSpies();
expect(target.hasOwnProperty('spiedProp')).toBe(false); expect(subject.hasOwnProperty('spiedProp')).toBe(false);
expect(target.spiedProp).toBe(originalReturn); expect(subject.spiedProp).toBe(originalReturn);
}); });
}); });
}); });
+5 -5
View File
@@ -2,7 +2,7 @@ describe('Spies', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
}); });
afterEach(function() { afterEach(function() {
@@ -50,8 +50,8 @@ describe('Spies', function() {
TestClass.prototype.someFunction TestClass.prototype.someFunction
); );
expect(spy.and).toEqual(jasmine.any(privateUnderTest.SpyStrategy)); expect(spy.and).toEqual(jasmine.any(jasmineUnderTest.SpyStrategy));
expect(spy.calls).toEqual(jasmine.any(privateUnderTest.CallTracker)); expect(spy.calls).toEqual(jasmine.any(jasmineUnderTest.CallTracker));
}); });
it('tracks the argument of calls', function() { it('tracks the argument of calls', function() {
@@ -241,7 +241,7 @@ describe('Spies', function() {
}); });
it('uses the provided matchersUtil selecting a strategy', function() { it('uses the provided matchersUtil selecting a strategy', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [ customTesters: [
function(a, b) { function(a, b) {
if ((a === 'bar' && b === 'baz') || (a === 'baz' && b === 'bar')) { if ((a === 'bar' && b === 'baz') || (a === 'baz' && b === 'bar')) {
@@ -250,7 +250,7 @@ describe('Spies', function() {
} }
] ]
}); });
const spy = new privateUnderTest.Spy('aSpy', matchersUtil); const spy = new jasmineUnderTest.Spy('aSpy', matchersUtil);
spy.and.returnValue('default strategy return value'); spy.and.returnValue('default strategy return value');
spy.withArgs('bar').and.returnValue('custom strategy return value'); spy.withArgs('bar').and.returnValue('custom strategy return value');
expect(spy('foo')).toEqual('default strategy return value'); expect(spy('foo')).toEqual('default strategy return value');
+33 -28
View File
@@ -1,19 +1,19 @@
describe('SpyStrategy', function() { describe('SpyStrategy', function() {
it('defaults its name to unknown', function() { it('defaults its name to unknown', function() {
const spyStrategy = new privateUnderTest.SpyStrategy(); const spyStrategy = new jasmineUnderTest.SpyStrategy();
expect(spyStrategy.identity).toEqual('unknown'); expect(spyStrategy.identity).toEqual('unknown');
}); });
it('takes a name', function() { it('takes a name', function() {
const spyStrategy = new privateUnderTest.SpyStrategy({ name: 'foo' }); const spyStrategy = new jasmineUnderTest.SpyStrategy({ name: 'foo' });
expect(spyStrategy.identity).toEqual('foo'); expect(spyStrategy.identity).toEqual('foo');
}); });
it('stubs an original function, if provided', function() { it('stubs an original function, if provided', function() {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.exec(); spyStrategy.exec();
@@ -22,7 +22,7 @@ describe('SpyStrategy', function() {
it("allows an original function to be called, passed through the params and returns it's value", function() { it("allows an original function to be called, passed through the params and returns it's value", function() {
const originalFn = jasmine.createSpy('original').and.returnValue(42), const originalFn = jasmine.createSpy('original').and.returnValue(42),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.callThrough(); spyStrategy.callThrough();
const returnValue = spyStrategy.exec(null, ['foo']); const returnValue = spyStrategy.exec(null, ['foo']);
@@ -34,7 +34,7 @@ describe('SpyStrategy', function() {
it('can return a specified value when executed', function() { it('can return a specified value when executed', function() {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.returnValue(17); spyStrategy.returnValue(17);
const returnValue = spyStrategy.exec(); const returnValue = spyStrategy.exec();
@@ -45,7 +45,7 @@ describe('SpyStrategy', function() {
it('can return specified values in order specified when executed', function() { it('can return specified values in order specified when executed', function() {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.returnValues('value1', 'value2', 'value3'); spyStrategy.returnValues('value1', 'value2', 'value3');
@@ -58,7 +58,7 @@ describe('SpyStrategy', function() {
it('allows an exception to be thrown when executed', function() { it('allows an exception to be thrown when executed', function() {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.throwError(new TypeError('bar')); spyStrategy.throwError(new TypeError('bar'));
@@ -70,7 +70,7 @@ describe('SpyStrategy', function() {
it('allows a string to be thrown, wrapping it into an exception when executed', function() { it('allows a string to be thrown, wrapping it into an exception when executed', function() {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.throwError('bar'); spyStrategy.throwError('bar');
@@ -82,7 +82,7 @@ describe('SpyStrategy', function() {
it('allows a non-Error to be thrown when executed', function() { it('allows a non-Error to be thrown when executed', function() {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.throwError({ code: 'ESRCH' }); spyStrategy.throwError({ code: 'ESRCH' });
@@ -95,7 +95,7 @@ describe('SpyStrategy', function() {
it('allows a fake function to be called instead', function() { it('allows a fake function to be called instead', function() {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
fakeFn = jasmine.createSpy('fake').and.returnValue(67), fakeFn = jasmine.createSpy('fake').and.returnValue(67),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.callFake(fakeFn); spyStrategy.callFake(fakeFn);
const returnValue = spyStrategy.exec(); const returnValue = spyStrategy.exec();
@@ -109,7 +109,7 @@ describe('SpyStrategy', function() {
fakeFn = jasmine.createSpy('fake').and.callFake(async () => { fakeFn = jasmine.createSpy('fake').and.callFake(async () => {
return 67; return 67;
}), }),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.callFake(fakeFn); spyStrategy.callFake(fakeFn);
spyStrategy spyStrategy
@@ -128,7 +128,7 @@ describe('SpyStrategy', function() {
describe('#resolveTo', function() { describe('#resolveTo', function() {
it('allows a resolved promise to be returned', function(done) { it('allows a resolved promise to be returned', function(done) {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ spyStrategy = new jasmineUnderTest.SpyStrategy({
fn: originalFn fn: originalFn
}); });
@@ -144,7 +144,7 @@ describe('SpyStrategy', function() {
it('allows an empty resolved promise to be returned', function(done) { it('allows an empty resolved promise to be returned', function(done) {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ spyStrategy = new jasmineUnderTest.SpyStrategy({
fn: originalFn fn: originalFn
}); });
@@ -162,7 +162,7 @@ describe('SpyStrategy', function() {
describe('#rejectWith', function() { describe('#rejectWith', function() {
it('allows a rejected promise to be returned', function(done) { it('allows a rejected promise to be returned', function(done) {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ spyStrategy = new jasmineUnderTest.SpyStrategy({
fn: originalFn fn: originalFn
}); });
@@ -179,7 +179,7 @@ describe('SpyStrategy', function() {
it('allows an empty rejected promise to be returned', function(done) { it('allows an empty rejected promise to be returned', function(done) {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ spyStrategy = new jasmineUnderTest.SpyStrategy({
fn: originalFn fn: originalFn
}); });
@@ -196,7 +196,7 @@ describe('SpyStrategy', function() {
it('allows a non-Error to be rejected', function(done) { it('allows a non-Error to be rejected', function(done) {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ spyStrategy = new jasmineUnderTest.SpyStrategy({
fn: originalFn fn: originalFn
}); });
@@ -220,7 +220,7 @@ describe('SpyStrategy', function() {
.createSpy('custom strategy') .createSpy('custom strategy')
.and.returnValue(plan), .and.returnValue(plan),
originalFn = jasmine.createSpy('original'), originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ spyStrategy = new jasmineUnderTest.SpyStrategy({
fn: originalFn, fn: originalFn,
customStrategies: { customStrategies: {
doSomething: customStrategy doSomething: customStrategy
@@ -237,7 +237,7 @@ describe('SpyStrategy', function() {
it("throws an error if a custom strategy doesn't return a function", function() { it("throws an error if a custom strategy doesn't return a function", function() {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ spyStrategy = new jasmineUnderTest.SpyStrategy({
fn: originalFn, fn: originalFn,
customStrategies: { customStrategies: {
doSomething: function() { doSomething: function() {
@@ -252,32 +252,37 @@ describe('SpyStrategy', function() {
}); });
it('does not allow custom strategies to overwrite existing methods', function() { it('does not allow custom strategies to overwrite existing methods', function() {
const spyStrategy = new privateUnderTest.SpyStrategy({ const spyStrategy = new jasmineUnderTest.SpyStrategy({
fn: function() {}, fn: function() {},
customStrategies: { customStrategies: {
exec: function() {} exec: function() {}
} }
}); });
expect(spyStrategy.exec).toBe(privateUnderTest.SpyStrategy.prototype.exec); expect(spyStrategy.exec).toBe(jasmineUnderTest.SpyStrategy.prototype.exec);
}); });
it('throws an error when a non-function is passed to callFake strategy', function() { it('throws an error when a non-function is passed to callFake strategy', function() {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyOn(jasmineUnderTest, 'isFunction_').and.returnValue(false);
spyOn(jasmineUnderTest, 'isAsyncFunction_').and.returnValue(false);
expect(function() { expect(function() {
spyStrategy.callFake('not a function'); spyStrategy.callFake(function() {});
}).toThrowError( }).toThrowError(/^Argument passed to callFake should be a function, got/);
'Argument passed to callFake should be a function, got not a function'
); expect(function() {
spyStrategy.callFake(function() {});
}).toThrowError(/^Argument passed to callFake should be a function, got/);
}); });
it('allows generator functions to be passed to callFake strategy', function() { it('allows generator functions to be passed to callFake strategy', function() {
const generator = function*() { const generator = function*() {
yield 'ok'; yield 'ok';
}, },
spyStrategy = new privateUnderTest.SpyStrategy({ fn: function() {} }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: function() {} });
spyStrategy.callFake(generator); spyStrategy.callFake(generator);
@@ -287,7 +292,7 @@ describe('SpyStrategy', function() {
it('allows a return to plan stubbing after another strategy', function() { it('allows a return to plan stubbing after another strategy', function() {
const originalFn = jasmine.createSpy('original'), const originalFn = jasmine.createSpy('original'),
fakeFn = jasmine.createSpy('fake').and.returnValue(67), fakeFn = jasmine.createSpy('fake').and.returnValue(67),
spyStrategy = new privateUnderTest.SpyStrategy({ fn: originalFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.callFake(fakeFn); spyStrategy.callFake(fakeFn);
let returnValue = spyStrategy.exec(); let returnValue = spyStrategy.exec();
@@ -304,7 +309,7 @@ describe('SpyStrategy', function() {
it('returns the spy after changing the strategy', function() { it('returns the spy after changing the strategy', function() {
const spy = {}, const spy = {},
spyFn = jasmine.createSpy('spyFn').and.returnValue(spy), spyFn = jasmine.createSpy('spyFn').and.returnValue(spy),
spyStrategy = new privateUnderTest.SpyStrategy({ getSpy: spyFn }); spyStrategy = new jasmineUnderTest.SpyStrategy({ getSpy: spyFn });
expect(spyStrategy.callThrough()).toBe(spy); expect(spyStrategy.callThrough()).toBe(spy);
expect(spyStrategy.returnValue()).toBe(spy); expect(spyStrategy.returnValue()).toBe(spy);
+11 -11
View File
@@ -8,7 +8,7 @@ describe('StackTrace', function() {
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)' ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)'
}; };
const result = new privateUnderTest.StackTrace(error); const result = new jasmineUnderTest.StackTrace(error);
expect(result.message).toEqual('Error: nope'); expect(result.message).toEqual('Error: nope');
expect(result.style).toEqual('v8'); expect(result.style).toEqual('v8');
@@ -39,7 +39,7 @@ describe('StackTrace', function() {
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)' ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)'
}; };
const result = new privateUnderTest.StackTrace(error); const result = new jasmineUnderTest.StackTrace(error);
expect(result.message).toEqual('Error: line 1\nline 2'); expect(result.message).toEqual('Error: line 1\nline 2');
const rawFrames = result.frames.map(function(f) { const rawFrames = result.frames.map(function(f) {
@@ -60,7 +60,7 @@ describe('StackTrace', function() {
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)' ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)'
}; };
const result = new privateUnderTest.StackTrace(error); const result = new jasmineUnderTest.StackTrace(error);
expect(result.message).toEqual('Error: line 1\n\nline 2'); expect(result.message).toEqual('Error: line 1\n\nline 2');
const rawFrames = result.frames.map(function(f) { const rawFrames = result.frames.map(function(f) {
@@ -82,7 +82,7 @@ describe('StackTrace', function() {
' at Immediate.<anonymous> (/somewhere/jasmine/lib/jasmine-core/jasmine.js:4314:12)\n' + ' at Immediate.<anonymous> (/somewhere/jasmine/lib/jasmine-core/jasmine.js:4314:12)\n' +
' at runCallback (timers.js:672:20)' ' at runCallback (timers.js:672:20)'
}; };
const result = new privateUnderTest.StackTrace(error); const result = new jasmineUnderTest.StackTrace(error);
expect(result.message).toEqual('Error'); expect(result.message).toEqual('Error');
expect(result.style).toEqual('v8'); expect(result.style).toEqual('v8');
@@ -123,7 +123,7 @@ describe('StackTrace', function() {
'http://localhost:8888/__spec__/core/UtilSpec.js:115:28\n' + 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28\n' +
'run@http://localhost:8888/__jasmine__/jasmine.js:4320:27' 'run@http://localhost:8888/__jasmine__/jasmine.js:4320:27'
}; };
const result = new privateUnderTest.StackTrace(error); const result = new jasmineUnderTest.StackTrace(error);
expect(result.message).toBeFalsy(); expect(result.message).toBeFalsy();
expect(result.style).toEqual('webkit'); expect(result.style).toEqual('webkit');
@@ -150,7 +150,7 @@ describe('StackTrace', function() {
'@http://localhost:8888/__spec__/core/FooSpec.js:164:24\n' + '@http://localhost:8888/__spec__/core/FooSpec.js:164:24\n' +
'attempt@http://localhost:8888/__jasmine__/jasmine.js:8074:44\n' 'attempt@http://localhost:8888/__jasmine__/jasmine.js:8074:44\n'
}; };
const result = new privateUnderTest.StackTrace(error); const result = new jasmineUnderTest.StackTrace(error);
expect(result.message).toBeFalsy(); expect(result.message).toBeFalsy();
expect(result.style).toEqual('webkit'); expect(result.style).toEqual('webkit');
@@ -175,7 +175,7 @@ describe('StackTrace', function() {
message: 'nope', message: 'nope',
stack: 'randomcharsnotincludingwhitespace' stack: 'randomcharsnotincludingwhitespace'
}; };
const result = new privateUnderTest.StackTrace(error); const result = new jasmineUnderTest.StackTrace(error);
expect(result.style).toBeNull(); expect(result.style).toBeNull();
expect(result.frames).toEqual([{ raw: error.stack }]); expect(result.frames).toEqual([{ raw: error.stack }]);
}); });
@@ -187,7 +187,7 @@ describe('StackTrace', function() {
' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n' ' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n'
}; };
const result = new privateUnderTest.StackTrace(error); const result = new jasmineUnderTest.StackTrace(error);
expect(result.frames).toEqual([ expect(result.frames).toEqual([
{ {
@@ -209,7 +209,7 @@ describe('StackTrace', function() {
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)' ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)'
}; };
const result = new privateUnderTest.StackTrace(error); const result = new jasmineUnderTest.StackTrace(error);
expect(result.style).toEqual('v8'); expect(result.style).toEqual('v8');
expect(result.frames).toEqual([ expect(result.frames).toEqual([
{ {
@@ -241,7 +241,7 @@ describe('StackTrace', function() {
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)' ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)'
}; };
const result = new privateUnderTest.StackTrace(error); const result = new jasmineUnderTest.StackTrace(error);
expect(result.message).toEqual('TypeError: nope'); expect(result.message).toEqual('TypeError: nope');
expect(result.frames).toEqual([ expect(result.frames).toEqual([
@@ -269,7 +269,7 @@ describe('StackTrace', function() {
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)' ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)'
}; };
const result_no_error = new privateUnderTest.StackTrace(no_error); const result_no_error = new jasmineUnderTest.StackTrace(no_error);
expect(result_no_error.message).not.toEqual(jasmine.anything()); expect(result_no_error.message).not.toEqual(jasmine.anything());
}); });
+26 -27
View File
@@ -1,12 +1,12 @@
describe('SuiteBuilder', function() { describe('SuiteBuilder', function() {
beforeEach(function() { beforeEach(function() {
// Rethrow exceptions to ease debugging // Rethrow exceptions to ease debugging
spyOn(privateUnderTest.Suite.prototype, 'handleException').and.callFake( spyOn(jasmineUnderTest.Suite.prototype, 'handleException').and.callFake(
function(e) { function(e) {
throw e; throw e;
} }
); );
spyOn(privateUnderTest.Spec.prototype, 'handleException').and.callFake( spyOn(jasmineUnderTest.Spec.prototype, 'handleException').and.callFake(
function(e) { function(e) {
throw e; throw e;
} }
@@ -15,9 +15,9 @@ describe('SuiteBuilder', function() {
it('creates the top suite', function() { it('creates the top suite', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
expect(suiteBuilder.topSuite).toBeInstanceOf(privateUnderTest.Suite); expect(suiteBuilder.topSuite).toBeInstanceOf(jasmineUnderTest.Suite);
expect(suiteBuilder.topSuite.description).toEqual( expect(suiteBuilder.topSuite.description).toEqual(
'Jasmine__TopLevel__Suite' 'Jasmine__TopLevel__Suite'
); );
@@ -33,7 +33,7 @@ describe('SuiteBuilder', function() {
it('focuses the suite', function() { it('focuses the suite', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
const suite = suiteBuilder.fdescribe('a suite', function() { const suite = suiteBuilder.fdescribe('a suite', function() {
suiteBuilder.it('a spec'); suiteBuilder.it('a spec');
@@ -45,7 +45,7 @@ describe('SuiteBuilder', function() {
it('unfocuses any focused ancestor suite', function() { it('unfocuses any focused ancestor suite', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
const grandparent = suiteBuilder.fdescribe('a suite', function() { const grandparent = suiteBuilder.fdescribe('a suite', function() {
suiteBuilder.describe('another suite', function() { suiteBuilder.describe('another suite', function() {
@@ -64,7 +64,7 @@ describe('SuiteBuilder', function() {
it('excludes the suite', function() { it('excludes the suite', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
const suite = suiteBuilder.xdescribe('a suite', function() { const suite = suiteBuilder.xdescribe('a suite', function() {
suiteBuilder.it('a spec'); suiteBuilder.it('a spec');
@@ -75,7 +75,7 @@ describe('SuiteBuilder', function() {
it('causes child suites to be marked excluded', function() { it('causes child suites to be marked excluded', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
let suite; let suite;
suiteBuilder.xdescribe('a suite', function() { suiteBuilder.xdescribe('a suite', function() {
@@ -103,7 +103,7 @@ describe('SuiteBuilder', function() {
function definesSuites(fnName) { function definesSuites(fnName) {
it('links suites to their parents and children', function() { it('links suites to their parents and children', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
let child; let child;
const parent = suiteBuilder[fnName]('parent', function() { const parent = suiteBuilder[fnName]('parent', function() {
@@ -120,7 +120,7 @@ describe('SuiteBuilder', function() {
it('gives each suite a unique ID', function() { it('gives each suite a unique ID', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
let child; let child;
const parent = suiteBuilder[fnName]('parent', function() { const parent = suiteBuilder[fnName]('parent', function() {
@@ -142,7 +142,7 @@ describe('SuiteBuilder', function() {
function definesSpecs(fnName) { function definesSpecs(fnName) {
it('adds the spec to its suite', function() { it('adds the spec to its suite', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
let spec; let spec;
const suite = suiteBuilder.describe('a suite', function() { const suite = suiteBuilder.describe('a suite', function() {
@@ -154,7 +154,7 @@ describe('SuiteBuilder', function() {
it('gives each spec a unique ID', function() { it('gives each spec a unique ID', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
const spec1 = suiteBuilder[fnName]('a spec', function() {}); const spec1 = suiteBuilder[fnName]('a spec', function() {});
const spec2 = suiteBuilder[fnName]('another spec', function() {}); const spec2 = suiteBuilder[fnName]('another spec', function() {});
@@ -166,7 +166,7 @@ describe('SuiteBuilder', function() {
it('gives each spec a full path', function() { it('gives each spec a full path', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
let spec; let spec;
suiteBuilder.describe('a suite', function() { suiteBuilder.describe('a suite', function() {
@@ -199,7 +199,7 @@ describe('SuiteBuilder', function() {
}); });
it('forbids duplicate spec names', function() { it('forbids duplicate spec names', function() {
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
expect(function() { expect(function() {
suiteBuilder.describe('a suite', function() { suiteBuilder.describe('a suite', function() {
@@ -214,7 +214,7 @@ describe('SuiteBuilder', function() {
}); });
it('forbids duplicate spec names in the top suite', function() { it('forbids duplicate spec names in the top suite', function() {
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
expect(function() { expect(function() {
suiteBuilder.it('another spec'); suiteBuilder.it('another spec');
@@ -225,7 +225,7 @@ describe('SuiteBuilder', function() {
}); });
it('forbids duplicate suite names', function() { it('forbids duplicate suite names', function() {
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
expect(function() { expect(function() {
suiteBuilder.describe('a suite', function() { suiteBuilder.describe('a suite', function() {
@@ -244,7 +244,7 @@ describe('SuiteBuilder', function() {
}); });
it('forbids duplicate suite names in the top suite', function() { it('forbids duplicate suite names in the top suite', function() {
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
expect(function() { expect(function() {
suiteBuilder.describe('a suite', function() { suiteBuilder.describe('a suite', function() {
@@ -257,7 +257,7 @@ describe('SuiteBuilder', function() {
}); });
it('allows spec and suite names to be duplicated in different suites', function() { it('allows spec and suite names to be duplicated in different suites', function() {
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
expect(function() { expect(function() {
suiteBuilder.describe('suite a', function() { suiteBuilder.describe('suite a', function() {
@@ -285,7 +285,7 @@ describe('SuiteBuilder', function() {
}); });
it('allows duplicate spec and suite names', function() { it('allows duplicate spec and suite names', function() {
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
expect(function() { expect(function() {
suiteBuilder.describe('dupe suite', function() { suiteBuilder.describe('dupe suite', function() {
@@ -303,19 +303,18 @@ describe('SuiteBuilder', function() {
describe('#parallelReset', function() { describe('#parallelReset', function() {
it('resets the top suite result', function() { it('resets the top suite result', function() {
privateUnderTest.Suite.prototype.handleException.and.callThrough(); jasmineUnderTest.Suite.prototype.handleException.and.callThrough();
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
suiteBuilder.topSuite.handleException(new Error('nope')); suiteBuilder.topSuite.handleException(new Error('nope'));
suiteBuilder.parallelReset(); suiteBuilder.parallelReset();
expect(suiteBuilder.topSuite.doneEvent()).toEqual({ expect(suiteBuilder.topSuite.result).toEqual({
id: suiteBuilder.topSuite.id, id: suiteBuilder.topSuite.id,
description: 'Jasmine__TopLevel__Suite', description: 'Jasmine__TopLevel__Suite',
fullName: '', fullName: '',
status: 'passed',
failedExpectations: [], failedExpectations: [],
deprecationWarnings: [], deprecationWarnings: [],
duration: null, duration: null,
@@ -327,7 +326,7 @@ describe('SuiteBuilder', function() {
it('removes children of the top suite', function() { it('removes children of the top suite', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
suiteBuilder.describe('a suite', function() { suiteBuilder.describe('a suite', function() {
suiteBuilder.it('a nested spec'); suiteBuilder.it('a nested spec');
}); });
@@ -340,7 +339,7 @@ describe('SuiteBuilder', function() {
it('preserves top suite befores and afters', function() { it('preserves top suite befores and afters', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
function beforeAll() {} function beforeAll() {}
function beforeEach() {} function beforeEach() {}
@@ -370,7 +369,7 @@ describe('SuiteBuilder', function() {
it('resets totalSpecsDefined', function() { it('resets totalSpecsDefined', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
suiteBuilder.it('a spec'); suiteBuilder.it('a spec');
suiteBuilder.parallelReset(); suiteBuilder.parallelReset();
@@ -380,7 +379,7 @@ describe('SuiteBuilder', function() {
it('resets focusedRunables', function() { it('resets focusedRunables', function() {
const env = { configuration: () => ({}) }; const env = { configuration: () => ({}) };
const suiteBuilder = new privateUnderTest.SuiteBuilder({ env }); const suiteBuilder = new jasmineUnderTest.SuiteBuilder({ env });
suiteBuilder.fit('a spec', function() {}); suiteBuilder.fit('a spec', function() {});
suiteBuilder.parallelReset(); suiteBuilder.parallelReset();
+49 -109
View File
@@ -2,7 +2,7 @@ describe('Suite', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
}); });
afterEach(function() { afterEach(function() {
@@ -10,7 +10,7 @@ describe('Suite', function() {
}); });
it('keeps its id', function() { it('keeps its id', function() {
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
env: env, env: env,
id: 456, id: 456,
description: 'I am a suite' description: 'I am a suite'
@@ -20,7 +20,7 @@ describe('Suite', function() {
}); });
it('returns blank full name for top level suite', function() { it('returns blank full name for top level suite', function() {
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
env: env, env: env,
description: 'I am a suite' description: 'I am a suite'
}); });
@@ -29,12 +29,12 @@ describe('Suite', function() {
}); });
it('returns its full name when it has parent suites', function() { it('returns its full name when it has parent suites', function() {
const parentSuite = new privateUnderTest.Suite({ const parentSuite = new jasmineUnderTest.Suite({
env: env, env: env,
description: 'I am a parent suite', description: 'I am a parent suite',
parentSuite: jasmine.createSpy('pretend top level suite') parentSuite: jasmine.createSpy('pretend top level suite')
}), }),
suite = new privateUnderTest.Suite({ suite = new jasmineUnderTest.Suite({
env: env, env: env,
description: 'I am a suite', description: 'I am a suite',
parentSuite: parentSuite parentSuite: parentSuite
@@ -44,7 +44,7 @@ describe('Suite', function() {
}); });
it('adds beforeEach functions in order of needed execution', function() { it('adds beforeEach functions in order of needed execution', function() {
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
env: env, env: env,
description: 'I am a suite' description: 'I am a suite'
}), }),
@@ -61,7 +61,7 @@ describe('Suite', function() {
}); });
it('adds beforeAll functions in order of needed execution', function() { it('adds beforeAll functions in order of needed execution', function() {
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
env: env, env: env,
description: 'I am a suite' description: 'I am a suite'
}), }),
@@ -78,7 +78,7 @@ describe('Suite', function() {
}); });
it('adds afterEach functions in order of needed execution', function() { it('adds afterEach functions in order of needed execution', function() {
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
env: env, env: env,
description: 'I am a suite' description: 'I am a suite'
}), }),
@@ -95,7 +95,7 @@ describe('Suite', function() {
}); });
it('adds afterAll functions in order of needed execution', function() { it('adds afterAll functions in order of needed execution', function() {
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
env: env, env: env,
description: 'I am a suite' description: 'I am a suite'
}), }),
@@ -112,53 +112,51 @@ describe('Suite', function() {
}); });
it('has a status of failed if any expectations have failed', function() { it('has a status of failed if any expectations have failed', function() {
const suite = new privateUnderTest.Suite({}); const suite = new jasmineUnderTest.Suite({});
suite.addExpectationResult(false, {}); suite.addExpectationResult(false, {});
expect(suite.doneEvent().status).toBe('failed'); expect(suite.getResult().status).toBe('failed');
}); });
it('retrieves a result with updated status', function() { it('retrieves a result with updated status', function() {
const suite = new privateUnderTest.Suite({}); const suite = new jasmineUnderTest.Suite({});
expect(suite.doneEvent().status).toBe('passed'); expect(suite.getResult().status).toBe('passed');
}); });
it('retrieves a result with pending status', function() { it('retrieves a result with pending status', function() {
const suite = new privateUnderTest.Suite({}); const suite = new jasmineUnderTest.Suite({});
suite.pend(); suite.pend();
expect(suite.doneEvent().status).toBe('pending'); expect(suite.getResult().status).toBe('pending');
}); });
it('throws an ExpectationFailed when receiving a failed expectation when throwOnExpectationFailure is set', function() { it('throws an ExpectationFailed when receiving a failed expectation when throwOnExpectationFailure is set', function() {
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
throwOnExpectationFailure: true throwOnExpectationFailure: true
}); });
expect(function() { expect(function() {
suite.addExpectationResult(false, { message: 'failed' }); suite.addExpectationResult(false, { message: 'failed' });
}).toThrowError(jasmineUnderTest.private.errors.ExpectationFailed); }).toThrowError(jasmineUnderTest.errors.ExpectationFailed);
expect(suite.doneEvent().status).toBe('failed'); expect(suite.getResult().status).toBe('failed');
expect(suite.doneEvent().failedExpectations).toEqual([ expect(suite.result.failedExpectations).toEqual([
jasmine.objectContaining({ message: 'failed' }) jasmine.objectContaining({ message: 'failed' })
]); ]);
}); });
it('does not add an additional failure when an expectation fails', function() { it('does not add an additional failure when an expectation fails', function() {
const suite = new privateUnderTest.Suite({}); const suite = new jasmineUnderTest.Suite({});
suite.handleException( suite.handleException(new jasmineUnderTest.errors.ExpectationFailed());
new jasmineUnderTest.private.errors.ExpectationFailed()
);
expect(suite.doneEvent().failedExpectations).toEqual([]); expect(suite.getResult().failedExpectations).toEqual([]);
}); });
it('forwards late expectation failures to onLateError', function() { it('forwards late expectation failures to onLateError', function() {
const onLateError = jasmine.createSpy('onLateError'); const onLateError = jasmine.createSpy('onLateError');
const suite = new privateUnderTest.Suite({ onLateError }); const suite = new jasmineUnderTest.Suite({ onLateError });
const data = { const data = {
matcherName: '', matcherName: '',
passed: false, passed: false,
@@ -175,12 +173,12 @@ describe('Suite', function() {
message: jasmine.stringMatching(/^Error: nope/) message: jasmine.stringMatching(/^Error: nope/)
}) })
); );
expect(suite.doneEvent().failedExpectations).toEqual([]); expect(suite.result.failedExpectations).toEqual([]);
}); });
it('does not forward non-late expectation failures to onLateError', function() { it('does not forward non-late expectation failures to onLateError', function() {
const onLateError = jasmine.createSpy('onLateError'); const onLateError = jasmine.createSpy('onLateError');
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
onLateError onLateError
}); });
const data = { const data = {
@@ -194,12 +192,12 @@ describe('Suite', function() {
suite.addExpectationResult(false, data, true); suite.addExpectationResult(false, data, true);
expect(onLateError).not.toHaveBeenCalled(); expect(onLateError).not.toHaveBeenCalled();
expect(suite.doneEvent().failedExpectations.length).toEqual(1); expect(suite.result.failedExpectations.length).toEqual(1);
}); });
it('forwards late handleException calls to onLateError', function() { it('forwards late handleException calls to onLateError', function() {
const onLateError = jasmine.createSpy('onLateError'); const onLateError = jasmine.createSpy('onLateError');
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
onLateError onLateError
}); });
const error = new Error('oops'); const error = new Error('oops');
@@ -212,12 +210,12 @@ describe('Suite', function() {
message: jasmine.stringMatching(/^Error: oops/) message: jasmine.stringMatching(/^Error: oops/)
}) })
); );
expect(suite.doneEvent().failedExpectations).toEqual([]); expect(suite.result.failedExpectations).toEqual([]);
}); });
it('does not forward non-late handleException calls to onLateError', function() { it('does not forward non-late handleException calls to onLateError', function() {
const onLateError = jasmine.createSpy('onLateError'); const onLateError = jasmine.createSpy('onLateError');
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
onLateError onLateError
}); });
const error = new Error('oops'); const error = new Error('oops');
@@ -225,11 +223,11 @@ describe('Suite', function() {
suite.handleException(error); suite.handleException(error);
expect(onLateError).not.toHaveBeenCalled(); expect(onLateError).not.toHaveBeenCalled();
expect(suite.doneEvent().failedExpectations.length).toEqual(1); expect(suite.result.failedExpectations.length).toEqual(1);
}); });
it('clears the reportedDone flag when reset', function() { it('clears the reportedDone flag when reset', function() {
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
queueableFn: { fn: function() {} } queueableFn: { fn: function() {} }
}); });
suite.reportedDone = true; suite.reportedDone = true;
@@ -240,7 +238,7 @@ describe('Suite', function() {
}); });
it('calls timer to compute duration', function() { it('calls timer to compute duration', function() {
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
env: env, env: env,
id: 456, id: 456,
description: 'I am a suite', description: 'I am a suite',
@@ -248,24 +246,24 @@ describe('Suite', function() {
}); });
suite.startTimer(); suite.startTimer();
suite.endTimer(); suite.endTimer();
expect(suite.doneEvent().duration).toEqual(77000); expect(suite.getResult().duration).toEqual(77000);
}); });
describe('#sharedUserContext', function() { describe('#sharedUserContext', function() {
beforeEach(function() { beforeEach(function() {
this.suite = new privateUnderTest.Suite({}); this.suite = new jasmineUnderTest.Suite({});
}); });
it('returns a UserContext', function() { it('returns a UserContext', function() {
expect(this.suite.sharedUserContext().constructor).toBe( expect(this.suite.sharedUserContext().constructor).toBe(
privateUnderTest.UserContext jasmineUnderTest.UserContext
); );
}); });
}); });
describe('attr.autoCleanClosures', function() { describe('attr.autoCleanClosures', function() {
function arrangeSuite(attrs) { function arrangeSuite(attrs) {
const suite = new privateUnderTest.Suite(attrs); const suite = new jasmineUnderTest.Suite(attrs);
suite.beforeAll(function() {}); suite.beforeAll(function() {});
suite.beforeEach(function() {}); suite.beforeEach(function() {});
suite.afterEach(function() {}); suite.afterEach(function() {});
@@ -303,21 +301,21 @@ describe('Suite', function() {
describe('#reset', function() { describe('#reset', function() {
it('should reset the "pending" status', function() { it('should reset the "pending" status', function() {
const suite = new privateUnderTest.Suite({}); const suite = new jasmineUnderTest.Suite({});
suite.pend(); suite.pend();
suite.reset(); suite.reset();
expect(suite.doneEvent().status).toBe('passed'); expect(suite.getResult().status).toBe('passed');
}); });
it('should not reset the "pending" status when the suite was excluded', function() { it('should not reset the "pending" status when the suite was excluded', function() {
const suite = new privateUnderTest.Suite({}); const suite = new jasmineUnderTest.Suite({});
suite.exclude(); suite.exclude();
suite.reset(); suite.reset();
expect(suite.doneEvent().status).toBe('pending'); expect(suite.getResult().status).toBe('pending');
}); });
it('should also reset the children', function() { it('should also reset the children', function() {
const suite = new privateUnderTest.Suite({}); const suite = new jasmineUnderTest.Suite({});
const child1 = jasmine.createSpyObj(['reset']); const child1 = jasmine.createSpyObj(['reset']);
const child2 = jasmine.createSpyObj(['reset']); const child2 = jasmine.createSpyObj(['reset']);
suite.addChild(child1); suite.addChild(child1);
@@ -330,12 +328,12 @@ describe('Suite', function() {
}); });
it('should reset the failedExpectations', function() { it('should reset the failedExpectations', function() {
const suite = new privateUnderTest.Suite({}); const suite = new jasmineUnderTest.Suite({});
suite.handleException(new Error()); suite.handleException(new Error());
suite.reset(); suite.reset();
const result = suite.doneEvent(); const result = suite.getResult();
expect(result.status).toBe('passed'); expect(result.status).toBe('passed');
expect(result.failedExpectations).toHaveSize(0); expect(result.failedExpectations).toHaveSize(0);
}); });
@@ -344,7 +342,7 @@ describe('Suite', function() {
describe('#onMultipleDone', function() { describe('#onMultipleDone', function() {
it('reports a special error when it is the top suite', function() { it('reports a special error when it is the top suite', function() {
const onLateError = jasmine.createSpy('onLateError'); const onLateError = jasmine.createSpy('onLateError');
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
onLateError, onLateError,
parentSuite: null parentSuite: null
}); });
@@ -361,7 +359,7 @@ describe('Suite', function() {
it('reports an error including the suite name when it is a normal suite', function() { it('reports an error including the suite name when it is a normal suite', function() {
const onLateError = jasmine.createSpy('onLateError'); const onLateError = jasmine.createSpy('onLateError');
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
onLateError, onLateError,
description: 'the suite', description: 'the suite',
parentSuite: { parentSuite: {
@@ -383,7 +381,7 @@ describe('Suite', function() {
describe('#hasChildWithDescription', function() { describe('#hasChildWithDescription', function() {
it('returns true if there is a child with the given description', function() { it('returns true if there is a child with the given description', function() {
const subject = new privateUnderTest.Suite({}); const subject = new jasmineUnderTest.Suite({});
const description = 'a spec'; const description = 'a spec';
subject.addChild({ description }); subject.addChild({ description });
@@ -391,15 +389,15 @@ describe('Suite', function() {
}); });
it('returns false if there is no child with the given description', function() { it('returns false if there is no child with the given description', function() {
const subject = new privateUnderTest.Suite({}); const subject = new jasmineUnderTest.Suite({});
subject.addChild({ description: 'a different spec' }); subject.addChild({ description: 'a different spec' });
expect(subject.hasChildWithDescription('a spec')).toBeFalse(); expect(subject.hasChildWithDescription('a spec')).toBeFalse();
}); });
it('does not recurse into child suites', function() { it('does not recurse into child suites', function() {
const subject = new privateUnderTest.Suite({}); const subject = new jasmineUnderTest.Suite({});
const childSuite = new privateUnderTest.Suite({}); const childSuite = new jasmineUnderTest.Suite({});
subject.addChild(childSuite); subject.addChild(childSuite);
const description = 'a spec'; const description = 'a spec';
childSuite.addChild(description); childSuite.addChild(description);
@@ -407,62 +405,4 @@ describe('Suite', function() {
expect(subject.hasChildWithDescription('a spec')).toBeFalse(); expect(subject.hasChildWithDescription('a spec')).toBeFalse();
}); });
}); });
describe('#setSuiteProperty', function() {
it('throws if the key is not a string', function() {
const suite = new privateUnderTest.Suite({});
expect(function() {
suite.setSuiteProperty({}, '');
}).toThrowError('Key must be a string');
});
it('throws if the value is not structured-cloneable', function() {
const suite = new privateUnderTest.Suite({});
expect(function() {
suite.setSuiteProperty('k', new Promise(() => {}));
}).toThrowError("Value can't be cloned");
});
it('throws if the value is not JSON-serializable', function() {
const suite = new privateUnderTest.Suite({});
expect(function() {
const v = {};
v.self = v;
suite.setSuiteProperty('k', v);
}).toThrowError("Value can't be cloned");
});
});
describe('#startedEvent', function() {
it('includes only properties that are known before execution', function() {
const topSuite = new privateUnderTest.Suite({});
const parentSuite = new privateUnderTest.Suite({
id: 'suite1',
parentSuite: topSuite,
description: 'a parent suite'
});
const suite = new privateUnderTest.Suite({
id: 'suite2',
parentSuite,
reportedParentSuiteId: parentSuite.id,
description: 'a suite',
filename: 'somefile.js',
getPath() {
return ['a parent suite', 'a spec'];
},
queueableFn: { fn: () => {} }
});
expect(suite.startedEvent()).toEqual({
id: 'suite2',
parentSuiteId: 'suite1',
description: 'a suite',
fullName: 'a parent suite a suite',
filename: 'somefile.js'
});
});
});
}); });
+88 -20
View File
@@ -6,6 +6,9 @@ describe('TreeProcessor', function() {
attrs = attrs || {}; attrs = attrs || {};
this.id = 'node' + nodeNumber++; this.id = 'node' + nodeNumber++;
this.children = attrs.children || []; this.children = attrs.children || [];
this.canBeReentered = function() {
return !attrs.noReenter;
};
this.markedPending = attrs.markedPending || false; this.markedPending = attrs.markedPending || false;
this.sharedUserContext = function() { this.sharedUserContext = function() {
return attrs.userContext || {}; return attrs.userContext || {};
@@ -25,7 +28,7 @@ describe('TreeProcessor', function() {
it('processes a single leaf', function() { it('processes a single leaf', function() {
const leaf = new Leaf(), const leaf = new Leaf(),
processor = new privateUnderTest.TreeProcessor({ processor = new jasmineUnderTest.TreeProcessor({
tree: leaf, tree: leaf,
runnableIds: [leaf.id] runnableIds: [leaf.id]
}); });
@@ -37,7 +40,7 @@ describe('TreeProcessor', function() {
it('processes a single pending leaf', function() { it('processes a single pending leaf', function() {
const leaf = new Leaf({ markedPending: true }), const leaf = new Leaf({ markedPending: true }),
processor = new privateUnderTest.TreeProcessor({ processor = new jasmineUnderTest.TreeProcessor({
tree: leaf, tree: leaf,
runnableIds: [leaf.id] runnableIds: [leaf.id]
}); });
@@ -49,7 +52,7 @@ describe('TreeProcessor', function() {
it('processes a single non-specified leaf', function() { it('processes a single non-specified leaf', function() {
const leaf = new Leaf(), const leaf = new Leaf(),
processor = new privateUnderTest.TreeProcessor({ processor = new jasmineUnderTest.TreeProcessor({
tree: leaf, tree: leaf,
runnableIds: [] runnableIds: []
}); });
@@ -61,7 +64,7 @@ describe('TreeProcessor', function() {
it('processes a single excluded leaf', function() { it('processes a single excluded leaf', function() {
const leaf = new Leaf(), const leaf = new Leaf(),
processor = new privateUnderTest.TreeProcessor({ processor = new jasmineUnderTest.TreeProcessor({
tree: leaf, tree: leaf,
runnableIds: [leaf.id], runnableIds: [leaf.id],
excludeNode: function() { excludeNode: function() {
@@ -77,7 +80,7 @@ describe('TreeProcessor', function() {
it('processes a tree with a single leaf with the root specified', function() { it('processes a tree with a single leaf with the root specified', function() {
const leaf = new Leaf(), const leaf = new Leaf(),
parent = new Node({ children: [leaf] }), parent = new Node({ children: [leaf] }),
processor = new privateUnderTest.TreeProcessor({ processor = new jasmineUnderTest.TreeProcessor({
tree: parent, tree: parent,
runnableIds: [parent.id] runnableIds: [parent.id]
}); });
@@ -92,7 +95,7 @@ describe('TreeProcessor', function() {
it('processes a tree with a single pending leaf, with the root specified', function() { it('processes a tree with a single pending leaf, with the root specified', function() {
const leaf = new Leaf({ markedPending: true }), const leaf = new Leaf({ markedPending: true }),
parent = new Node({ children: [leaf] }), parent = new Node({ children: [leaf] }),
processor = new privateUnderTest.TreeProcessor({ processor = new jasmineUnderTest.TreeProcessor({
tree: parent, tree: parent,
runnableIds: [parent.id] runnableIds: [parent.id]
}); });
@@ -108,7 +111,7 @@ describe('TreeProcessor', function() {
const specified = new Leaf(); const specified = new Leaf();
const nonSpecified = new Leaf(); const nonSpecified = new Leaf();
const root = new Node({ children: [nonSpecified, specified] }); const root = new Node({ children: [nonSpecified, specified] });
const processor = new privateUnderTest.TreeProcessor({ const processor = new jasmineUnderTest.TreeProcessor({
tree: root, tree: root,
runnableIds: [specified.id] runnableIds: [specified.id]
}); });
@@ -125,16 +128,18 @@ describe('TreeProcessor', function() {
const leaf1 = new Leaf(); const leaf1 = new Leaf();
const node = new Node({ children: [leaf1] }); const node = new Node({ children: [leaf1] });
const root = new Node({ children: [node] }); const root = new Node({ children: [node] });
const processor = new privateUnderTest.TreeProcessor({ const processor = new jasmineUnderTest.TreeProcessor({
tree: root, tree: root,
runnableIds: [] runnableIds: []
}); });
const result = processor.processTree(); const result = processor.processTree();
expect(result.childrenOfTopSuite()).toEqual([{ suite: node }]); expect(result.childrenOfTopSuite()).toEqual([
{ suite: node, segmentNumber: 0 }
]);
expect(result.isExcluded(node)).toEqual(true); expect(result.isExcluded(node)).toEqual(true);
expect(result.childrenOfSuite(node)).toEqual([{ spec: leaf1 }]); expect(result.childrenOfSuiteSegment(node, 0)).toEqual([{ spec: leaf1 }]);
expect(result.isExcluded(node)).toEqual(true); expect(result.isExcluded(node)).toEqual(true);
}); });
@@ -153,7 +158,7 @@ describe('TreeProcessor', function() {
children: [childless, pendingNode] children: [childless, pendingNode]
}), }),
root = new Node({ children: [parent, parentOfPendings] }), root = new Node({ children: [parent, parentOfPendings] }),
processor = new privateUnderTest.TreeProcessor({ processor = new jasmineUnderTest.TreeProcessor({
tree: root, tree: root,
runnableIds: [root.id] runnableIds: [root.id]
}); });
@@ -162,36 +167,99 @@ describe('TreeProcessor', function() {
expect(result.isExcluded(parent)).toEqual(false); expect(result.isExcluded(parent)).toEqual(false);
expect(result.childrenOfTopSuite()).toEqual([ expect(result.childrenOfTopSuite()).toEqual([
{ suite: parent }, { suite: parent, segmentNumber: 0 },
{ suite: parentOfPendings } { suite: parentOfPendings, segmentNumber: 0 }
]); ]);
expect(result.isExcluded(parentOfPendings)).toEqual(true); expect(result.isExcluded(parentOfPendings)).toEqual(true);
expect(result.childrenOfSuite(parentOfPendings)).toEqual([ expect(result.childrenOfSuiteSegment(parentOfPendings, 0)).toEqual([
{ suite: childless }, { suite: childless, segmentNumber: 0 },
{ suite: pendingNode } { suite: pendingNode, segmentNumber: 0 }
]); ]);
expect(result.isExcluded(childless)).toEqual(true); expect(result.isExcluded(childless)).toEqual(true);
expect(result.childrenOfSuite(childless)).toEqual([]); expect(result.childrenOfSuiteSegment(childless, 0)).toEqual([]);
expect(result.isExcluded(pendingLeaf)).toEqual(false); expect(result.isExcluded(pendingLeaf)).toEqual(false);
expect(result.isExcluded(executableLeaf)).toEqual(false); expect(result.isExcluded(executableLeaf)).toEqual(false);
expect(result.isExcluded(parent)).toEqual(false); expect(result.isExcluded(parent)).toEqual(false);
expect(result.childrenOfSuite(parent)).toEqual([ expect(result.childrenOfSuiteSegment(parent, 0)).toEqual([
{ spec: pendingLeaf }, { spec: pendingLeaf },
{ spec: executableLeaf } { spec: executableLeaf }
]); ]);
expect(result.isExcluded(pendingNode)).toEqual(true); expect(result.isExcluded(pendingNode)).toEqual(true);
expect(result.childrenOfSuite(pendingNode)).toEqual([ expect(result.childrenOfSuiteSegment(pendingNode, 0)).toEqual([
{ spec: childOfPending } { spec: childOfPending }
]); ]);
expect(result.isExcluded(childOfPending)).toEqual(false); expect(result.isExcluded(childOfPending)).toEqual(false);
}); });
it('throws if the specified order would re-enter a node that does not allow re-entry', function() {
const leaf1 = new Leaf(),
leaf2 = new Leaf(),
leaf3 = new Leaf(),
reentered = new Node({ noReenter: true, children: [leaf1, leaf2] }),
root = new Node({ children: [reentered, leaf3] }),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf1.id, leaf3.id, leaf2.id]
});
expect(function() {
processor.processTree();
}).toThrowError(
'Invalid order: would cause a beforeAll or afterAll to be run multiple times'
);
});
it('does not throw if a node being re-entered allows re-entry', function() {
const leaf1 = new Leaf();
const leaf2 = new Leaf();
const leaf3 = new Leaf();
const reentered = new Node({ children: [leaf1, leaf2] });
const root = new Node({ children: [reentered, leaf3] });
const processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf1.id, leaf3.id, leaf2.id]
});
const env = jasmineUnderTest.getEnv();
spyOn(env, 'deprecated');
processor.processTree();
expect(env.deprecated).toHaveBeenCalledWith(
'The specified spec/suite order splits up a suite, running unrelated specs in the middle of it. This will become an error in a future release.'
);
});
it("does not throw if a node which can't be re-entered is only entered once", function() {
const leaf1 = new Leaf(),
leaf2 = new Leaf(),
leaf3 = new Leaf(),
noReentry = new Node({ noReenter: true }),
root = new Node({ children: [noReentry] }),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf2.id, leaf1.id, leaf3.id]
});
processor.processTree();
});
it("does not throw if a node which can't be re-entered is run directly", function() {
const noReentry = new Node({ noReenter: true }),
root = new Node({ children: [noReentry] }),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [root.id]
});
processor.processTree();
});
it('orders children according to orderChildren when specified', function() { it('orders children according to orderChildren when specified', function() {
const leaf1 = new Leaf(); const leaf1 = new Leaf();
const leaf2 = new Leaf(); const leaf2 = new Leaf();
@@ -220,7 +288,7 @@ describe('TreeProcessor', function() {
] ]
}); });
const runQueue = jasmine.createSpy('runQueue'); const runQueue = jasmine.createSpy('runQueue');
const processor = new privateUnderTest.TreeProcessor({ const processor = new jasmineUnderTest.TreeProcessor({
tree: root, tree: root,
runnableIds: [root.id], runnableIds: [root.id],
runQueue, runQueue,
+58 -60
View File
@@ -2,7 +2,7 @@ describe('TreeRunner', function() {
describe('spec execution', function() { describe('spec execution', function() {
it('starts the timer, reports the spec started, and updates run state at the start of the queue', async function() { it('starts the timer, reports the spec started, and updates run state at the start of the queue', async function() {
const timer = jasmine.createSpyObj('timer', ['start']); const timer = jasmine.createSpyObj('timer', ['start']);
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
id: 'spec1', id: 'spec1',
queueableFn: {}, queueableFn: {},
timer timer
@@ -28,9 +28,7 @@ describe('TreeRunner', function() {
spec.id, spec.id,
spec.parentSuiteId spec.parentSuiteId
); );
expect(reportDispatcher.specStarted).toHaveBeenCalledWith( expect(reportDispatcher.specStarted).toHaveBeenCalledWith(spec.result);
spec.startedEvent()
);
await Promise.resolve(); await Promise.resolve();
expect(reportDispatcher.specStarted).toHaveBeenCalledBefore(next); expect(reportDispatcher.specStarted).toHaveBeenCalledBefore(next);
await expectAsync(executePromise).toBePending(); await expectAsync(executePromise).toBePending();
@@ -38,7 +36,7 @@ describe('TreeRunner', function() {
it('stops the timer, updates run state, and reports the spec done at the end of the queue', async function() { it('stops the timer, updates run state, and reports the spec done at the end of the queue', async function() {
const timer = jasmine.createSpyObj('timer', ['start', 'elapsed']); const timer = jasmine.createSpyObj('timer', ['start', 'elapsed']);
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
id: 'spec1', id: 'spec1',
queueableFn: {}, queueableFn: {},
timer timer
@@ -63,8 +61,8 @@ describe('TreeRunner', function() {
expect(currentRunableTracker.currentSpec()).toBeFalsy(); expect(currentRunableTracker.currentSpec()).toBeFalsy();
expect(runableResources.clearForRunable).toHaveBeenCalledWith(spec.id); expect(runableResources.clearForRunable).toHaveBeenCalledWith(spec.id);
expect(reportDispatcher.specDone).toHaveBeenCalledWith(spec.doneEvent()); expect(reportDispatcher.specDone).toHaveBeenCalledWith(spec.result);
expect(spec.doneEvent().duration).toEqual('the elapsed time'); expect(spec.result.duration).toEqual('the elapsed time');
expect(spec.reportedDone).toEqual(true); expect(spec.reportedDone).toEqual(true);
await Promise.resolve(); await Promise.resolve();
await Promise.resolve(); await Promise.resolve();
@@ -82,7 +80,7 @@ describe('TreeRunner', function() {
expect(after).not.toHaveBeenCalled(); expect(after).not.toHaveBeenCalled();
}) })
}; };
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: queueableFn, queueableFn: queueableFn,
beforeAndAfterFns: function() { beforeAndAfterFns: function() {
return { befores: [before], afters: [after] }; return { befores: [before], afters: [after] };
@@ -106,7 +104,7 @@ describe('TreeRunner', function() {
spec.pend(); spec.pend();
} }
}; };
spec = new privateUnderTest.Spec({ queueableFn }); spec = new jasmineUnderTest.Spec({ queueableFn });
const { runQueue, suiteRunQueueArgs } = runSingleSpecSuite(spec); const { runQueue, suiteRunQueueArgs } = runSingleSpecSuite(spec);
suiteRunQueueArgs.queueableFns[0].fn(); suiteRunQueueArgs.queueableFns[0].fn();
@@ -116,8 +114,8 @@ describe('TreeRunner', function() {
expect(specRunQueueArgs.queueableFns[1]).toEqual(queueableFn); expect(specRunQueueArgs.queueableFns[1]).toEqual(queueableFn);
queueableFn.fn(); queueableFn.fn();
expect(spec.doneEvent().status).toEqual('pending'); expect(spec.getResult().status).toEqual('pending');
expect(spec.doneEvent().pendingReason).toEqual(''); expect(spec.getResult().pendingReason).toEqual('');
}); });
it('marks specs pending at runtime with a message', function() { it('marks specs pending at runtime with a message', function() {
@@ -127,7 +125,7 @@ describe('TreeRunner', function() {
spec.pend('some reason'); spec.pend('some reason');
} }
}; };
spec = new privateUnderTest.Spec({ queueableFn }); spec = new jasmineUnderTest.Spec({ queueableFn });
const { runQueue, suiteRunQueueArgs } = runSingleSpecSuite(spec); const { runQueue, suiteRunQueueArgs } = runSingleSpecSuite(spec);
suiteRunQueueArgs.queueableFns[0].fn(); suiteRunQueueArgs.queueableFns[0].fn();
@@ -137,12 +135,12 @@ describe('TreeRunner', function() {
expect(specRunQueueArgs.queueableFns[1]).toEqual(queueableFn); expect(specRunQueueArgs.queueableFns[1]).toEqual(queueableFn);
queueableFn.fn(); queueableFn.fn();
expect(spec.doneEvent().status).toEqual('pending'); expect(spec.getResult().status).toEqual('pending');
expect(spec.doneEvent().pendingReason).toEqual('some reason'); expect(spec.getResult().pendingReason).toEqual('some reason');
}); });
it('passes failSpecWithNoExp to Spec#executionFinished', async function() { it('passes failSpecWithNoExp to Spec#executionFinished', async function() {
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
id: 'spec1', id: 'spec1',
queueableFn: {} queueableFn: {}
}); });
@@ -168,8 +166,8 @@ describe('TreeRunner', function() {
describe('Suite execution', function() { describe('Suite execution', function() {
it('reports the duration of the suite', async function() { it('reports the duration of the suite', async function() {
const timer = jasmine.createSpyObj('timer', ['start', 'elapsed']); const timer = jasmine.createSpyObj('timer', ['start', 'elapsed']);
const topSuite = new privateUnderTest.Suite({ id: 'topSuite' }); const topSuite = new jasmineUnderTest.Suite({ id: 'topSuite' });
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
id: 'suite1', id: 'suite1',
parentSuite: topSuite, parentSuite: topSuite,
timer timer
@@ -180,7 +178,7 @@ describe('TreeRunner', function() {
childrenOfTopSuite() { childrenOfTopSuite() {
return [{ suite }]; return [{ suite }];
}, },
childrenOfSuite() { childrenOfSuiteSegment() {
return []; return [];
}, },
isExcluded() { isExcluded() {
@@ -189,13 +187,13 @@ describe('TreeRunner', function() {
}; };
const runQueue = jasmine.createSpy('runQueue'); const runQueue = jasmine.createSpy('runQueue');
const reportDispatcher = mockReportDispatcher(); const reportDispatcher = mockReportDispatcher();
const subject = new privateUnderTest.TreeRunner({ const subject = new jasmineUnderTest.TreeRunner({
executionTree, executionTree,
runQueue, runQueue,
globalErrors: mockGlobalErrors(), globalErrors: mockGlobalErrors(),
runableResources: mockRunableResources(), runableResources: mockRunableResources(),
reportDispatcher, reportDispatcher,
currentRunableTracker: new privateUnderTest.CurrentRunableTracker(), currentRunableTracker: new jasmineUnderTest.CurrentRunableTracker(),
getConfig() { getConfig() {
return {}; return {};
}, },
@@ -218,7 +216,7 @@ describe('TreeRunner', function() {
timer.elapsed.and.returnValue('the duration'); timer.elapsed.and.returnValue('the duration');
suiteRunQueueOpts.onComplete(); suiteRunQueueOpts.onComplete();
expect(timer.elapsed).toHaveBeenCalled(); expect(timer.elapsed).toHaveBeenCalled();
const result = suite.doneEvent(); const result = suite.getResult();
expect(result.duration).toEqual('the duration'); expect(result.duration).toEqual('the duration');
expect(reportDispatcher.suiteDone).toHaveBeenCalledWith(result); expect(reportDispatcher.suiteDone).toHaveBeenCalledWith(result);
@@ -226,12 +224,12 @@ describe('TreeRunner', function() {
}); });
it('returns false if a suite failed', async function() { it('returns false if a suite failed', async function() {
const topSuite = new privateUnderTest.Suite({ id: 'topSuite' }); const topSuite = new jasmineUnderTest.Suite({ id: 'topSuite' });
const failingSuite = new privateUnderTest.Suite({ const failingSuite = new jasmineUnderTest.Suite({
id: 'failingSuite', id: 'failingSuite',
parentSuite: topSuite parentSuite: topSuite
}); });
const passingSuite = new privateUnderTest.Suite({ const passingSuite = new jasmineUnderTest.Suite({
id: 'passingSuite', id: 'passingSuite',
parentSuite: topSuite parentSuite: topSuite
}); });
@@ -240,7 +238,7 @@ describe('TreeRunner', function() {
childrenOfTopSuite() { childrenOfTopSuite() {
return [{ suite: failingSuite }, { suite: passingSuite }]; return [{ suite: failingSuite }, { suite: passingSuite }];
}, },
childrenOfSuite() { childrenOfSuiteSegment() {
return []; return [];
}, },
isExcluded() { isExcluded() {
@@ -249,13 +247,13 @@ describe('TreeRunner', function() {
}; };
const runQueue = jasmine.createSpy('runQueue'); const runQueue = jasmine.createSpy('runQueue');
const reportDispatcher = mockReportDispatcher(); const reportDispatcher = mockReportDispatcher();
const subject = new privateUnderTest.TreeRunner({ const subject = new jasmineUnderTest.TreeRunner({
executionTree, executionTree,
runQueue, runQueue,
globalErrors: mockGlobalErrors(), globalErrors: mockGlobalErrors(),
runableResources: mockRunableResources(), runableResources: mockRunableResources(),
reportDispatcher, reportDispatcher,
currentRunableTracker: new privateUnderTest.CurrentRunableTracker(), currentRunableTracker: new jasmineUnderTest.CurrentRunableTracker(),
getConfig() { getConfig() {
return {}; return {};
}, },
@@ -290,13 +288,13 @@ describe('TreeRunner', function() {
}); });
it('reports children when there is a beforeAll failure', async function() { it('reports children when there is a beforeAll failure', async function() {
const topSuite = new privateUnderTest.Suite({ id: 'topSuite' }); const topSuite = new jasmineUnderTest.Suite({ id: 'topSuite' });
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
id: 'suite', id: 'suite',
parentSuite: topSuite parentSuite: topSuite
}); });
suite.beforeAll({ fn() {} }); suite.beforeAll({ fn() {} });
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
id: 'spec', id: 'spec',
parentSuite: suite, parentSuite: suite,
queueableFn: { fn() {} } queueableFn: { fn() {} }
@@ -308,7 +306,7 @@ describe('TreeRunner', function() {
childrenOfTopSuite() { childrenOfTopSuite() {
return [{ suite }]; return [{ suite }];
}, },
childrenOfSuite() { childrenOfSuiteSegment() {
return [{ spec }]; return [{ spec }];
}, },
isExcluded() { isExcluded() {
@@ -320,13 +318,13 @@ describe('TreeRunner', function() {
const reportChildrenOfBeforeAllFailure = jasmine const reportChildrenOfBeforeAllFailure = jasmine
.createSpy('reportChildrenOfBeforeAllFailure') .createSpy('reportChildrenOfBeforeAllFailure')
.and.returnValue(Promise.resolve()); .and.returnValue(Promise.resolve());
const subject = new privateUnderTest.TreeRunner({ const subject = new jasmineUnderTest.TreeRunner({
executionTree, executionTree,
runQueue, runQueue,
globalErrors: mockGlobalErrors(), globalErrors: mockGlobalErrors(),
runableResources: mockRunableResources(), runableResources: mockRunableResources(),
reportDispatcher, reportDispatcher,
currentRunableTracker: new privateUnderTest.CurrentRunableTracker(), currentRunableTracker: new jasmineUnderTest.CurrentRunableTracker(),
reportChildrenOfBeforeAllFailure, reportChildrenOfBeforeAllFailure,
getConfig() { getConfig() {
return {}; return {};
@@ -356,12 +354,12 @@ describe('TreeRunner', function() {
}); });
it('throws if the wrong suite is completed', async function() { it('throws if the wrong suite is completed', async function() {
const topSuite = new privateUnderTest.Suite({ id: 'topSuite' }); const topSuite = new jasmineUnderTest.Suite({ id: 'topSuite' });
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
id: 'suite', id: 'suite',
parentSuite: topSuite parentSuite: topSuite
}); });
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
id: 'spec', id: 'spec',
parentSuite: suite, parentSuite: suite,
queueableFn: { fn() {} } queueableFn: { fn() {} }
@@ -371,7 +369,7 @@ describe('TreeRunner', function() {
childrenOfTopSuite() { childrenOfTopSuite() {
return [{ suite }]; return [{ suite }];
}, },
childrenOfSuite() { childrenOfSuiteSegment() {
return [{ spec }]; return [{ spec }];
}, },
isExcluded() { isExcluded() {
@@ -380,13 +378,13 @@ describe('TreeRunner', function() {
}; };
const runQueue = jasmine.createSpy('runQueue'); const runQueue = jasmine.createSpy('runQueue');
const reportDispatcher = mockReportDispatcher(); const reportDispatcher = mockReportDispatcher();
const subject = new privateUnderTest.TreeRunner({ const subject = new jasmineUnderTest.TreeRunner({
executionTree, executionTree,
runQueue, runQueue,
globalErrors: mockGlobalErrors(), globalErrors: mockGlobalErrors(),
runableResources: mockRunableResources(), runableResources: mockRunableResources(),
reportDispatcher, reportDispatcher,
currentRunableTracker: new privateUnderTest.CurrentRunableTracker(), currentRunableTracker: new jasmineUnderTest.CurrentRunableTracker(),
getConfig() { getConfig() {
return {}; return {};
}, },
@@ -412,7 +410,7 @@ describe('TreeRunner', function() {
}); });
it('does not remove before and after fns from the top suite', async function() { it('does not remove before and after fns from the top suite', async function() {
const topSuite = new privateUnderTest.Suite({ id: 'topSuite' }); const topSuite = new jasmineUnderTest.Suite({ id: 'topSuite' });
spyOn(topSuite, 'cleanupBeforeAfter'); spyOn(topSuite, 'cleanupBeforeAfter');
const executionTree = { const executionTree = {
topSuite, topSuite,
@@ -424,13 +422,13 @@ describe('TreeRunner', function() {
} }
}; };
const runQueue = jasmine.createSpy('runQueue'); const runQueue = jasmine.createSpy('runQueue');
const subject = new privateUnderTest.TreeRunner({ const subject = new jasmineUnderTest.TreeRunner({
executionTree, executionTree,
runQueue, runQueue,
globalErrors: mockGlobalErrors(), globalErrors: mockGlobalErrors(),
runableResources: mockRunableResources(), runableResources: mockRunableResources(),
reportDispatcher: mockReportDispatcher(), reportDispatcher: mockReportDispatcher(),
currentRunableTracker: new privateUnderTest.CurrentRunableTracker(), currentRunableTracker: new jasmineUnderTest.CurrentRunableTracker(),
getConfig() { getConfig() {
return {}; return {};
} }
@@ -460,7 +458,7 @@ describe('TreeRunner', function() {
expect(after).not.toHaveBeenCalled(); expect(after).not.toHaveBeenCalled();
}) })
}; };
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn, queueableFn,
beforeAndAfterFns: function() { beforeAndAfterFns: function() {
return { befores: [before], afters: [after] }; return { befores: [before], afters: [after] };
@@ -504,13 +502,13 @@ describe('TreeRunner', function() {
}); });
it('works for beforeAll when the detectLateRejectionHandling param is true', async function() { it('works for beforeAll when the detectLateRejectionHandling param is true', async function() {
const topSuite = new privateUnderTest.Suite({ id: 'topSuite' }); const topSuite = new jasmineUnderTest.Suite({ id: 'topSuite' });
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
id: 'suite', id: 'suite',
parentSuite: topSuite parentSuite: topSuite
}); });
suite.beforeAll(function() {}); suite.beforeAll(function() {});
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn() {} }, queueableFn: { fn() {} },
parentSuite: suite parentSuite: suite
}); });
@@ -519,7 +517,7 @@ describe('TreeRunner', function() {
childrenOfTopSuite() { childrenOfTopSuite() {
return [{ suite }]; return [{ suite }];
}, },
childrenOfSuite() { childrenOfSuiteSegment() {
return [{ spec }]; return [{ spec }];
}, },
isExcluded() { isExcluded() {
@@ -530,14 +528,14 @@ describe('TreeRunner', function() {
const reportDispatcher = mockReportDispatcher(); const reportDispatcher = mockReportDispatcher();
const globalErrors = mockGlobalErrors(); const globalErrors = mockGlobalErrors();
const setTimeout = jasmine.createSpy('setTimeout'); const setTimeout = jasmine.createSpy('setTimeout');
const subject = new privateUnderTest.TreeRunner({ const subject = new jasmineUnderTest.TreeRunner({
executionTree, executionTree,
runQueue, runQueue,
globalErrors, globalErrors,
runableResources: mockRunableResources(), runableResources: mockRunableResources(),
reportDispatcher, reportDispatcher,
setTimeout, setTimeout,
currentRunableTracker: new privateUnderTest.CurrentRunableTracker(), currentRunableTracker: new jasmineUnderTest.CurrentRunableTracker(),
getConfig() { getConfig() {
return { detectLateRejectionHandling: true }; return { detectLateRejectionHandling: true };
}, },
@@ -573,13 +571,13 @@ describe('TreeRunner', function() {
}); });
it('works for afterAll when the detectLateRejectionHandling param is true', async function() { it('works for afterAll when the detectLateRejectionHandling param is true', async function() {
const topSuite = new privateUnderTest.Suite({ id: 'topSuite' }); const topSuite = new jasmineUnderTest.Suite({ id: 'topSuite' });
const suite = new privateUnderTest.Suite({ const suite = new jasmineUnderTest.Suite({
id: 'suite', id: 'suite',
parentSuite: topSuite parentSuite: topSuite
}); });
suite.afterAll(function() {}); suite.afterAll(function() {});
const spec = new privateUnderTest.Spec({ const spec = new jasmineUnderTest.Spec({
queueableFn: { fn() {} }, queueableFn: { fn() {} },
parentSuite: suite parentSuite: suite
}); });
@@ -588,7 +586,7 @@ describe('TreeRunner', function() {
childrenOfTopSuite() { childrenOfTopSuite() {
return [{ suite }]; return [{ suite }];
}, },
childrenOfSuite() { childrenOfSuiteSegment() {
return [{ spec }]; return [{ spec }];
}, },
isExcluded() { isExcluded() {
@@ -599,14 +597,14 @@ describe('TreeRunner', function() {
const reportDispatcher = mockReportDispatcher(); const reportDispatcher = mockReportDispatcher();
const globalErrors = mockGlobalErrors(); const globalErrors = mockGlobalErrors();
const setTimeout = jasmine.createSpy('setTimeout'); const setTimeout = jasmine.createSpy('setTimeout');
const subject = new privateUnderTest.TreeRunner({ const subject = new jasmineUnderTest.TreeRunner({
executionTree, executionTree,
runQueue, runQueue,
globalErrors, globalErrors,
runableResources: mockRunableResources(), runableResources: mockRunableResources(),
reportDispatcher, reportDispatcher,
setTimeout, setTimeout,
currentRunableTracker: new privateUnderTest.CurrentRunableTracker(), currentRunableTracker: new jasmineUnderTest.CurrentRunableTracker(),
getConfig() { getConfig() {
return { detectLateRejectionHandling: true }; return { detectLateRejectionHandling: true };
}, },
@@ -645,7 +643,7 @@ describe('TreeRunner', function() {
function runSingleSpecSuite(spec, optionalConfig) { function runSingleSpecSuite(spec, optionalConfig) {
const topSuiteId = 'suite1'; const topSuiteId = 'suite1';
spec.parentSuiteId = topSuiteId; spec.parentSuiteId = topSuiteId;
const topSuite = new privateUnderTest.Suite({ id: topSuiteId }); const topSuite = new jasmineUnderTest.Suite({ id: topSuiteId });
topSuite.addChild(spec); topSuite.addChild(spec);
const executionTree = { const executionTree = {
topSuite, topSuite,
@@ -661,8 +659,8 @@ describe('TreeRunner', function() {
const runableResources = mockRunableResources(); const runableResources = mockRunableResources();
const globalErrors = mockGlobalErrors(); const globalErrors = mockGlobalErrors();
const setTimeout = jasmine.createSpy('setTimeout'); const setTimeout = jasmine.createSpy('setTimeout');
const currentRunableTracker = new privateUnderTest.CurrentRunableTracker(); const currentRunableTracker = new jasmineUnderTest.CurrentRunableTracker();
const subject = new privateUnderTest.TreeRunner({ const subject = new jasmineUnderTest.TreeRunner({
executionTree, executionTree,
runQueue, runQueue,
globalErrors, globalErrors,
@@ -696,10 +694,10 @@ describe('TreeRunner', function() {
function mockReportDispatcher() { function mockReportDispatcher() {
const reportDispatcher = jasmine.createSpyObj( const reportDispatcher = jasmine.createSpyObj(
'reportDispatcher', 'reportDispatcher',
privateUnderTest.reporterEvents jasmineUnderTest.reporterEvents
); );
for (const k of privateUnderTest.reporterEvents) { for (const k of jasmineUnderTest.reporterEvents) {
reportDispatcher[k].and.returnValue(Promise.resolve()); reportDispatcher[k].and.returnValue(Promise.resolve());
} }
+5 -5
View File
@@ -1,6 +1,6 @@
describe('UserContext', function() { describe('UserContext', function() {
it('Behaves just like an plain object', function() { it('Behaves just like an plain object', function() {
const context = new privateUnderTest.UserContext(), const context = new jasmineUnderTest.UserContext(),
properties = []; properties = [];
for (const prop in context) { for (const prop in context) {
@@ -15,9 +15,9 @@ describe('UserContext', function() {
describe('.fromExisting', function() { describe('.fromExisting', function() {
describe('when using an already built context as model', function() { describe('when using an already built context as model', function() {
beforeEach(function() { beforeEach(function() {
this.context = new privateUnderTest.UserContext(); this.context = new jasmineUnderTest.UserContext();
this.context.key = 'value'; this.context.key = 'value';
this.cloned = privateUnderTest.UserContext.fromExisting(this.context); this.cloned = jasmineUnderTest.UserContext.fromExisting(this.context);
}); });
it('returns a cloned object', function() { it('returns a cloned object', function() {
@@ -34,7 +34,7 @@ describe('UserContext', function() {
this.context = {}; this.context = {};
this.value = 'value'; this.value = 'value';
this.context.key = this.value; this.context.key = this.value;
this.cloned = privateUnderTest.UserContext.fromExisting(this.context); this.cloned = jasmineUnderTest.UserContext.fromExisting(this.context);
}); });
it('returns an object with the same attributes', function() { it('returns an object with the same attributes', function() {
@@ -46,7 +46,7 @@ describe('UserContext', function() {
}); });
it('returns an UserContext', function() { it('returns an UserContext', function() {
expect(this.cloned.constructor).toBe(privateUnderTest.UserContext); expect(this.cloned.constructor).toBe(jasmineUnderTest.UserContext);
}); });
}); });
}); });
+48 -50
View File
@@ -1,33 +1,33 @@
describe('util', function() { describe('util', function() {
describe('isArray', function() { describe('isArray_', function() {
it('should return true if the argument is an array', function() { it('should return true if the argument is an array', function() {
expect(privateUnderTest.isArray([])).toBe(true); expect(jasmineUnderTest.isArray_([])).toBe(true);
expect(privateUnderTest.isArray(['a'])).toBe(true); expect(jasmineUnderTest.isArray_(['a'])).toBe(true);
}); });
it('should return false if the argument is not an array', function() { it('should return false if the argument is not an array', function() {
expect(privateUnderTest.isArray(undefined)).toBe(false); expect(jasmineUnderTest.isArray_(undefined)).toBe(false);
expect(privateUnderTest.isArray({})).toBe(false); expect(jasmineUnderTest.isArray_({})).toBe(false);
expect(privateUnderTest.isArray(function() {})).toBe(false); expect(jasmineUnderTest.isArray_(function() {})).toBe(false);
expect(privateUnderTest.isArray('foo')).toBe(false); expect(jasmineUnderTest.isArray_('foo')).toBe(false);
expect(privateUnderTest.isArray(5)).toBe(false); expect(jasmineUnderTest.isArray_(5)).toBe(false);
expect(privateUnderTest.isArray(null)).toBe(false); expect(jasmineUnderTest.isArray_(null)).toBe(false);
}); });
}); });
describe('isObject', function() { describe('isObject_', function() {
it('should return true if the argument is an object', function() { it('should return true if the argument is an object', function() {
expect(privateUnderTest.isObject({})).toBe(true); expect(jasmineUnderTest.isObject_({})).toBe(true);
expect(privateUnderTest.isObject({ an: 'object' })).toBe(true); expect(jasmineUnderTest.isObject_({ an: 'object' })).toBe(true);
}); });
it('should return false if the argument is not an object', function() { it('should return false if the argument is not an object', function() {
expect(privateUnderTest.isObject(undefined)).toBe(false); expect(jasmineUnderTest.isObject_(undefined)).toBe(false);
expect(privateUnderTest.isObject([])).toBe(false); expect(jasmineUnderTest.isObject_([])).toBe(false);
expect(privateUnderTest.isObject(function() {})).toBe(false); expect(jasmineUnderTest.isObject_(function() {})).toBe(false);
expect(privateUnderTest.isObject('foo')).toBe(false); expect(jasmineUnderTest.isObject_('foo')).toBe(false);
expect(privateUnderTest.isObject(5)).toBe(false); expect(jasmineUnderTest.isObject_(5)).toBe(false);
expect(privateUnderTest.isObject(null)).toBe(false); expect(jasmineUnderTest.isObject_(null)).toBe(false);
}); });
}); });
@@ -45,121 +45,119 @@ describe('util', function() {
describe('isPromise', function() { describe('isPromise', function() {
it('should return true when passed a native promise', function() { it('should return true when passed a native promise', function() {
expect(privateUnderTest.isPromise(mockNativePromise)).toBe(true); expect(jasmineUnderTest.isPromise(mockNativePromise)).toBe(true);
}); });
it('should return false for promise like objects', function() { it('should return false for promise like objects', function() {
expect(privateUnderTest.isPromise(mockPromiseLikeObject)).toBe(false); expect(jasmineUnderTest.isPromise(mockPromiseLikeObject)).toBe(false);
}); });
it('should return false for strings', function() { it('should return false for strings', function() {
expect(privateUnderTest.isPromise('hello')).toBe(false); expect(jasmineUnderTest.isPromise('hello')).toBe(false);
}); });
it('should return false for numbers', function() { it('should return false for numbers', function() {
expect(privateUnderTest.isPromise(3)).toBe(false); expect(jasmineUnderTest.isPromise(3)).toBe(false);
}); });
it('should return false for null', function() { it('should return false for null', function() {
expect(privateUnderTest.isPromise(null)).toBe(false); expect(jasmineUnderTest.isPromise(null)).toBe(false);
}); });
it('should return false for undefined', function() { it('should return false for undefined', function() {
expect(privateUnderTest.isPromise(undefined)).toBe(false); expect(jasmineUnderTest.isPromise(undefined)).toBe(false);
}); });
it('should return false for arrays', function() { it('should return false for arrays', function() {
expect(privateUnderTest.isPromise([])).toBe(false); expect(jasmineUnderTest.isPromise([])).toBe(false);
}); });
it('should return false for objects', function() { it('should return false for objects', function() {
expect(privateUnderTest.isPromise({})).toBe(false); expect(jasmineUnderTest.isPromise({})).toBe(false);
}); });
it('should return false for boolean values', function() { it('should return false for boolean values', function() {
expect(privateUnderTest.isPromise(true)).toBe(false); expect(jasmineUnderTest.isPromise(true)).toBe(false);
}); });
}); });
describe('isPromiseLike', function() { describe('isPromiseLike', function() {
it('should return true when passed a native promise', function() { it('should return true when passed a native promise', function() {
expect(privateUnderTest.isPromiseLike(mockNativePromise)).toBe(true); expect(jasmineUnderTest.isPromiseLike(mockNativePromise)).toBe(true);
}); });
it('should return true for promise like objects', function() { it('should return true for promise like objects', function() {
expect(privateUnderTest.isPromiseLike(mockPromiseLikeObject)).toBe( expect(jasmineUnderTest.isPromiseLike(mockPromiseLikeObject)).toBe(
true true
); );
}); });
it('should return false if then is not a function', function() { it('should return false if then is not a function', function() {
expect( expect(
privateUnderTest.isPromiseLike({ jasmineUnderTest.isPromiseLike({ then: { its: 'Not a function :O' } })
then: { its: 'Not a function :O' }
})
).toBe(false); ).toBe(false);
}); });
it('should return false for strings', function() { it('should return false for strings', function() {
expect(privateUnderTest.isPromiseLike('hello')).toBe(false); expect(jasmineUnderTest.isPromiseLike('hello')).toBe(false);
}); });
it('should return false for numbers', function() { it('should return false for numbers', function() {
expect(privateUnderTest.isPromiseLike(3)).toBe(false); expect(jasmineUnderTest.isPromiseLike(3)).toBe(false);
}); });
it('should return false for null', function() { it('should return false for null', function() {
expect(privateUnderTest.isPromiseLike(null)).toBe(false); expect(jasmineUnderTest.isPromiseLike(null)).toBe(false);
}); });
it('should return false for undefined', function() { it('should return false for undefined', function() {
expect(privateUnderTest.isPromiseLike(undefined)).toBe(false); expect(jasmineUnderTest.isPromiseLike(undefined)).toBe(false);
}); });
it('should return false for arrays', function() { it('should return false for arrays', function() {
expect(privateUnderTest.isPromiseLike([])).toBe(false); expect(jasmineUnderTest.isPromiseLike([])).toBe(false);
}); });
it('should return false for objects', function() { it('should return false for objects', function() {
expect(privateUnderTest.isPromiseLike({})).toBe(false); expect(jasmineUnderTest.isPromiseLike({})).toBe(false);
}); });
it('should return false for boolean values', function() { it('should return false for boolean values', function() {
expect(privateUnderTest.isPromiseLike(true)).toBe(false); expect(jasmineUnderTest.isPromiseLike(true)).toBe(false);
}); });
}); });
}); });
describe('cloneArgs', function() { describe('cloneArgs', function() {
it('clones primitives as-is', function() { it('clones primitives as-is', function() {
expect(privateUnderTest.util.cloneArgs([true, false])).toEqual([ expect(jasmineUnderTest.util.cloneArgs([true, false])).toEqual([
true, true,
false false
]); ]);
expect(privateUnderTest.util.cloneArgs([0, 1])).toEqual([0, 1]); expect(jasmineUnderTest.util.cloneArgs([0, 1])).toEqual([0, 1]);
expect(privateUnderTest.util.cloneArgs(['str'])).toEqual(['str']); expect(jasmineUnderTest.util.cloneArgs(['str'])).toEqual(['str']);
}); });
it('clones Regexp objects as-is', function() { it('clones Regexp objects as-is', function() {
const regex = /match/; const regex = /match/;
expect(privateUnderTest.util.cloneArgs([regex])).toEqual([regex]); expect(jasmineUnderTest.util.cloneArgs([regex])).toEqual([regex]);
}); });
it('clones Date objects as-is', function() { it('clones Date objects as-is', function() {
const date = new Date(2022, 1, 1); const date = new Date(2022, 1, 1);
expect(privateUnderTest.util.cloneArgs([date])).toEqual([date]); expect(jasmineUnderTest.util.cloneArgs([date])).toEqual([date]);
}); });
it('clones null and undefined', function() { it('clones null and undefined', function() {
expect(privateUnderTest.util.cloneArgs([null])).toEqual([null]); expect(jasmineUnderTest.util.cloneArgs([null])).toEqual([null]);
expect(privateUnderTest.util.cloneArgs([undefined])).toEqual([undefined]); expect(jasmineUnderTest.util.cloneArgs([undefined])).toEqual([undefined]);
}); });
}); });
describe('getPropertyDescriptor', function() { describe('getPropertyDescriptor', function() {
it('get property descriptor from object', function() { it('get property descriptor from object', function() {
const obj = { prop: 1 }, const obj = { prop: 1 },
actual = privateUnderTest.util.getPropertyDescriptor(obj, 'prop'), actual = jasmineUnderTest.util.getPropertyDescriptor(obj, 'prop'),
expected = Object.getOwnPropertyDescriptor(obj, 'prop'); expected = Object.getOwnPropertyDescriptor(obj, 'prop');
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
@@ -167,7 +165,7 @@ describe('util', function() {
it('get property descriptor from object property', function() { it('get property descriptor from object property', function() {
const proto = { prop: 1 }, const proto = { prop: 1 },
actual = privateUnderTest.util.getPropertyDescriptor(proto, 'prop'), actual = jasmineUnderTest.util.getPropertyDescriptor(proto, 'prop'),
expected = Object.getOwnPropertyDescriptor(proto, 'prop'); expected = Object.getOwnPropertyDescriptor(proto, 'prop');
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
@@ -178,8 +176,8 @@ describe('util', function() {
it('returns the file containing jasmine.util', function() { it('returns the file containing jasmine.util', function() {
// Chrome sometimes reports foo.js as foo.js/, so tolerate // Chrome sometimes reports foo.js as foo.js/, so tolerate
// a trailing slash if present. // a trailing slash if present.
expect(privateUnderTest.util.jasmineFile()).toMatch(/util.js\/?$/); expect(jasmineUnderTest.util.jasmineFile()).toMatch(/util.js\/?$/);
expect(jasmine.private.util.jasmineFile()).toMatch(/jasmine.js\/?$/); expect(jasmine.util.jasmineFile()).toMatch(/jasmine.js\/?$/);
}); });
}); });
}); });
+17 -17
View File
@@ -1,49 +1,49 @@
describe('AllOf', function() { describe('AllOf', function() {
it('matches a single value', function() { it('matches a single value', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const allOf = new privateUnderTest.AllOf('foo'); const allOf = new jasmineUnderTest.AllOf('foo');
expect(allOf.asymmetricMatch('foo', matchersUtil)).toBeTrue(); expect(allOf.asymmetricMatch('foo', matchersUtil)).toBeTrue();
}); });
it('matches a single matcher', function() { it('matches a single matcher', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const allOf = new privateUnderTest.AllOf( const allOf = new jasmineUnderTest.AllOf(
new privateUnderTest.StringContaining('oo') new jasmineUnderTest.StringContaining('oo')
); );
expect(allOf.asymmetricMatch('foo', matchersUtil)).toBeTrue(); expect(allOf.asymmetricMatch('foo', matchersUtil)).toBeTrue();
}); });
it('matches multiple matchers', function() { it('matches multiple matchers', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const allOf = new privateUnderTest.AllOf( const allOf = new jasmineUnderTest.AllOf(
new privateUnderTest.StringContaining('o'), new jasmineUnderTest.StringContaining('o'),
new privateUnderTest.StringContaining('f') new jasmineUnderTest.StringContaining('f')
); );
expect(allOf.asymmetricMatch('foo', matchersUtil)).toBeTrue(); expect(allOf.asymmetricMatch('foo', matchersUtil)).toBeTrue();
}); });
it('does not match when value does not match', function() { it('does not match when value does not match', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const allOf = new privateUnderTest.AllOf('bar'); const allOf = new jasmineUnderTest.AllOf('bar');
expect(allOf.asymmetricMatch('foo', matchersUtil)).toBeFalse(); expect(allOf.asymmetricMatch('foo', matchersUtil)).toBeFalse();
}); });
it('does not match when any matchers fail', function() { it('does not match when any matchers fail', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const allOf = new privateUnderTest.AllOf( const allOf = new jasmineUnderTest.AllOf(
new privateUnderTest.StringContaining('o'), new jasmineUnderTest.StringContaining('o'),
new privateUnderTest.StringContaining('x') new jasmineUnderTest.StringContaining('x')
); );
expect(allOf.asymmetricMatch('foo', matchersUtil)).toBeFalse(); expect(allOf.asymmetricMatch('foo', matchersUtil)).toBeFalse();
}); });
it('jasmineToStrings itself', function() { it('jasmineToStrings itself', function() {
const matcher = new privateUnderTest.AllOf('o'); const matcher = new jasmineUnderTest.AllOf('o');
const pp = jasmine.createSpy('pp').and.returnValue('sample'); const pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(matcher.jasmineToString(pp)).toEqual('<jasmine.allOf(sample)>'); expect(matcher.jasmineToString(pp)).toEqual('<jasmine.allOf(sample)>');
@@ -53,7 +53,7 @@ describe('AllOf', function() {
describe('when called without an argument', function() { describe('when called without an argument', function() {
it('tells the user to pass a constructor argument', function() { it('tells the user to pass a constructor argument', function() {
expect(function() { expect(function() {
new privateUnderTest.AllOf(); new jasmineUnderTest.AllOf();
}).toThrowError( }).toThrowError(
TypeError, TypeError,
'jasmine.allOf() expects at least one argument to be passed.' 'jasmine.allOf() expects at least one argument to be passed.'
+13 -13
View File
@@ -1,73 +1,73 @@
describe('Any', function() { describe('Any', function() {
it('matches a string', function() { it('matches a string', function() {
const any = new privateUnderTest.Any(String); const any = new jasmineUnderTest.Any(String);
expect(any.asymmetricMatch('foo')).toBe(true); expect(any.asymmetricMatch('foo')).toBe(true);
}); });
it('matches a number', function() { it('matches a number', function() {
const any = new privateUnderTest.Any(Number); const any = new jasmineUnderTest.Any(Number);
expect(any.asymmetricMatch(1)).toBe(true); expect(any.asymmetricMatch(1)).toBe(true);
}); });
it('matches a function', function() { it('matches a function', function() {
const any = new privateUnderTest.Any(Function); const any = new jasmineUnderTest.Any(Function);
expect(any.asymmetricMatch(function() {})).toBe(true); expect(any.asymmetricMatch(function() {})).toBe(true);
}); });
it('matches an Object', function() { it('matches an Object', function() {
const any = new privateUnderTest.Any(Object); const any = new jasmineUnderTest.Any(Object);
expect(any.asymmetricMatch({})).toBe(true); expect(any.asymmetricMatch({})).toBe(true);
}); });
it('matches a Boolean', function() { it('matches a Boolean', function() {
const any = new privateUnderTest.Any(Boolean); const any = new jasmineUnderTest.Any(Boolean);
expect(any.asymmetricMatch(true)).toBe(true); expect(any.asymmetricMatch(true)).toBe(true);
}); });
it('matches a Map', function() { it('matches a Map', function() {
const any = new privateUnderTest.Any(Map); const any = new jasmineUnderTest.Any(Map);
expect(any.asymmetricMatch(new Map())).toBe(true); expect(any.asymmetricMatch(new Map())).toBe(true);
}); });
it('matches a Set', function() { it('matches a Set', function() {
const any = new privateUnderTest.Any(Set); const any = new jasmineUnderTest.Any(Set);
expect(any.asymmetricMatch(new Set())).toBe(true); expect(any.asymmetricMatch(new Set())).toBe(true);
}); });
it('matches a TypedArray', function() { it('matches a TypedArray', function() {
const any = new privateUnderTest.Any(Uint32Array); const any = new jasmineUnderTest.Any(Uint32Array);
expect(any.asymmetricMatch(new Uint32Array([]))).toBe(true); expect(any.asymmetricMatch(new Uint32Array([]))).toBe(true);
}); });
it('matches a Symbol', function() { it('matches a Symbol', function() {
const any = new privateUnderTest.Any(Symbol); const any = new jasmineUnderTest.Any(Symbol);
expect(any.asymmetricMatch(Symbol())).toBe(true); expect(any.asymmetricMatch(Symbol())).toBe(true);
}); });
it('matches another constructed object', function() { it('matches another constructed object', function() {
const Thing = function() {}, const Thing = function() {},
any = new privateUnderTest.Any(Thing); any = new jasmineUnderTest.Any(Thing);
expect(any.asymmetricMatch(new Thing())).toBe(true); expect(any.asymmetricMatch(new Thing())).toBe(true);
}); });
it('does not treat null as an Object', function() { it('does not treat null as an Object', function() {
const any = new privateUnderTest.Any(Object); const any = new jasmineUnderTest.Any(Object);
expect(any.asymmetricMatch(null)).toBe(false); expect(any.asymmetricMatch(null)).toBe(false);
}); });
it("jasmineToString's itself", function() { it("jasmineToString's itself", function() {
const any = new privateUnderTest.Any(Number); const any = new jasmineUnderTest.Any(Number);
expect(any.jasmineToString()).toEqual('<jasmine.any(Number)>'); expect(any.jasmineToString()).toEqual('<jasmine.any(Number)>');
expect(any.jasmineToString()).toEqual('<jasmine.any(Number)>'); expect(any.jasmineToString()).toEqual('<jasmine.any(Number)>');
@@ -76,7 +76,7 @@ describe('Any', function() {
describe('when called without an argument', function() { describe('when called without an argument', function() {
it('tells the user to pass a constructor or use jasmine.anything()', function() { it('tells the user to pass a constructor or use jasmine.anything()', function() {
expect(function() { expect(function() {
new privateUnderTest.Any(); new jasmineUnderTest.Any();
}).toThrowError(TypeError, /constructor.*anything/); }).toThrowError(TypeError, /constructor.*anything/);
}); });
}); });
+11 -11
View File
@@ -1,67 +1,67 @@
describe('Anything', function() { describe('Anything', function() {
it('matches a string', function() { it('matches a string', function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch('foo')).toBe(true); expect(anything.asymmetricMatch('foo')).toBe(true);
}); });
it('matches a number', function() { it('matches a number', function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch(42)).toBe(true); expect(anything.asymmetricMatch(42)).toBe(true);
}); });
it('matches an object', function() { it('matches an object', function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch({ foo: 'bar' })).toBe(true); expect(anything.asymmetricMatch({ foo: 'bar' })).toBe(true);
}); });
it('matches an array', function() { it('matches an array', function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch([1, 2, 3])).toBe(true); expect(anything.asymmetricMatch([1, 2, 3])).toBe(true);
}); });
it('matches a Map', function() { it('matches a Map', function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch(new Map())).toBe(true); expect(anything.asymmetricMatch(new Map())).toBe(true);
}); });
it('matches a Set', function() { it('matches a Set', function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch(new Set())).toBe(true); expect(anything.asymmetricMatch(new Set())).toBe(true);
}); });
it('matches a TypedArray', function() { it('matches a TypedArray', function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch(new Uint32Array([]))).toBe(true); expect(anything.asymmetricMatch(new Uint32Array([]))).toBe(true);
}); });
it('matches a Symbol', function() { it('matches a Symbol', function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch(Symbol())).toBe(true); expect(anything.asymmetricMatch(Symbol())).toBe(true);
}); });
it("doesn't match undefined", function() { it("doesn't match undefined", function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch()).toBe(false); expect(anything.asymmetricMatch()).toBe(false);
expect(anything.asymmetricMatch(undefined)).toBe(false); expect(anything.asymmetricMatch(undefined)).toBe(false);
}); });
it("doesn't match null", function() { it("doesn't match null", function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch(null)).toBe(false); expect(anything.asymmetricMatch(null)).toBe(false);
}); });
it("jasmineToString's itself", function() { it("jasmineToString's itself", function() {
const anything = new privateUnderTest.Anything(); const anything = new jasmineUnderTest.Anything();
expect(anything.jasmineToString()).toEqual('<jasmine.anything>'); expect(anything.jasmineToString()).toEqual('<jasmine.anything>');
}); });
@@ -1,12 +1,12 @@
describe('ArrayContaining', function() { describe('ArrayContaining', function() {
it('matches any actual to an empty array', function() { it('matches any actual to an empty array', function() {
const containing = new privateUnderTest.ArrayContaining([]); const containing = new jasmineUnderTest.ArrayContaining([]);
expect(containing.asymmetricMatch('foo')).toBe(true); expect(containing.asymmetricMatch('foo')).toBe(true);
}); });
it('does not work when not passed an array', function() { it('does not work when not passed an array', function() {
const containing = new privateUnderTest.ArrayContaining('foo'); const containing = new jasmineUnderTest.ArrayContaining('foo');
expect(function() { expect(function() {
containing.asymmetricMatch([]); containing.asymmetricMatch([]);
@@ -14,36 +14,36 @@ describe('ArrayContaining', function() {
}); });
it('matches when the item is in the actual', function() { it('matches when the item is in the actual', function() {
const containing = new privateUnderTest.ArrayContaining(['foo']); const containing = new jasmineUnderTest.ArrayContaining(['foo']);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(['foo'], matchersUtil)).toBe(true); expect(containing.asymmetricMatch(['foo'], matchersUtil)).toBe(true);
}); });
it('matches when additional items are in the actual', function() { it('matches when additional items are in the actual', function() {
const containing = new privateUnderTest.ArrayContaining(['foo']); const containing = new jasmineUnderTest.ArrayContaining(['foo']);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(['foo', 'bar'], matchersUtil)).toBe(true); expect(containing.asymmetricMatch(['foo', 'bar'], matchersUtil)).toBe(true);
}); });
it('does not match when the item is not in the actual', function() { it('does not match when the item is not in the actual', function() {
const containing = new privateUnderTest.ArrayContaining(['foo']); const containing = new jasmineUnderTest.ArrayContaining(['foo']);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(['bar'], matchersUtil)).toBe(false); expect(containing.asymmetricMatch(['bar'], matchersUtil)).toBe(false);
}); });
it('does not match when the actual is not an array', function() { it('does not match when the actual is not an array', function() {
const containing = new privateUnderTest.ArrayContaining(['foo']); const containing = new jasmineUnderTest.ArrayContaining(['foo']);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch('foo', matchersUtil)).toBe(false); expect(containing.asymmetricMatch('foo', matchersUtil)).toBe(false);
}); });
it('jasmineToStrings itself', function() { it('jasmineToStrings itself', function() {
const sample = [], const sample = [],
matcher = new privateUnderTest.ArrayContaining(sample), matcher = new jasmineUnderTest.ArrayContaining(sample),
pp = jasmine.createSpy('pp').and.returnValue('sample'); pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(matcher.jasmineToString(pp)).toEqual( expect(matcher.jasmineToString(pp)).toEqual(
@@ -64,8 +64,8 @@ describe('ArrayContaining', function() {
return true; return true;
} }
}; };
const containing = new privateUnderTest.ArrayContaining(['fooVal']); const containing = new jasmineUnderTest.ArrayContaining(['fooVal']);
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [tester] customTesters: [tester]
}); });
@@ -1,13 +1,13 @@
describe('ArrayWithExactContents', function() { describe('ArrayWithExactContents', function() {
it('matches an array with the same items in a different order', function() { it('matches an array with the same items in a different order', function() {
const matcher = new privateUnderTest.ArrayWithExactContents(['a', 2, /a/]); const matcher = new jasmineUnderTest.ArrayWithExactContents(['a', 2, /a/]);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matcher.asymmetricMatch([2, 'a', /a/], matchersUtil)).toBe(true); expect(matcher.asymmetricMatch([2, 'a', /a/], matchersUtil)).toBe(true);
}); });
it('does not work when not passed an array', function() { it('does not work when not passed an array', function() {
const matcher = new privateUnderTest.ArrayWithExactContents('foo'); const matcher = new jasmineUnderTest.ArrayWithExactContents('foo');
expect(function() { expect(function() {
matcher.asymmetricMatch([]); matcher.asymmetricMatch([]);
@@ -15,8 +15,8 @@ describe('ArrayWithExactContents', function() {
}); });
it('does not match when an item is missing', function() { it('does not match when an item is missing', function() {
const matcher = new privateUnderTest.ArrayWithExactContents(['a', 2, /a/]); const matcher = new jasmineUnderTest.ArrayWithExactContents(['a', 2, /a/]);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matcher.asymmetricMatch(['a', 2], matchersUtil)).toBe(false); expect(matcher.asymmetricMatch(['a', 2], matchersUtil)).toBe(false);
expect(matcher.asymmetricMatch(['a', 2, undefined], matchersUtil)).toBe( expect(matcher.asymmetricMatch(['a', 2, undefined], matchersUtil)).toBe(
@@ -25,15 +25,15 @@ describe('ArrayWithExactContents', function() {
}); });
it('does not match when there is an extra item', function() { it('does not match when there is an extra item', function() {
const matcher = new privateUnderTest.ArrayWithExactContents(['a']); const matcher = new jasmineUnderTest.ArrayWithExactContents(['a']);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matcher.asymmetricMatch(['a', 2], matchersUtil)).toBe(false); expect(matcher.asymmetricMatch(['a', 2], matchersUtil)).toBe(false);
}); });
it('jasmineToStrings itself', function() { it('jasmineToStrings itself', function() {
const sample = [], const sample = [],
matcher = new privateUnderTest.ArrayWithExactContents(sample), matcher = new jasmineUnderTest.ArrayWithExactContents(sample),
pp = jasmine.createSpy('pp').and.returnValue('sample'); pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(matcher.jasmineToString(pp)).toEqual( expect(matcher.jasmineToString(pp)).toEqual(
@@ -54,8 +54,8 @@ describe('ArrayWithExactContents', function() {
return true; return true;
} }
}; };
const matcher = new privateUnderTest.ArrayWithExactContents(['fooVal']); const matcher = new jasmineUnderTest.ArrayWithExactContents(['fooVal']);
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [tester] customTesters: [tester]
}); });
+6 -6
View File
@@ -1,20 +1,20 @@
describe('Empty', function() { describe('Empty', function() {
it('matches an empty object', function() { it('matches an empty object', function() {
const empty = new privateUnderTest.Empty(); const empty = new jasmineUnderTest.Empty();
expect(empty.asymmetricMatch({})).toBe(true); expect(empty.asymmetricMatch({})).toBe(true);
expect(empty.asymmetricMatch({ undefined: false })).toBe(false); expect(empty.asymmetricMatch({ undefined: false })).toBe(false);
}); });
it('matches an empty array', function() { it('matches an empty array', function() {
const empty = new privateUnderTest.Empty(); const empty = new jasmineUnderTest.Empty();
expect(empty.asymmetricMatch([])).toBe(true); expect(empty.asymmetricMatch([])).toBe(true);
expect(empty.asymmetricMatch([1, 12, 3])).toBe(false); expect(empty.asymmetricMatch([1, 12, 3])).toBe(false);
}); });
it('matches an empty string', function() { it('matches an empty string', function() {
const empty = new privateUnderTest.Empty(); const empty = new jasmineUnderTest.Empty();
expect(empty.asymmetricMatch('')).toBe(true); expect(empty.asymmetricMatch('')).toBe(true);
expect(empty.asymmetricMatch('')).toBe(true); expect(empty.asymmetricMatch('')).toBe(true);
@@ -22,7 +22,7 @@ describe('Empty', function() {
}); });
it('matches an empty map', function() { it('matches an empty map', function() {
const empty = new privateUnderTest.Empty(); const empty = new jasmineUnderTest.Empty();
const fullMap = new Map(); const fullMap = new Map();
fullMap.set('thing', 2); fullMap.set('thing', 2);
@@ -31,7 +31,7 @@ describe('Empty', function() {
}); });
it('matches an empty set', function() { it('matches an empty set', function() {
const empty = new privateUnderTest.Empty(); const empty = new jasmineUnderTest.Empty();
const fullSet = new Set(); const fullSet = new Set();
fullSet.add(3); fullSet.add(3);
@@ -40,7 +40,7 @@ describe('Empty', function() {
}); });
it('matches an empty typed array', function() { it('matches an empty typed array', function() {
const empty = new privateUnderTest.Empty(); const empty = new jasmineUnderTest.Empty();
expect(empty.asymmetricMatch(new Int16Array())).toBe(true); expect(empty.asymmetricMatch(new Int16Array())).toBe(true);
expect(empty.asymmetricMatch(new Int16Array([1, 2]))).toBe(false); expect(empty.asymmetricMatch(new Int16Array([1, 2]))).toBe(false);
+5 -5
View File
@@ -1,6 +1,6 @@
describe('Falsy', function() { describe('Falsy', function() {
it('is true for an empty string', function() { it('is true for an empty string', function() {
const falsy = new privateUnderTest.Falsy(); const falsy = new jasmineUnderTest.Falsy();
expect(falsy.asymmetricMatch('')).toBe(true); expect(falsy.asymmetricMatch('')).toBe(true);
expect(falsy.asymmetricMatch('')).toBe(true); expect(falsy.asymmetricMatch('')).toBe(true);
@@ -8,7 +8,7 @@ describe('Falsy', function() {
}); });
it('is false for a number that is 0', function() { it('is false for a number that is 0', function() {
const falsy = new privateUnderTest.Falsy(Number); const falsy = new jasmineUnderTest.Falsy(Number);
expect(falsy.asymmetricMatch(1)).toBe(false); expect(falsy.asymmetricMatch(1)).toBe(false);
expect(falsy.asymmetricMatch(0)).toBe(true); expect(falsy.asymmetricMatch(0)).toBe(true);
@@ -17,20 +17,20 @@ describe('Falsy', function() {
}); });
it('is true for a null or undefined', function() { it('is true for a null or undefined', function() {
const falsy = new privateUnderTest.Falsy(Function); const falsy = new jasmineUnderTest.Falsy(Function);
expect(falsy.asymmetricMatch(null)).toBe(true); expect(falsy.asymmetricMatch(null)).toBe(true);
expect(falsy.asymmetricMatch(undefined)).toBe(true); expect(falsy.asymmetricMatch(undefined)).toBe(true);
}); });
it('is true for NaN', function() { it('is true for NaN', function() {
const falsy = new privateUnderTest.Falsy(Object); const falsy = new jasmineUnderTest.Falsy(Object);
expect(falsy.asymmetricMatch(NaN)).toBe(true); expect(falsy.asymmetricMatch(NaN)).toBe(true);
}); });
it('is true for a false Boolean', function() { it('is true for a false Boolean', function() {
const falsy = new privateUnderTest.Falsy(Boolean); const falsy = new jasmineUnderTest.Falsy(Boolean);
expect(falsy.asymmetricMatch(false)).toBe(true); expect(falsy.asymmetricMatch(false)).toBe(true);
expect(falsy.asymmetricMatch(true)).toBe(false); expect(falsy.asymmetricMatch(true)).toBe(false);
+6 -6
View File
@@ -1,28 +1,28 @@
describe('Is', function() { describe('Is', function() {
it('passes for primitives that are ===', function() { it('passes for primitives that are ===', function() {
const exactly = new privateUnderTest.Is(17); const exactly = new jasmineUnderTest.Is(17);
expect(exactly.asymmetricMatch(17)).toBeTrue(); expect(exactly.asymmetricMatch(17)).toBeTrue();
}); });
it('fails for primitives that are not ===', function() { it('fails for primitives that are not ===', function() {
const exactly = new privateUnderTest.Is(42); const exactly = new jasmineUnderTest.Is(42);
expect(exactly.asymmetricMatch('42')).toBeFalse(); expect(exactly.asymmetricMatch('42')).toBeFalse();
}); });
it('passes for the same object instance', function() { it('passes for the same object instance', function() {
const obj = {}; const obj = {};
const exactly = new privateUnderTest.Is(obj); const exactly = new jasmineUnderTest.Is(obj);
expect(exactly.asymmetricMatch(obj)).toBeTrue(); expect(exactly.asymmetricMatch(obj)).toBeTrue();
}); });
it('fails for different object instances, even if they are deep value equal', function() { it('fails for different object instances, even if they are deep value equal', function() {
const exactly = new privateUnderTest.Is({}); const exactly = new jasmineUnderTest.Is({});
expect(exactly.asymmetricMatch({})).toBeFalse(); expect(exactly.asymmetricMatch({})).toBeFalse();
}); });
it('describes itself for use in diffs and pretty printing', function() { it('describes itself for use in diffs and pretty printing', function() {
const exactly = new privateUnderTest.Is({ foo: ['bar'] }); const exactly = new jasmineUnderTest.Is({ foo: ['bar'] });
const pp = privateUnderTest.basicPrettyPrinter; const pp = jasmineUnderTest.basicPrettyPrinter_;
expect(exactly.jasmineToString(pp)).toEqual( expect(exactly.jasmineToString(pp)).toEqual(
"<jasmine.is(Object({ foo: [ 'bar' ] }))>" "<jasmine.is(Object({ foo: [ 'bar' ] }))>"
); );
@@ -1,7 +1,7 @@
describe('MapContaining', function() { describe('MapContaining', function() {
it('matches any actual map to an empty map', function() { it('matches any actual map to an empty map', function() {
const actualMap = new Map([['foo', 'bar']]); const actualMap = new Map([['foo', 'bar']]);
const containing = new privateUnderTest.MapContaining(new Map()); const containing = new jasmineUnderTest.MapContaining(new Map());
expect(containing.asymmetricMatch(actualMap)).toBe(true); expect(containing.asymmetricMatch(actualMap)).toBe(true);
}); });
@@ -17,8 +17,8 @@ describe('MapContaining', function() {
[{ foo: 'bar' }, 'baz'], [{ foo: 'bar' }, 'baz'],
['foo', [1, 2, 3]] ['foo', [1, 2, 3]]
]); ]);
const containing = new privateUnderTest.MapContaining(containingMap); const containing = new jasmineUnderTest.MapContaining(containingMap);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true); expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
}); });
@@ -33,8 +33,8 @@ describe('MapContaining', function() {
[{ foo: 'bar' }, 'baz'], [{ foo: 'bar' }, 'baz'],
['foo', [1, 2, 3]] ['foo', [1, 2, 3]]
]); ]);
const containing = new privateUnderTest.MapContaining(containingMap); const containing = new jasmineUnderTest.MapContaining(containingMap);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false); expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
}); });
@@ -43,8 +43,8 @@ describe('MapContaining', function() {
const actualMap = new Map([['foo', [1, 2, 3]], [{ foo: 'bar' }, 'baz']]); const actualMap = new Map([['foo', [1, 2, 3]], [{ foo: 'bar' }, 'baz']]);
const containingMap = new Map([[{ foo: 'bar' }, 'baz'], ['foo', [1, 2]]]); const containingMap = new Map([[{ foo: 'bar' }, 'baz'], ['foo', [1, 2]]]);
const containing = new privateUnderTest.MapContaining(containingMap); const containing = new jasmineUnderTest.MapContaining(containingMap);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false); expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
}); });
@@ -60,8 +60,8 @@ describe('MapContaining', function() {
[jasmineUnderTest.stringMatching(/^foo\d/), 'bar'], [jasmineUnderTest.stringMatching(/^foo\d/), 'bar'],
['baz', jasmineUnderTest.arrayContaining([2, 3])] ['baz', jasmineUnderTest.arrayContaining([2, 3])]
]); ]);
const containing = new privateUnderTest.MapContaining(containingMap); const containing = new jasmineUnderTest.MapContaining(containingMap);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true); expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
}); });
@@ -73,8 +73,8 @@ describe('MapContaining', function() {
[jasmineUnderTest.stringMatching(/^foo\d/), 'bar'], [jasmineUnderTest.stringMatching(/^foo\d/), 'bar'],
['baz', jasmineUnderTest.arrayContaining([2, 3])] ['baz', jasmineUnderTest.arrayContaining([2, 3])]
]); ]);
const containing = new privateUnderTest.MapContaining(containingMap); const containing = new jasmineUnderTest.MapContaining(containingMap);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false); expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
}); });
@@ -86,8 +86,8 @@ describe('MapContaining', function() {
[jasmineUnderTest.stringMatching(/^foo\d/), 'bar'], [jasmineUnderTest.stringMatching(/^foo\d/), 'bar'],
['baz', jasmineUnderTest.arrayContaining([4, 5])] ['baz', jasmineUnderTest.arrayContaining([4, 5])]
]); ]);
const containing = new privateUnderTest.MapContaining(containingMap); const containing = new jasmineUnderTest.MapContaining(containingMap);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false); expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
}); });
@@ -100,11 +100,11 @@ describe('MapContaining', function() {
]); ]);
const containingMap = new Map([ const containingMap = new Map([
['foo', new privateUnderTest.MapContaining(new Map([['foo1', 1]]))], ['foo', new jasmineUnderTest.MapContaining(new Map([['foo1', 1]]))],
[new privateUnderTest.MapContaining(new Map([[2, 'bar2']])), 'bar'] [new jasmineUnderTest.MapContaining(new Map([[2, 'bar2']])), 'bar']
]); ]);
const containing = new privateUnderTest.MapContaining(containingMap); const containing = new jasmineUnderTest.MapContaining(containingMap);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true); expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
}); });
@@ -117,10 +117,10 @@ describe('MapContaining', function() {
: a === b; : a === b;
} }
const actualMap = new Map([['foo', -1]]); const actualMap = new Map([['foo', -1]]);
const containing = new privateUnderTest.MapContaining( const containing = new jasmineUnderTest.MapContaining(
new Map([['foo', -2]]) new Map([['foo', -2]])
); );
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [tester] customTesters: [tester]
}); });
@@ -130,13 +130,13 @@ describe('MapContaining', function() {
it('does not match when actual is not a map', function() { it('does not match when actual is not a map', function() {
const containingMap = new Map([['foo', 'bar']]); const containingMap = new Map([['foo', 'bar']]);
expect( expect(
new privateUnderTest.MapContaining(containingMap).asymmetricMatch('foo') new jasmineUnderTest.MapContaining(containingMap).asymmetricMatch('foo')
).toBe(false); ).toBe(false);
expect( expect(
new privateUnderTest.MapContaining(containingMap).asymmetricMatch(-1) new jasmineUnderTest.MapContaining(containingMap).asymmetricMatch(-1)
).toBe(false); ).toBe(false);
expect( expect(
new privateUnderTest.MapContaining(containingMap).asymmetricMatch({ new jasmineUnderTest.MapContaining(containingMap).asymmetricMatch({
foo: 'bar' foo: 'bar'
}) })
).toBe(false); ).toBe(false);
@@ -144,7 +144,7 @@ describe('MapContaining', function() {
it('throws an error when sample is not a map', function() { it('throws an error when sample is not a map', function() {
expect(function() { expect(function() {
new privateUnderTest.MapContaining({ foo: 'bar' }).asymmetricMatch( new jasmineUnderTest.MapContaining({ foo: 'bar' }).asymmetricMatch(
new Map() new Map()
); );
}).toThrowError(/You must provide a map/); }).toThrowError(/You must provide a map/);
@@ -152,7 +152,7 @@ describe('MapContaining', function() {
it('defines a `jasmineToString` method', function() { it('defines a `jasmineToString` method', function() {
const sample = new Map(), const sample = new Map(),
containing = new privateUnderTest.MapContaining(sample), containing = new jasmineUnderTest.MapContaining(sample),
pp = jasmine.createSpy('pp').and.returnValue('sample'); pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(containing.jasmineToString(pp)).toEqual( expect(containing.jasmineToString(pp)).toEqual(
@@ -1,20 +1,20 @@
describe('NotEmpty', function() { describe('NotEmpty', function() {
it('matches a non empty object', function() { it('matches a non empty object', function() {
const notEmpty = new privateUnderTest.NotEmpty(); const notEmpty = new jasmineUnderTest.NotEmpty();
expect(notEmpty.asymmetricMatch({ undefined: false })).toBe(true); expect(notEmpty.asymmetricMatch({ undefined: false })).toBe(true);
expect(notEmpty.asymmetricMatch({})).toBe(false); expect(notEmpty.asymmetricMatch({})).toBe(false);
}); });
it('matches a non empty array', function() { it('matches a non empty array', function() {
const notEmpty = new privateUnderTest.NotEmpty(); const notEmpty = new jasmineUnderTest.NotEmpty();
expect(notEmpty.asymmetricMatch([1, 12, 3])).toBe(true); expect(notEmpty.asymmetricMatch([1, 12, 3])).toBe(true);
expect(notEmpty.asymmetricMatch([])).toBe(false); expect(notEmpty.asymmetricMatch([])).toBe(false);
}); });
it('matches a non empty string', function() { it('matches a non empty string', function() {
const notEmpty = new privateUnderTest.NotEmpty(); const notEmpty = new jasmineUnderTest.NotEmpty();
expect(notEmpty.asymmetricMatch('12312')).toBe(true); expect(notEmpty.asymmetricMatch('12312')).toBe(true);
expect(notEmpty.asymmetricMatch('')).toBe(false); expect(notEmpty.asymmetricMatch('')).toBe(false);
@@ -22,7 +22,7 @@ describe('NotEmpty', function() {
}); });
it('matches a non empty map', function() { it('matches a non empty map', function() {
const notEmpty = new privateUnderTest.NotEmpty(); const notEmpty = new jasmineUnderTest.NotEmpty();
const fullMap = new Map(); const fullMap = new Map();
fullMap.set('one', 1); fullMap.set('one', 1);
const emptyMap = new Map(); const emptyMap = new Map();
@@ -32,7 +32,7 @@ describe('NotEmpty', function() {
}); });
it('matches a non empty set', function() { it('matches a non empty set', function() {
const notEmpty = new privateUnderTest.NotEmpty(); const notEmpty = new jasmineUnderTest.NotEmpty();
const filledSet = new Set(); const filledSet = new Set();
filledSet.add(1); filledSet.add(1);
const emptySet = new Set(); const emptySet = new Set();
@@ -42,7 +42,7 @@ describe('NotEmpty', function() {
}); });
it('matches a non empty typed array', function() { it('matches a non empty typed array', function() {
const notEmpty = new privateUnderTest.NotEmpty(); const notEmpty = new jasmineUnderTest.NotEmpty();
expect(notEmpty.asymmetricMatch(new Int16Array([1, 2, 3]))).toBe(true); expect(notEmpty.asymmetricMatch(new Int16Array([1, 2, 3]))).toBe(true);
expect(notEmpty.asymmetricMatch(new Int16Array())).toBe(false); expect(notEmpty.asymmetricMatch(new Int16Array())).toBe(false);
@@ -1,13 +1,13 @@
describe('ObjectContaining', function() { describe('ObjectContaining', function() {
it('matches any object actual to an empty object', function() { it('matches any object actual to an empty object', function() {
const containing = new privateUnderTest.ObjectContaining({}); const containing = new jasmineUnderTest.ObjectContaining({});
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({ foo: 1 }, matchersUtil)).toBe(true); expect(containing.asymmetricMatch({ foo: 1 }, matchersUtil)).toBe(true);
}); });
it('does not match when the actual is not an object', function() { it('does not match when the actual is not an object', function() {
const containing = new privateUnderTest.ObjectContaining({}); const containing = new jasmineUnderTest.ObjectContaining({});
[1, true, undefined, 'a string'].forEach(function(actual) { [1, true, undefined, 'a string'].forEach(function(actual) {
expect(containing.asymmetricMatch(actual)).toBe(false); expect(containing.asymmetricMatch(actual)).toBe(false);
@@ -15,7 +15,7 @@ describe('ObjectContaining', function() {
}); });
it('does not match an empty object actual', function() { it('does not match an empty object actual', function() {
const containing = new privateUnderTest.ObjectContaining('foo'); const containing = new jasmineUnderTest.ObjectContaining('foo');
expect(function() { expect(function() {
containing.asymmetricMatch({}); containing.asymmetricMatch({});
@@ -23,8 +23,8 @@ describe('ObjectContaining', function() {
}); });
it('matches when the key/value pair is present in the actual', function() { it('matches when the key/value pair is present in the actual', function() {
const containing = new privateUnderTest.ObjectContaining({ foo: 'fooVal' }); const containing = new jasmineUnderTest.ObjectContaining({ foo: 'fooVal' });
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect( expect(
containing.asymmetricMatch({ foo: 'fooVal', bar: 'barVal' }, matchersUtil) containing.asymmetricMatch({ foo: 'fooVal', bar: 'barVal' }, matchersUtil)
@@ -32,8 +32,8 @@ describe('ObjectContaining', function() {
}); });
it('does not match when the key/value pair is not present in the actual', function() { it('does not match when the key/value pair is not present in the actual', function() {
const containing = new privateUnderTest.ObjectContaining({ foo: 'fooVal' }); const containing = new jasmineUnderTest.ObjectContaining({ foo: 'fooVal' });
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect( expect(
containing.asymmetricMatch( containing.asymmetricMatch(
@@ -44,8 +44,8 @@ describe('ObjectContaining', function() {
}); });
it('does not match when the key is present but the value is different in the actual', function() { it('does not match when the key is present but the value is different in the actual', function() {
const containing = new privateUnderTest.ObjectContaining({ foo: 'other' }); const containing = new jasmineUnderTest.ObjectContaining({ foo: 'other' });
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect( expect(
containing.asymmetricMatch({ foo: 'fooVal', bar: 'barVal' }, matchersUtil) containing.asymmetricMatch({ foo: 'fooVal', bar: 'barVal' }, matchersUtil)
@@ -54,7 +54,7 @@ describe('ObjectContaining', function() {
it("jasmineToString's itself", function() { it("jasmineToString's itself", function() {
const sample = {}, const sample = {},
matcher = new privateUnderTest.ObjectContaining(sample), matcher = new jasmineUnderTest.ObjectContaining(sample),
pp = jasmine.createSpy('pp').and.returnValue('sample'); pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(matcher.jasmineToString(pp)).toEqual( expect(matcher.jasmineToString(pp)).toEqual(
@@ -64,10 +64,10 @@ describe('ObjectContaining', function() {
}); });
it('matches recursively', function() { it('matches recursively', function() {
const containing = new privateUnderTest.ObjectContaining({ const containing = new jasmineUnderTest.ObjectContaining({
one: new privateUnderTest.ObjectContaining({ two: {} }) one: new jasmineUnderTest.ObjectContaining({ two: {} })
}); });
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({ one: { two: {} } }, matchersUtil)).toBe( expect(containing.asymmetricMatch({ one: { two: {} } }, matchersUtil)).toBe(
true true
@@ -75,10 +75,10 @@ describe('ObjectContaining', function() {
}); });
it('matches when key is present with undefined value', function() { it('matches when key is present with undefined value', function() {
const containing = new privateUnderTest.ObjectContaining({ const containing = new jasmineUnderTest.ObjectContaining({
one: undefined one: undefined
}); });
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({ one: undefined }, matchersUtil)).toBe( expect(containing.asymmetricMatch({ one: undefined }, matchersUtil)).toBe(
true true
@@ -86,17 +86,17 @@ describe('ObjectContaining', function() {
}); });
it('does not match when key with undefined value is not present', function() { it('does not match when key with undefined value is not present', function() {
const containing = new privateUnderTest.ObjectContaining({ const containing = new jasmineUnderTest.ObjectContaining({
one: undefined one: undefined
}); });
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({}, matchersUtil)).toBe(false); expect(containing.asymmetricMatch({}, matchersUtil)).toBe(false);
}); });
it('matches defined properties', function() { it('matches defined properties', function() {
const containing = new privateUnderTest.ObjectContaining({ foo: 'fooVal' }); const containing = new jasmineUnderTest.ObjectContaining({ foo: 'fooVal' });
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const definedPropertyObject = {}; const definedPropertyObject = {};
Object.defineProperty(definedPropertyObject, 'foo', { Object.defineProperty(definedPropertyObject, 'foo', {
@@ -110,8 +110,8 @@ describe('ObjectContaining', function() {
}); });
it('matches prototype properties', function() { it('matches prototype properties', function() {
const containing = new privateUnderTest.ObjectContaining({ foo: 'fooVal' }); const containing = new jasmineUnderTest.ObjectContaining({ foo: 'fooVal' });
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const prototypeObject = { foo: 'fooVal' }; const prototypeObject = { foo: 'fooVal' };
const obj = Object.create(prototypeObject); const obj = Object.create(prototypeObject);
@@ -131,8 +131,8 @@ describe('ObjectContaining', function() {
return true; return true;
} }
}; };
const containing = new privateUnderTest.ObjectContaining({ foo: 'fooVal' }); const containing = new jasmineUnderTest.ObjectContaining({ foo: 'fooVal' });
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [tester] customTesters: [tester]
}); });
@@ -144,8 +144,8 @@ describe('ObjectContaining', function() {
describe('valuesForDiff_', function() { describe('valuesForDiff_', function() {
describe('when other is not an object', function() { describe('when other is not an object', function() {
it('sets self to jasmineToString()', function() { it('sets self to jasmineToString()', function() {
const containing = new privateUnderTest.ObjectContaining({}), const containing = new jasmineUnderTest.ObjectContaining({}),
pp = privateUnderTest.makePrettyPrinter(), pp = jasmineUnderTest.makePrettyPrinter(),
result = containing.valuesForDiff_('a', pp); result = containing.valuesForDiff_('a', pp);
expect(result).toEqual({ expect(result).toEqual({
@@ -159,11 +159,11 @@ describe('ObjectContaining', function() {
it('includes keys that are present in both other and sample', function() { it('includes keys that are present in both other and sample', function() {
const sample = { a: 1, b: 2 }, const sample = { a: 1, b: 2 },
other = { a: 3, b: 4 }, other = { a: 3, b: 4 },
containing = new privateUnderTest.ObjectContaining(sample), containing = new jasmineUnderTest.ObjectContaining(sample),
result = containing.valuesForDiff_(other); result = containing.valuesForDiff_(other);
expect(result.self).not.toBeInstanceOf( expect(result.self).not.toBeInstanceOf(
privateUnderTest.ObjectContaining jasmineUnderTest.ObjectContaining
); );
expect(result).toEqual({ expect(result).toEqual({
self: sample, self: sample,
@@ -174,11 +174,11 @@ describe('ObjectContaining', function() {
it('includes keys that are present only in sample', function() { it('includes keys that are present only in sample', function() {
const sample = { a: 1, b: 2 }, const sample = { a: 1, b: 2 },
other = { a: 3 }, other = { a: 3 },
containing = new privateUnderTest.ObjectContaining(sample), containing = new jasmineUnderTest.ObjectContaining(sample),
result = containing.valuesForDiff_(other); result = containing.valuesForDiff_(other);
expect(result.self).not.toBeInstanceOf( expect(result.self).not.toBeInstanceOf(
privateUnderTest.ObjectContaining jasmineUnderTest.ObjectContaining
); );
expect(containing.valuesForDiff_(other)).toEqual({ expect(containing.valuesForDiff_(other)).toEqual({
self: sample, self: sample,
@@ -192,11 +192,11 @@ describe('ObjectContaining', function() {
it('omits keys that are present only in other', function() { it('omits keys that are present only in other', function() {
const sample = { a: 1, b: 2 }, const sample = { a: 1, b: 2 },
other = { a: 3, b: 4, c: 5 }, other = { a: 3, b: 4, c: 5 },
containing = new privateUnderTest.ObjectContaining(sample), containing = new jasmineUnderTest.ObjectContaining(sample),
result = containing.valuesForDiff_(other); result = containing.valuesForDiff_(other);
expect(result.self).not.toBeInstanceOf( expect(result.self).not.toBeInstanceOf(
privateUnderTest.ObjectContaining jasmineUnderTest.ObjectContaining
); );
expect(result).toEqual({ expect(result).toEqual({
self: sample, self: sample,
@@ -1,7 +1,7 @@
describe('SetContaining', function() { describe('SetContaining', function() {
it('matches any actual set to an empty set', function() { it('matches any actual set to an empty set', function() {
const actualSet = new Set(['foo', 'bar']); const actualSet = new Set(['foo', 'bar']);
const containing = new privateUnderTest.SetContaining(new Set()); const containing = new jasmineUnderTest.SetContaining(new Set());
expect(containing.asymmetricMatch(actualSet)).toBe(true); expect(containing.asymmetricMatch(actualSet)).toBe(true);
}); });
@@ -10,8 +10,8 @@ describe('SetContaining', function() {
const actualSet = new Set([{ foo: 'bar' }, 'baz', [1, 2, 3]]); const actualSet = new Set([{ foo: 'bar' }, 'baz', [1, 2, 3]]);
const containingSet = new Set([[1, 2, 3], { foo: 'bar' }]); const containingSet = new Set([[1, 2, 3], { foo: 'bar' }]);
const containing = new privateUnderTest.SetContaining(containingSet); const containing = new jasmineUnderTest.SetContaining(containingSet);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(true); expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(true);
}); });
@@ -20,8 +20,8 @@ describe('SetContaining', function() {
const actualSet = new Set([{ foo: 'bar' }, 'baz', [1, 2, 3]]); const actualSet = new Set([{ foo: 'bar' }, 'baz', [1, 2, 3]]);
const containingSet = new Set([[1, 2], { foo: 'bar' }]); const containingSet = new Set([[1, 2], { foo: 'bar' }]);
const containing = new privateUnderTest.SetContaining(containingSet); const containing = new jasmineUnderTest.SetContaining(containingSet);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(false); expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(false);
}); });
@@ -33,8 +33,8 @@ describe('SetContaining', function() {
jasmineUnderTest.stringMatching(/^foo\d/), jasmineUnderTest.stringMatching(/^foo\d/),
jasmineUnderTest.arrayContaining([2, 3]) jasmineUnderTest.arrayContaining([2, 3])
]); ]);
const containing = new privateUnderTest.SetContaining(containingSet); const containing = new jasmineUnderTest.SetContaining(containingSet);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(true); expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(true);
}); });
@@ -46,8 +46,8 @@ describe('SetContaining', function() {
jasmine.stringMatching(/^foo\d/), jasmine.stringMatching(/^foo\d/),
jasmine.arrayContaining([2, 3]) jasmine.arrayContaining([2, 3])
]); ]);
const containing = new privateUnderTest.SetContaining(containingSet); const containing = new jasmineUnderTest.SetContaining(containingSet);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(false); expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(false);
}); });
@@ -56,11 +56,11 @@ describe('SetContaining', function() {
const actualSet = new Set(['foo', new Set([1, 'bar', 2]), 'other']); const actualSet = new Set(['foo', new Set([1, 'bar', 2]), 'other']);
const containingSet = new Set([ const containingSet = new Set([
new privateUnderTest.SetContaining(new Set(['bar'])), new jasmineUnderTest.SetContaining(new Set(['bar'])),
'foo' 'foo'
]); ]);
const containing = new privateUnderTest.SetContaining(containingSet); const containing = new jasmineUnderTest.SetContaining(containingSet);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(true); expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(true);
}); });
@@ -73,8 +73,8 @@ describe('SetContaining', function() {
: a === b; : a === b;
} }
const actualSet = new Set(['foo', -1]); const actualSet = new Set(['foo', -1]);
const containing = new privateUnderTest.SetContaining(new Set([-2, 'foo'])); const containing = new jasmineUnderTest.SetContaining(new Set([-2, 'foo']));
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [tester] customTesters: [tester]
}); });
@@ -84,19 +84,19 @@ describe('SetContaining', function() {
it('does not match when actual is not a set', function() { it('does not match when actual is not a set', function() {
const containingSet = new Set(['foo']); const containingSet = new Set(['foo']);
expect( expect(
new privateUnderTest.SetContaining(containingSet).asymmetricMatch('foo') new jasmineUnderTest.SetContaining(containingSet).asymmetricMatch('foo')
).toBe(false); ).toBe(false);
expect( expect(
new privateUnderTest.SetContaining(containingSet).asymmetricMatch(1) new jasmineUnderTest.SetContaining(containingSet).asymmetricMatch(1)
).toBe(false); ).toBe(false);
expect( expect(
new privateUnderTest.SetContaining(containingSet).asymmetricMatch(['foo']) new jasmineUnderTest.SetContaining(containingSet).asymmetricMatch(['foo'])
).toBe(false); ).toBe(false);
}); });
it('throws an error when sample is not a set', function() { it('throws an error when sample is not a set', function() {
expect(function() { expect(function() {
new privateUnderTest.SetContaining({ foo: 'bar' }).asymmetricMatch( new jasmineUnderTest.SetContaining({ foo: 'bar' }).asymmetricMatch(
new Set() new Set()
); );
}).toThrowError(/You must provide a set/); }).toThrowError(/You must provide a set/);
@@ -104,7 +104,7 @@ describe('SetContaining', function() {
it('defines a `jasmineToString` method', function() { it('defines a `jasmineToString` method', function() {
const sample = new Set(), const sample = new Set(),
containing = new privateUnderTest.SetContaining(sample), containing = new jasmineUnderTest.SetContaining(sample),
pp = jasmine.createSpy('pp').and.returnValue('sample'); pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(containing.jasmineToString(pp)).toEqual( expect(containing.jasmineToString(pp)).toEqual(
@@ -1,6 +1,6 @@
describe('StringContaining', function() { describe('StringContaining', function() {
it('searches for a provided substring when the expected is a String', function() { it('searches for a provided substring when the expected is a String', function() {
const matcher = new privateUnderTest.StringContaining('foo'); const matcher = new jasmineUnderTest.StringContaining('foo');
expect(matcher.asymmetricMatch('barfoobaz')).toBe(true); expect(matcher.asymmetricMatch('barfoobaz')).toBe(true);
expect(matcher.asymmetricMatch('barbaz')).toBe(false); expect(matcher.asymmetricMatch('barbaz')).toBe(false);
@@ -8,17 +8,17 @@ describe('StringContaining', function() {
it('raises an Error when the expected is not a String', function() { it('raises an Error when the expected is not a String', function() {
expect(function() { expect(function() {
new privateUnderTest.StringContaining(/foo/); new jasmineUnderTest.StringContaining(/foo/);
}).toThrowError(/not a String/); }).toThrowError(/not a String/);
}); });
it('fails when the actual is not a String', function() { it('fails when the actual is not a String', function() {
const matcher = new privateUnderTest.StringContaining('x'); const matcher = new jasmineUnderTest.StringContaining('x');
expect(matcher.asymmetricMatch(['x'])).toBe(false); expect(matcher.asymmetricMatch(['x'])).toBe(false);
}); });
it("jasmineToString's itself", function() { it("jasmineToString's itself", function() {
const matching = new privateUnderTest.StringContaining('foo'); const matching = new jasmineUnderTest.StringContaining('foo');
expect(matching.jasmineToString()).toEqual( expect(matching.jasmineToString()).toEqual(
'<jasmine.stringContaining("foo")>' '<jasmine.stringContaining("foo")>'
@@ -1,13 +1,13 @@
describe('StringMatching', function() { describe('StringMatching', function() {
it('matches a string against a provided regexp', function() { it('matches a string against a provided regexp', function() {
const matcher = new privateUnderTest.StringMatching(/foo/); const matcher = new jasmineUnderTest.StringMatching(/foo/);
expect(matcher.asymmetricMatch('barfoobaz')).toBe(true); expect(matcher.asymmetricMatch('barfoobaz')).toBe(true);
expect(matcher.asymmetricMatch('barbaz')).toBe(false); expect(matcher.asymmetricMatch('barbaz')).toBe(false);
}); });
it('matches a string against provided string', function() { it('matches a string against provided string', function() {
const matcher = new privateUnderTest.StringMatching('foo'); const matcher = new jasmineUnderTest.StringMatching('foo');
expect(matcher.asymmetricMatch('barfoobaz')).toBe(true); expect(matcher.asymmetricMatch('barfoobaz')).toBe(true);
expect(matcher.asymmetricMatch('barbaz')).toBe(false); expect(matcher.asymmetricMatch('barbaz')).toBe(false);
@@ -15,12 +15,12 @@ describe('StringMatching', function() {
it('raises an Error when the expected is not a String or RegExp', function() { it('raises an Error when the expected is not a String or RegExp', function() {
expect(function() { expect(function() {
new privateUnderTest.StringMatching({}); new jasmineUnderTest.StringMatching({});
}).toThrowError(/not a String or a RegExp/); }).toThrowError(/not a String or a RegExp/);
}); });
it("jasmineToString's itself", function() { it("jasmineToString's itself", function() {
const matching = new privateUnderTest.StringMatching(/^foo/); const matching = new jasmineUnderTest.StringMatching(/^foo/);
expect(matching.jasmineToString()).toEqual( expect(matching.jasmineToString()).toEqual(
'<jasmine.stringMatching(/^foo/)>' '<jasmine.stringMatching(/^foo/)>'
+9 -9
View File
@@ -1,13 +1,13 @@
describe('Truthy', function() { describe('Truthy', function() {
it('is true for a non empty string', function() { it('is true for a non empty string', function() {
const truthy = new privateUnderTest.Truthy(); const truthy = new jasmineUnderTest.Truthy();
expect(truthy.asymmetricMatch('foo')).toBe(true); expect(truthy.asymmetricMatch('foo')).toBe(true);
expect(truthy.asymmetricMatch('')).toBe(false); expect(truthy.asymmetricMatch('')).toBe(false);
}); });
it('is true for a number that is not 0', function() { it('is true for a number that is not 0', function() {
const truthy = new privateUnderTest.Truthy(); const truthy = new jasmineUnderTest.Truthy();
expect(truthy.asymmetricMatch(1)).toBe(true); expect(truthy.asymmetricMatch(1)).toBe(true);
expect(truthy.asymmetricMatch(0)).toBe(false); expect(truthy.asymmetricMatch(0)).toBe(false);
@@ -16,44 +16,44 @@ describe('Truthy', function() {
}); });
it('is true for a function', function() { it('is true for a function', function() {
const truthy = new privateUnderTest.Truthy(); const truthy = new jasmineUnderTest.Truthy();
expect(truthy.asymmetricMatch(function() {})).toBe(true); expect(truthy.asymmetricMatch(function() {})).toBe(true);
}); });
it('is true for an Object', function() { it('is true for an Object', function() {
const truthy = new privateUnderTest.Truthy(); const truthy = new jasmineUnderTest.Truthy();
expect(truthy.asymmetricMatch({})).toBe(true); expect(truthy.asymmetricMatch({})).toBe(true);
}); });
it('is true for a truthful Boolean', function() { it('is true for a truthful Boolean', function() {
const truthy = new privateUnderTest.Truthy(); const truthy = new jasmineUnderTest.Truthy();
expect(truthy.asymmetricMatch(true)).toBe(true); expect(truthy.asymmetricMatch(true)).toBe(true);
expect(truthy.asymmetricMatch(false)).toBe(false); expect(truthy.asymmetricMatch(false)).toBe(false);
}); });
it('is true for an empty object', function() { it('is true for an empty object', function() {
const truthy = new privateUnderTest.Truthy(); const truthy = new jasmineUnderTest.Truthy();
expect(truthy.asymmetricMatch({})).toBe(true); expect(truthy.asymmetricMatch({})).toBe(true);
}); });
it('is true for an empty array', function() { it('is true for an empty array', function() {
const truthy = new privateUnderTest.Truthy(); const truthy = new jasmineUnderTest.Truthy();
expect(truthy.asymmetricMatch([])).toBe(true); expect(truthy.asymmetricMatch([])).toBe(true);
}); });
it('is true for a date', function() { it('is true for a date', function() {
const truthy = new privateUnderTest.Truthy(); const truthy = new jasmineUnderTest.Truthy();
expect(truthy.asymmetricMatch(new Date())).toBe(true); expect(truthy.asymmetricMatch(new Date())).toBe(true);
}); });
it('is true for a infiniti', function() { it('is true for a infiniti', function() {
const truthy = new privateUnderTest.Truthy(); const truthy = new jasmineUnderTest.Truthy();
expect(truthy.asymmetricMatch(Infinity)).toBe(true); expect(truthy.asymmetricMatch(Infinity)).toBe(true);
expect(truthy.asymmetricMatch(-Infinity)).toBe(true); expect(truthy.asymmetricMatch(-Infinity)).toBe(true);
+53 -24
View File
@@ -1,13 +1,42 @@
describe('base helpers', function() { describe('base helpers', function() {
describe('isError', function() { describe('isError_', function() {
it('correctly handles WebSocket events', function(done) {
if (typeof jasmine.getGlobal().WebSocket === 'undefined') {
pending('Environment does not provide WebSocket');
}
const obj = (function() {
const sock = new WebSocket('ws://localhost');
let event;
sock.onerror = function(e) {
event = e;
};
return function() {
return event;
};
})();
let left = 20;
const int = setInterval(function() {
if (obj() || left === 0) {
const result = jasmineUnderTest.isError_(obj());
expect(result).toBe(false);
clearInterval(int);
done();
} else {
left--;
}
}, 100);
});
it('returns true for an Error subclass', function() { it('returns true for an Error subclass', function() {
function MyError() {} function MyError() {}
MyError.prototype = new Error(); MyError.prototype = new Error();
expect(privateUnderTest.isError(new MyError())).toBe(true); expect(jasmineUnderTest.isError_(new MyError())).toBe(true);
}); });
it('returns true for an un-thrown Error with no message in this environment', function() { it('returns true for an un-thrown Error with no message in this environment', function() {
expect(privateUnderTest.isError(new Error())).toBe(true); expect(jasmineUnderTest.isError_(new Error())).toBe(true);
}); });
it('returns true for an Error that originated from another frame', function() { it('returns true for an Error that originated from another frame', function() {
@@ -21,102 +50,102 @@ describe('base helpers', function() {
try { try {
const error = iframe.contentWindow.eval('new Error()'); const error = iframe.contentWindow.eval('new Error()');
expect(privateUnderTest.isError(error)).toBe(true); expect(jasmineUnderTest.isError_(error)).toBe(true);
} finally { } finally {
document.body.removeChild(iframe); document.body.removeChild(iframe);
} }
}); });
it('returns false for a falsy value', function() { it('returns false for a falsy value', function() {
expect(privateUnderTest.isError(undefined)).toBe(false); expect(jasmineUnderTest.isError_(undefined)).toBe(false);
}); });
it('returns false for a non-Error object', function() { it('returns false for a non-Error object', function() {
expect(privateUnderTest.isError({})).toBe(false); expect(jasmineUnderTest.isError_({})).toBe(false);
}); });
}); });
describe('isAsymmetricEqualityTester_', function() { describe('isAsymmetricEqualityTester_', function() {
it('returns false when the argument is falsy', function() { it('returns false when the argument is falsy', function() {
expect(privateUnderTest.isAsymmetricEqualityTester(null)).toBe(false); expect(jasmineUnderTest.isAsymmetricEqualityTester_(null)).toBe(false);
}); });
it('returns false when the argument does not have a asymmetricMatch property', function() { it('returns false when the argument does not have a asymmetricMatch property', function() {
const obj = {}; const obj = {};
expect(privateUnderTest.isAsymmetricEqualityTester(obj)).toBe(false); expect(jasmineUnderTest.isAsymmetricEqualityTester_(obj)).toBe(false);
}); });
it("returns false when the argument's asymmetricMatch is not a function", function() { it("returns false when the argument's asymmetricMatch is not a function", function() {
const obj = { asymmetricMatch: 'yes' }; const obj = { asymmetricMatch: 'yes' };
expect(privateUnderTest.isAsymmetricEqualityTester(obj)).toBe(false); expect(jasmineUnderTest.isAsymmetricEqualityTester_(obj)).toBe(false);
}); });
it("returns true when the argument's asymmetricMatch is a function", function() { it("returns true when the argument's asymmetricMatch is a function", function() {
const obj = { asymmetricMatch: function() {} }; const obj = { asymmetricMatch: function() {} };
expect(privateUnderTest.isAsymmetricEqualityTester(obj)).toBe(true); expect(jasmineUnderTest.isAsymmetricEqualityTester_(obj)).toBe(true);
}); });
}); });
describe('isSet', function() { describe('isSet', function() {
it('returns true when the object is a Set', function() { it('returns true when the object is a Set', function() {
expect(privateUnderTest.isSet(new Set())).toBe(true); expect(jasmineUnderTest.isSet(new Set())).toBe(true);
}); });
it('returns false when the object is not a Set', function() { it('returns false when the object is not a Set', function() {
expect(privateUnderTest.isSet({})).toBe(false); expect(jasmineUnderTest.isSet({})).toBe(false);
}); });
}); });
describe('isURL', function() { describe('isURL', function() {
it('returns true when the object is a URL', function() { it('returns true when the object is a URL', function() {
expect(privateUnderTest.isURL(new URL('http://localhost/'))).toBe(true); expect(jasmineUnderTest.isURL(new URL('http://localhost/'))).toBe(true);
}); });
it('returns false when the object is not a URL', function() { it('returns false when the object is not a URL', function() {
expect(privateUnderTest.isURL({})).toBe(false); expect(jasmineUnderTest.isURL({})).toBe(false);
}); });
}); });
describe('isIterable', function() { describe('isIterable_', function() {
it('returns true when the object is an Array', function() { it('returns true when the object is an Array', function() {
expect(privateUnderTest.isIterable([])).toBe(true); expect(jasmineUnderTest.isIterable_([])).toBe(true);
}); });
it('returns true when the object is a Set', function() { it('returns true when the object is a Set', function() {
expect(privateUnderTest.isIterable(new Set())).toBe(true); expect(jasmineUnderTest.isIterable_(new Set())).toBe(true);
}); });
it('returns true when the object is a Map', function() { it('returns true when the object is a Map', function() {
expect(privateUnderTest.isIterable(new Map())).toBe(true); expect(jasmineUnderTest.isIterable_(new Map())).toBe(true);
}); });
it('returns true when the object implements @@iterator', function() { it('returns true when the object implements @@iterator', function() {
const myIterable = { [Symbol.iterator]: function() {} }; const myIterable = { [Symbol.iterator]: function() {} };
expect(privateUnderTest.isIterable(myIterable)).toBe(true); expect(jasmineUnderTest.isIterable_(myIterable)).toBe(true);
}); });
it('returns false when the object does not implement @@iterator', function() { it('returns false when the object does not implement @@iterator', function() {
expect(privateUnderTest.isIterable({})).toBe(false); expect(jasmineUnderTest.isIterable_({})).toBe(false);
}); });
}); });
describe('isPending', function() { describe('isPending_', function() {
it('returns a promise that resolves to true when the promise is pending', function() { it('returns a promise that resolves to true when the promise is pending', function() {
const promise = new Promise(function() {}); const promise = new Promise(function() {});
return expectAsync(privateUnderTest.isPending(promise)).toBeResolvedTo( return expectAsync(jasmineUnderTest.isPending_(promise)).toBeResolvedTo(
true true
); );
}); });
it('returns a promise that resolves to false when the promise is resolved', function() { it('returns a promise that resolves to false when the promise is resolved', function() {
const promise = Promise.resolve(); const promise = Promise.resolve();
return expectAsync(privateUnderTest.isPending(promise)).toBeResolvedTo( return expectAsync(jasmineUnderTest.isPending_(promise)).toBeResolvedTo(
false false
); );
}); });
it('returns a promise that resolves to false when the promise is rejected', function() { it('returns a promise that resolves to false when the promise is rejected', function() {
const promise = Promise.reject(new Error('nope')); const promise = Promise.reject(new Error('nope'));
return expectAsync(privateUnderTest.isPending(promise)).toBeResolvedTo( return expectAsync(jasmineUnderTest.isPending_(promise)).toBeResolvedTo(
false false
); );
}); });
+31 -9
View File
@@ -1,13 +1,13 @@
describe('buildExpectationResult', function() { describe('buildExpectationResult', function() {
it('defaults to passed', function() { it('defaults to passed', function() {
const result = privateUnderTest.buildExpectationResult({ const result = jasmineUnderTest.buildExpectationResult({
passed: 'some-value' passed: 'some-value'
}); });
expect(result.passed).toBe('some-value'); expect(result.passed).toBe('some-value');
}); });
it('message defaults to Passed for passing specs', function() { it('message defaults to Passed for passing specs', function() {
const result = privateUnderTest.buildExpectationResult({ const result = jasmineUnderTest.buildExpectationResult({
passed: true, passed: true,
message: 'some-value' message: 'some-value'
}); });
@@ -15,7 +15,7 @@ describe('buildExpectationResult', function() {
}); });
it('message returns the message for failing expectations', function() { it('message returns the message for failing expectations', function() {
const result = privateUnderTest.buildExpectationResult({ const result = jasmineUnderTest.buildExpectationResult({
passed: false, passed: false,
message: 'some-value' message: 'some-value'
}); });
@@ -24,7 +24,7 @@ describe('buildExpectationResult', function() {
describe('When the error property is provided', function() { describe('When the error property is provided', function() {
it('sets the message to the formatted error', function() { it('sets the message to the formatted error', function() {
const result = privateUnderTest.buildExpectationResult({ const result = jasmineUnderTest.buildExpectationResult({
passed: false, passed: false,
error: { message: 'foo', fileName: 'somefile.js' } error: { message: 'foo', fileName: 'somefile.js' }
}); });
@@ -33,7 +33,7 @@ describe('buildExpectationResult', function() {
}); });
it('delegates stack formatting to the provided formatter', function() { it('delegates stack formatting to the provided formatter', function() {
const result = privateUnderTest.buildExpectationResult({ const result = jasmineUnderTest.buildExpectationResult({
passed: false, passed: false,
error: { stack: 'foo', extra: 'wombat' } error: { stack: 'foo', extra: 'wombat' }
}); });
@@ -46,7 +46,7 @@ describe('buildExpectationResult', function() {
describe('When the errorForStack property is provided', function() { describe('When the errorForStack property is provided', function() {
it('builds the stack trace using errorForStack instead of Error', function() { it('builds the stack trace using errorForStack instead of Error', function() {
const result = privateUnderTest.buildExpectationResult({ const result = jasmineUnderTest.buildExpectationResult({
passed: false, passed: false,
errorForStack: { stack: 'foo' }, errorForStack: { stack: 'foo' },
error: { stack: 'bar' } error: { stack: 'bar' }
@@ -57,34 +57,56 @@ describe('buildExpectationResult', function() {
}); });
it('matcherName returns passed matcherName', function() { it('matcherName returns passed matcherName', function() {
const result = privateUnderTest.buildExpectationResult({ const result = jasmineUnderTest.buildExpectationResult({
matcherName: 'some-value' matcherName: 'some-value'
}); });
expect(result.matcherName).toBe('some-value'); expect(result.matcherName).toBe('some-value');
}); });
it('expected returns passed expected', function() {
const result = jasmineUnderTest.buildExpectationResult({
expected: 'some-value'
});
expect(result.expected).toBe('some-value');
});
it('actual returns passed actual', function() {
const result = jasmineUnderTest.buildExpectationResult({
actual: 'some-value'
});
expect(result.actual).toBe('some-value');
});
it('handles nodejs assertions', function() { it('handles nodejs assertions', function() {
if (typeof require === 'undefined') { if (typeof require === 'undefined') {
pending('This test only runs in Node'); pending('This test only runs in Node');
} }
const assert = require('assert'); const assert = require('assert');
const value = 8421;
const expectedValue = 'JasmineExpectationTestValue';
let error; let error;
try { try {
assert.equal('a', 'b'); assert.equal(value, expectedValue);
} catch (e) { } catch (e) {
error = e; error = e;
} }
expect(error.code).toEqual('ERR_ASSERTION'); expect(error.code).toEqual('ERR_ASSERTION');
expect(error.actual).toEqual(value);
expect(error.expected).toEqual(expectedValue);
expect(error.operator).toEqual('=='); expect(error.operator).toEqual('==');
const result = privateUnderTest.buildExpectationResult({ const result = jasmineUnderTest.buildExpectationResult({
passed: false, passed: false,
matcherName: '', matcherName: '',
expected: '',
actual: '',
error: error error: error
}); });
expect(result.code).toEqual('ERR_ASSERTION'); expect(result.code).toEqual('ERR_ASSERTION');
expect(result.actual).toEqual(value);
expect(result.expected).toEqual(expectedValue);
expect(result.matcherName).toEqual('assert =='); expect(result.matcherName).toEqual('assert ==');
}); });
}); });
+2 -2
View File
@@ -1,12 +1,12 @@
describe('formatErrorMsg', function() { describe('formatErrorMsg', function() {
it('should format an error with a domain', function() { it('should format an error with a domain', function() {
const formator = privateUnderTest.formatErrorMsg('api'); const formator = jasmineUnderTest.formatErrorMsg('api');
expect(formator('message')).toBe('api : message'); expect(formator('message')).toBe('api : message');
expect(formator('message2')).toBe('api : message2'); expect(formator('message2')).toBe('api : message2');
}); });
it('should format an error with a domain and usage', function() { it('should format an error with a domain and usage', function() {
const formator = privateUnderTest.formatErrorMsg('api', 'with a param'); const formator = jasmineUnderTest.formatErrorMsg('api', 'with a param');
expect(formator('message')).toBe('api : message\nUsage: with a param'); expect(formator('message')).toBe('api : message\nUsage: with a param');
expect(formator('message2')).toBe('api : message2\nUsage: with a param'); expect(formator('message2')).toBe('api : message2\nUsage: with a param');
}); });
@@ -1,7 +1,7 @@
describe('Asymmetric equality testers (Integration)', function() { describe('Asymmetric equality testers (Integration)', function() {
function verifyPasses(expectations) { function verifyPasses(expectations) {
it('passes', async function() { it('passes', async function() {
const env = new privateUnderTest.Env(); const env = new jasmineUnderTest.Env();
env.it('a spec', function() { env.it('a spec', function() {
expectations(env); expectations(env);
}); });
@@ -30,7 +30,7 @@ describe('Asymmetric equality testers (Integration)', function() {
function verifyFails(expectations) { function verifyFails(expectations) {
it('fails', async function() { it('fails', async function() {
const env = new privateUnderTest.Env(); const env = new jasmineUnderTest.Env();
env.it('a spec', function() { env.it('a spec', function() {
expectations(env); expectations(env);
}); });
@@ -2,7 +2,7 @@ describe('Custom Async Matchers (Integration)', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
env.configure({ random: false }); env.configure({ random: false });
}); });
@@ -107,7 +107,7 @@ describe('Custom Async Matchers (Integration)', function() {
const specExpectations = function() { const specExpectations = function() {
expect(matcherFactorySpy).toHaveBeenCalledWith( expect(matcherFactorySpy).toHaveBeenCalledWith(
jasmine.any(privateUnderTest.MatchersUtil) jasmine.any(jasmineUnderTest.MatchersUtil)
); );
}; };
+2 -2
View File
@@ -2,7 +2,7 @@ describe('Custom Matchers (Integration)', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
env.configure({ random: false }); env.configure({ random: false });
}); });
@@ -230,7 +230,7 @@ describe('Custom Matchers (Integration)', function() {
await env.execute(); await env.execute();
expect(matcherFactorySpy).toHaveBeenCalledWith( expect(matcherFactorySpy).toHaveBeenCalledWith(
jasmine.any(privateUnderTest.MatchersUtil) jasmine.any(jasmineUnderTest.MatchersUtil)
); );
}); });
@@ -2,7 +2,7 @@ describe('Custom object formatters', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
env.configure({ random: false }); env.configure({ random: false });
}); });
@@ -2,7 +2,7 @@ describe('Custom Spy Strategies (Integration)', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
env.configure({ random: false }); env.configure({ random: false });
}); });
@@ -2,7 +2,7 @@ describe('Default Spy Strategy (Integration)', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
env.configure({ random: false }); env.configure({ random: false });
}); });
+1 -1
View File
@@ -3,7 +3,7 @@ describe('Deprecation (integration)', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
}); });
afterEach(function() { afterEach(function() {
+90 -102
View File
@@ -4,7 +4,7 @@ describe('Env integration', function() {
beforeEach(function() { beforeEach(function() {
specHelpers.registerIntegrationMatchers(); specHelpers.registerIntegrationMatchers();
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
}); });
afterEach(function() { afterEach(function() {
@@ -199,7 +199,7 @@ describe('Env integration', function() {
} else { } else {
secondSpecContext = this; secondSpecContext = this;
} }
expect(this).toEqual(new privateUnderTest.UserContext()); expect(this).toEqual(new jasmineUnderTest.UserContext());
}); });
env.it('sync spec', function() { env.it('sync spec', function() {
@@ -229,7 +229,7 @@ describe('Env integration', function() {
env.beforeEach(function() { env.beforeEach(function() {
specContext = this; specContext = this;
expect(this).toEqual(new privateUnderTest.UserContext()); expect(this).toEqual(new jasmineUnderTest.UserContext());
}); });
env.it('sync spec', function(underTestCallback) { env.it('sync spec', function(underTestCallback) {
@@ -913,7 +913,6 @@ describe('Env integration', function() {
}); });
env.configure({ env.configure({
random: false,
specFilter: function(spec) { specFilter: function(spec) {
return /^first suite/.test(spec.getFullName()); return /^first suite/.test(spec.getFullName());
} }
@@ -921,7 +920,10 @@ describe('Env integration', function() {
await env.execute(); await env.execute();
expect(calls).toEqual(['first spec', 'second spec']); expect(calls.length).toEqual(2);
expect(calls).toEqual(
jasmine.arrayContaining(['first spec', 'second spec'])
);
expect(suiteCallback).toHaveBeenCalled(); expect(suiteCallback).toHaveBeenCalled();
}); });
@@ -1110,21 +1112,12 @@ describe('Env integration', function() {
); );
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ env = new jasmineUnderTest.Env({
global: { global: {
setTimeout: globalSetTimeout, setTimeout: globalSetTimeout,
clearTimeout: clearTimeout, clearTimeout: clearTimeout,
addEventListener() {},
removeEventListener() {},
queueMicrotask: function(fn) { queueMicrotask: function(fn) {
queueMicrotask(fn); queueMicrotask(fn);
},
// Enough Node globals to make getStackClearer() return the microtask
// implementation, which is the easiest to mock
process: {
versions: {
node: ''
}
} }
} }
}); });
@@ -1184,11 +1177,11 @@ describe('Env integration', function() {
env.cleanup_(); env.cleanup_();
// explicitly pass in timing functions so we can make sure that clear stack always works // explicitly pass in timing functions so we can make sure that clear stack always works
// no matter how long the suite in the spec is // no matter how long the suite in the spec is
env = new privateUnderTest.Env({ env = new jasmineUnderTest.Env({
global: { global: {
setTimeout: function(cb, t) { setTimeout: function(cb, t) {
const stack = new Error().stack; const stack = new Error().stack;
if (stack.indexOf('clearStack') >= 0) { if (stack.indexOf('ClearStack') >= 0) {
return realSetTimeout(cb, t); return realSetTimeout(cb, t);
} else { } else {
return setTimeout(cb, t); return setTimeout(cb, t);
@@ -1197,17 +1190,8 @@ describe('Env integration', function() {
clearTimeout: clearTimeout, clearTimeout: clearTimeout,
setInterval: setInterval, setInterval: setInterval,
clearInterval: clearInterval, clearInterval: clearInterval,
addEventListener() {},
removeEventListener() {},
queueMicrotask: function(fn) { queueMicrotask: function(fn) {
queueMicrotask(fn); queueMicrotask(fn);
},
// Enough Node globals to make getStackClearer() return the microtask
// implementation, which is the easiest to mock
process: {
versions: {
node: ''
}
} }
} }
}); });
@@ -1289,9 +1273,7 @@ describe('Env integration', function() {
await env.execute(); await env.execute();
expect(reporter.specDone).toHaveBeenCalledTimes(1); expect(reporter.specDone).toHaveBeenCalledTimes(1);
const event = reporter.specDone.calls.argsFor(0)[0]; const event = reporter.specDone.calls.argsFor(0)[0];
jasmine.debugLog( jasmine.debugLog('Spec result: ' + jasmine.basicPrettyPrinter_(event));
'Spec result: ' + jasmine.private.basicPrettyPrinter(event)
);
expect(event).toEqual(jasmine.objectContaining({ status: 'passed' })); expect(event).toEqual(jasmine.objectContaining({ status: 'passed' }));
jasmine.clock().tick(1); jasmine.clock().tick(1);
@@ -1557,7 +1539,7 @@ describe('Env integration', function() {
expect(reporter.jasmineStarted).toHaveBeenCalledWith({ expect(reporter.jasmineStarted).toHaveBeenCalledWith({
totalSpecsDefined: 1, totalSpecsDefined: 1,
order: { random: true, seed: jasmine.any(String) }, order: jasmine.any(jasmineUnderTest.Order),
parallel: false parallel: false
}); });
@@ -1592,7 +1574,7 @@ describe('Env integration', function() {
expect(reporter.jasmineStarted).toHaveBeenCalledWith({ expect(reporter.jasmineStarted).toHaveBeenCalledWith({
totalSpecsDefined: 1, totalSpecsDefined: 1,
order: { random: true, seed: jasmine.any(String) }, order: jasmine.any(jasmineUnderTest.Order),
parallel: false parallel: false
}); });
@@ -1618,6 +1600,15 @@ describe('Env integration', function() {
suiteFullNameToId[e.fullName] = e.id; suiteFullNameToId[e.fullName] = e.id;
}); });
// Clone args to work around Jasmine mutating the result after passing it
// to the reporter event.
// TODO: remove this once Jasmine no longer does that
const clone = structuredClone.bind(globalThis);
reporter.specStarted.calls.saveArgumentsByValue(clone);
reporter.specDone.calls.saveArgumentsByValue(clone);
reporter.specStarted.calls.saveArgumentsByValue(clone);
reporter.suiteDone.calls.saveArgumentsByValue(clone);
env.configure({ random: false }); env.configure({ random: false });
env.addReporter(reporter); env.addReporter(reporter);
@@ -1648,7 +1639,7 @@ describe('Env integration', function() {
expect(reporter.jasmineStarted).toHaveBeenCalledWith({ expect(reporter.jasmineStarted).toHaveBeenCalledWith({
totalSpecsDefined: 6, totalSpecsDefined: 6,
order: { random: false }, order: jasmine.any(jasmineUnderTest.Order),
parallel: false parallel: false
}); });
@@ -1656,18 +1647,15 @@ describe('Env integration', function() {
expect(reporter.specDone.calls.count()).toBe(6); expect(reporter.specDone.calls.count()).toBe(6);
const baseSpecEvent = { const baseSpecEvent = {
id: jasmine.any(String),
filename: jasmine.any(String)
};
const baseSpecDoneEvent = {
...baseSpecEvent,
passedExpectations: [], passedExpectations: [],
failedExpectations: [], failedExpectations: [],
deprecationWarnings: [], deprecationWarnings: [],
pendingReason: '', pendingReason: '',
duration: null, duration: null,
properties: null, properties: null,
debugLogs: null debugLogs: null,
id: jasmine.any(String),
filename: jasmine.any(String)
}; };
expect(reporter.specStarted.calls.argsFor(0)[0]).toEqual({ expect(reporter.specStarted.calls.argsFor(0)[0]).toEqual({
@@ -1677,7 +1665,7 @@ describe('Env integration', function() {
parentSuiteId: null parentSuiteId: null
}); });
expect(reporter.specDone.calls.argsFor(0)[0]).toEqual({ expect(reporter.specDone.calls.argsFor(0)[0]).toEqual({
...baseSpecDoneEvent, ...baseSpecEvent,
description: 'a top level spec', description: 'a top level spec',
fullName: 'a top level spec', fullName: 'a top level spec',
status: 'passed', status: 'passed',
@@ -1691,19 +1679,13 @@ describe('Env integration', function() {
parentSuiteId: suiteFullNameToId['A Suite'] parentSuiteId: suiteFullNameToId['A Suite']
}); });
expect(reporter.specDone.calls.argsFor(1)[0]).toEqual({ expect(reporter.specDone.calls.argsFor(1)[0]).toEqual({
...baseSpecDoneEvent, ...baseSpecEvent,
description: 'with a spec', description: 'with a spec',
fullName: 'A Suite with a spec', fullName: 'A Suite with a spec',
status: 'passed', status: 'passed',
parentSuiteId: suiteFullNameToId['A Suite'], parentSuiteId: suiteFullNameToId['A Suite'],
passedExpectations: [ passedExpectations: [
{ { matcherName: 'toBe', message: 'Passed.', stack: '', passed: true }
matcherName: 'toBe',
message: 'Passed.',
stack: '',
passed: true,
globalErrorType: undefined
}
], ],
duration: jasmine.any(Number) duration: jasmine.any(Number)
}); });
@@ -1712,10 +1694,11 @@ describe('Env integration', function() {
...baseSpecEvent, ...baseSpecEvent,
description: "with an x'ed spec", description: "with an x'ed spec",
fullName: "A Suite with a nested suite with an x'ed spec", fullName: "A Suite with a nested suite with an x'ed spec",
parentSuiteId: suiteFullNameToId['A Suite with a nested suite'] parentSuiteId: suiteFullNameToId['A Suite with a nested suite'],
pendingReason: 'Temporarily disabled with xit'
}); });
expect(reporter.specDone.calls.argsFor(2)[0]).toEqual({ expect(reporter.specDone.calls.argsFor(2)[0]).toEqual({
...baseSpecDoneEvent, ...baseSpecEvent,
description: "with an x'ed spec", description: "with an x'ed spec",
fullName: "A Suite with a nested suite with an x'ed spec", fullName: "A Suite with a nested suite with an x'ed spec",
status: 'pending', status: 'pending',
@@ -1731,7 +1714,7 @@ describe('Env integration', function() {
parentSuiteId: suiteFullNameToId['A Suite with a nested suite'] parentSuiteId: suiteFullNameToId['A Suite with a nested suite']
}); });
expect(reporter.specDone.calls.argsFor(3)[0]).toEqual({ expect(reporter.specDone.calls.argsFor(3)[0]).toEqual({
...baseSpecDoneEvent, ...baseSpecEvent,
description: 'with a spec', description: 'with a spec',
fullName: 'A Suite with a nested suite with a spec', fullName: 'A Suite with a nested suite with a spec',
status: 'failed', status: 'failed',
@@ -1752,7 +1735,7 @@ describe('Env integration', function() {
parentSuiteId: suiteFullNameToId['A Suite with only non-executable specs'] parentSuiteId: suiteFullNameToId['A Suite with only non-executable specs']
}); });
expect(reporter.specDone.calls.argsFor(4)[0]).toEqual({ expect(reporter.specDone.calls.argsFor(4)[0]).toEqual({
...baseSpecDoneEvent, ...baseSpecEvent,
description: 'is pending', description: 'is pending',
status: 'pending', status: 'pending',
fullName: 'A Suite with only non-executable specs is pending', fullName: 'A Suite with only non-executable specs is pending',
@@ -1765,10 +1748,12 @@ describe('Env integration', function() {
...baseSpecEvent, ...baseSpecEvent,
description: 'is xed', description: 'is xed',
fullName: 'A Suite with only non-executable specs is xed', fullName: 'A Suite with only non-executable specs is xed',
parentSuiteId: suiteFullNameToId['A Suite with only non-executable specs'] parentSuiteId:
suiteFullNameToId['A Suite with only non-executable specs'],
pendingReason: 'Temporarily disabled with xit'
}); });
expect(reporter.specDone.calls.argsFor(5)[0]).toEqual({ expect(reporter.specDone.calls.argsFor(5)[0]).toEqual({
...baseSpecDoneEvent, ...baseSpecEvent,
description: 'is xed', description: 'is xed',
status: 'pending', status: 'pending',
fullName: 'A Suite with only non-executable specs is xed', fullName: 'A Suite with only non-executable specs is xed',
@@ -1783,12 +1768,10 @@ describe('Env integration', function() {
const baseSuiteEvent = { const baseSuiteEvent = {
id: jasmine.any(String), id: jasmine.any(String),
filename: jasmine.any(String) filename: jasmine.any(String),
};
const baseSuiteDoneEvent = {
...baseSuiteEvent,
failedExpectations: [], failedExpectations: [],
deprecationWarnings: [], deprecationWarnings: [],
duration: null,
properties: null properties: null
}; };
@@ -1799,7 +1782,7 @@ describe('Env integration', function() {
parentSuiteId: null parentSuiteId: null
}); });
expect(reporter.suiteDone.calls.argsFor(2)[0]).toEqual({ expect(reporter.suiteDone.calls.argsFor(2)[0]).toEqual({
...baseSuiteDoneEvent, ...baseSuiteEvent,
description: 'A Suite', description: 'A Suite',
fullName: 'A Suite', fullName: 'A Suite',
status: 'passed', status: 'passed',
@@ -1814,7 +1797,7 @@ describe('Env integration', function() {
parentSuiteId: suiteFullNameToId['A Suite'] parentSuiteId: suiteFullNameToId['A Suite']
}); });
expect(reporter.suiteDone.calls.argsFor(0)[0]).toEqual({ expect(reporter.suiteDone.calls.argsFor(0)[0]).toEqual({
...baseSuiteDoneEvent, ...baseSuiteEvent,
description: 'with a nested suite', description: 'with a nested suite',
status: 'passed', status: 'passed',
fullName: 'A Suite with a nested suite', fullName: 'A Suite with a nested suite',
@@ -1829,7 +1812,7 @@ describe('Env integration', function() {
parentSuiteId: suiteFullNameToId['A Suite'] parentSuiteId: suiteFullNameToId['A Suite']
}); });
expect(reporter.suiteDone.calls.argsFor(1)[0]).toEqual({ expect(reporter.suiteDone.calls.argsFor(1)[0]).toEqual({
...baseSuiteDoneEvent, ...baseSuiteEvent,
description: 'with only non-executable specs', description: 'with only non-executable specs',
status: 'passed', status: 'passed',
fullName: 'A Suite with only non-executable specs', fullName: 'A Suite with only non-executable specs',
@@ -1938,10 +1921,12 @@ describe('Env integration', function() {
expect(reporter.jasmineStarted).toHaveBeenCalled(); expect(reporter.jasmineStarted).toHaveBeenCalled();
const startedArg = reporter.jasmineStarted.calls.argsFor(0)[0]; const startedArg = reporter.jasmineStarted.calls.argsFor(0)[0];
expect(startedArg.order).toEqual({ random: true, seed: '123456' }); expect(startedArg.order.random).toEqual(true);
expect(startedArg.order.seed).toEqual('123456');
const doneArg = reporter.jasmineDone.calls.argsFor(0)[0]; const doneArg = reporter.jasmineDone.calls.argsFor(0)[0];
expect(doneArg.order).toEqual({ random: true, seed: '123456' }); expect(doneArg.order.random).toEqual(true);
expect(doneArg.order.seed).toEqual('123456');
}); });
it('coerces the random seed to a string if it is a number', async function() { it('coerces the random seed to a string if it is a number', async function() {
@@ -2061,7 +2046,7 @@ describe('Env integration', function() {
expect(reporter.jasmineStarted).toHaveBeenCalledWith({ expect(reporter.jasmineStarted).toHaveBeenCalledWith({
totalSpecsDefined: 1, totalSpecsDefined: 1,
order: { random: true, seed: jasmine.any(String) }, order: jasmine.any(jasmineUnderTest.Order),
parallel: false parallel: false
}); });
@@ -2385,7 +2370,7 @@ describe('Env integration', function() {
}); });
it('throws an exception if you try to getSpecProperty outside of a spec', async function() { it('throws an exception if you try to getSpecProperty outside of a spec', async function() {
const env = new privateUnderTest.Env(); const env = new jasmineUnderTest.Env();
let exception; let exception;
env.describe('a suite', function() { env.describe('a suite', function() {
@@ -2406,7 +2391,7 @@ describe('Env integration', function() {
}); });
it('reports test properties on specs', async function() { it('reports test properties on specs', async function() {
const env = new privateUnderTest.Env(), const env = new jasmineUnderTest.Env(),
reporter = jasmine.createSpyObj('reporter', ['suiteDone', 'specDone']); reporter = jasmine.createSpyObj('reporter', ['suiteDone', 'specDone']);
reporter.specDone.and.callFake(function(e) { reporter.specDone.and.callFake(function(e) {
@@ -2439,7 +2424,7 @@ describe('Env integration', function() {
}); });
it('throws an exception if you try to setSpecProperty outside of a spec', async function() { it('throws an exception if you try to setSpecProperty outside of a spec', async function() {
const env = new privateUnderTest.Env(); const env = new jasmineUnderTest.Env();
let exception; let exception;
env.describe('a suite', function() { env.describe('a suite', function() {
@@ -2460,7 +2445,7 @@ describe('Env integration', function() {
}); });
it('reports test properties on suites', async function() { it('reports test properties on suites', async function() {
const env = new privateUnderTest.Env(), const env = new jasmineUnderTest.Env(),
reporter = jasmine.createSpyObj('reporter', [ reporter = jasmine.createSpyObj('reporter', [
'jasmineDone', 'jasmineDone',
'suiteDone', 'suiteDone',
@@ -2487,7 +2472,7 @@ describe('Env integration', function() {
}); });
it('throws an exception if you try to setSuiteProperty outside of a suite', function(done) { it('throws an exception if you try to setSuiteProperty outside of a suite', function(done) {
const env = new privateUnderTest.Env(); const env = new jasmineUnderTest.Env();
try { try {
env.setSuiteProperty('a', 'Bee'); env.setSuiteProperty('a', 'Bee');
@@ -2821,18 +2806,12 @@ describe('Env integration', function() {
}, },
queueMicrotask: function(fn) { queueMicrotask: function(fn) {
queueMicrotask(fn); queueMicrotask(fn);
},
// Enough Node globals to make getStackClearer() return the microtask
// implementation, which is the easiest to mock
process: {
versions: {
node: ''
}
} }
}; };
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
const reporter = jasmine.createSpyObj('reporter', [ const reporter = jasmine.createSpyObj('reporter', [
'jasmineDone', 'jasmineDone',
'suiteDone', 'suiteDone',
@@ -2933,7 +2912,7 @@ describe('Env integration', function() {
}); });
it('should report deprecation stack with an error object', async function() { it('should report deprecation stack with an error object', async function() {
const exceptionFormatter = new privateUnderTest.ExceptionFormatter(), const exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
reporter = jasmine.createSpyObj('reporter', [ reporter = jasmine.createSpyObj('reporter', [
'jasmineDone', 'jasmineDone',
'suiteDone', 'suiteDone',
@@ -3207,7 +3186,7 @@ describe('Env integration', function() {
const result = jasmineDone.calls.argsFor(0)[0]; const result = jasmineDone.calls.argsFor(0)[0];
expect(result.failedExpectations).toEqual([ expect(result.failedExpectations).toEqual([
{ jasmine.objectContaining({
passed: false, passed: false,
globalErrorType: 'lateExpectation', globalErrorType: 'lateExpectation',
message: message:
@@ -3216,14 +3195,13 @@ describe('Env integration', function() {
'1. Did you forget to return or await the result of expectAsync?\n' + '1. Did you forget to return or await the result of expectAsync?\n' +
'2. Was done() invoked before an async operation completed?\n' + '2. Was done() invoked before an async operation completed?\n' +
'3. Did an expectation follow a call to done()?', '3. Did an expectation follow a call to done()?',
matcherName: 'toBeResolved', matcherName: 'toBeResolved'
stack: jasmine.any(String) })
}
]); ]);
}); });
it('supports asymmetric equality testers that take a matchersUtil', async function() { it('supports asymmetric equality testers that take a matchersUtil', async function() {
const env = new privateUnderTest.Env(); const env = new jasmineUnderTest.Env();
env.it('spec using custom asymmetric equality tester', function() { env.it('spec using custom asymmetric equality tester', function() {
const customEqualityFn = function(a, b) { const customEqualityFn = function(a, b) {
@@ -3280,25 +3258,27 @@ describe('Env integration', function() {
}); });
it('is resolved after the stack is cleared', function(done) { it('is resolved after the stack is cleared', function(done) {
const stackClearer = privateUnderTest.getStackClearer( const realClearStack = jasmineUnderTest.getClearStack(
jasmineUnderTest.getGlobal() jasmineUnderTest.getGlobal()
); ),
spyOn(stackClearer, 'clearStack').and.callThrough(); clearStackSpy = jasmine
spyOn(privateUnderTest, 'getStackClearer').and.returnValue(stackClearer); .createSpy('clearStack')
.and.callFake(realClearStack);
spyOn(jasmineUnderTest, 'getClearStack').and.returnValue(clearStackSpy);
// Create a new env that has the clearStack defined above // Create a new env that has the clearStack defined above
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
env.describe('suite', function() { env.describe('suite', function() {
env.it('spec', function() {}); env.it('spec', function() {});
}); });
env.execute(null).then(function() { env.execute(null).then(function() {
expect(stackClearer.clearStack).toHaveBeenCalled(); // (many times) expect(clearStackSpy).toHaveBeenCalled(); // (many times)
stackClearer.clearStack.calls.reset(); clearStackSpy.calls.reset();
setTimeout(function() { setTimeout(function() {
expect(stackClearer.clearStack).not.toHaveBeenCalled(); expect(clearStackSpy).not.toHaveBeenCalled();
done(); done();
}); });
}); });
@@ -3316,7 +3296,7 @@ describe('Env integration', function() {
jasmineUnderTest.DEFAULT_TIMEOUT_INTERVAL = 123456; // a distinctive value jasmineUnderTest.DEFAULT_TIMEOUT_INTERVAL = 123456; // a distinctive value
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
env.describe('suite', function() { env.describe('suite', function() {
env.it('spec', function() {}); env.it('spec', function() {});
@@ -3387,15 +3367,17 @@ describe('Env integration', function() {
}); });
it('is called after the stack is cleared', async function() { it('is called after the stack is cleared', async function() {
const stackClearer = privateUnderTest.getStackClearer( const realClearStack = jasmineUnderTest.getClearStack(
jasmineUnderTest.getGlobal() jasmineUnderTest.getGlobal()
); ),
spyOn(stackClearer, 'clearStack').and.callThrough(); clearStackSpy = jasmine
spyOn(privateUnderTest, 'getStackClearer').and.returnValue(stackClearer); .createSpy('clearStack')
.and.callFake(realClearStack);
spyOn(jasmineUnderTest, 'getClearStack').and.returnValue(clearStackSpy);
// Create a new env that has the clearStack defined above // Create a new env that has the clearStack defined above
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
env.describe('suite', function() { env.describe('suite', function() {
env.it('spec', function() {}); env.it('spec', function() {});
@@ -3403,12 +3385,12 @@ describe('Env integration', function() {
await env.execute(); await env.execute();
expect(stackClearer.clearStack).toHaveBeenCalled(); // (many times) expect(clearStackSpy).toHaveBeenCalled(); // (many times)
stackClearer.clearStack.calls.reset(); clearStackSpy.calls.reset();
await new Promise(resolve => setTimeout(resolve)); await new Promise(resolve => setTimeout(resolve));
expect(stackClearer.clearStack).not.toHaveBeenCalled(); expect(clearStackSpy).not.toHaveBeenCalled();
}); });
it('is called after QueueRunner timeouts are cleared', async function() { it('is called after QueueRunner timeouts are cleared', async function() {
@@ -3423,7 +3405,7 @@ describe('Env integration', function() {
jasmineUnderTest.DEFAULT_TIMEOUT_INTERVAL = 123456; // a distinctive value jasmineUnderTest.DEFAULT_TIMEOUT_INTERVAL = 123456; // a distinctive value
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
env.describe('suite', function() { env.describe('suite', function() {
env.it('spec', function() {}); env.it('spec', function() {});
@@ -3749,8 +3731,11 @@ describe('Env integration', function() {
await env.execute(); await env.execute();
expect(thrown).toBeInstanceOf(Error); expect(thrown).toBeInstanceOf(Error);
expect(thrown.passed).toEqual(false);
expect(thrown.matcherName).toEqual('toEqual'); expect(thrown.matcherName).toEqual('toEqual');
expect(thrown.message).toEqual('Expected 1 to equal 2.'); expect(thrown.message).toEqual('Expected 1 to equal 2.');
expect(thrown.actual).toEqual(1);
expect(thrown.expected).toEqual(2);
}); });
it('does not throw when the matcher passes', async function() { it('does not throw when the matcher passes', async function() {
@@ -3802,10 +3787,13 @@ describe('Env integration', function() {
await env.execute(); await env.execute();
expect(thrown).toBeInstanceOf(Error); expect(thrown).toBeInstanceOf(Error);
expect(thrown.passed).toEqual(false);
expect(thrown.matcherName).toEqual('toBeResolvedTo'); expect(thrown.matcherName).toEqual('toBeResolvedTo');
expect(thrown.message).toEqual( expect(thrown.message).toEqual(
"Expected a promise to be resolved to 'b' but it was resolved to 'a'." "Expected a promise to be resolved to 'b' but it was resolved to 'a'."
); );
expect(thrown.actual).toBe(promise);
expect(thrown.expected).toEqual('b');
}); });
it('does not throw when the matcher passes', async function() { it('does not throw when the matcher passes', async function() {
+256 -87
View File
@@ -4,15 +4,15 @@ describe('Global error handling (integration)', function() {
beforeEach(function() { beforeEach(function() {
specHelpers.registerIntegrationMatchers(); specHelpers.registerIntegrationMatchers();
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
}); });
afterEach(function() { afterEach(function() {
env.cleanup_(); env.cleanup_();
}); });
function mockGlobal() { it('reports errors that occur during loading', async function() {
return { const global = {
...browserEventMethods(), ...browserEventMethods(),
setTimeout: function(fn, delay) { setTimeout: function(fn, delay) {
return setTimeout(fn, delay); return setTimeout(fn, delay);
@@ -23,21 +23,12 @@ describe('Global error handling (integration)', function() {
queueMicrotask: function(fn) { queueMicrotask: function(fn) {
queueMicrotask(fn); queueMicrotask(fn);
}, },
onerror: function() {}, onerror: function() {}
// Enough Node globals to make getStackClearer() return the microtask
// implementation, which is the easiest to mock
process: {
versions: {
node: ''
}
}
}; };
} spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
it('reports errors that occur during loading', async function() {
const global = mockGlobal();
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
const reporter = jasmine.createSpyObj('reporter', [ const reporter = jasmine.createSpyObj('reporter', [
'jasmineDone', 'jasmineDone',
'suiteDone', 'suiteDone',
@@ -62,34 +53,45 @@ describe('Global error handling (integration)', function() {
passed: false, passed: false,
globalErrorType: 'load', globalErrorType: 'load',
message: 'Uncaught SyntaxError: Unexpected end of input', message: 'Uncaught SyntaxError: Unexpected end of input',
stack: undefined,
filename: 'borkenSpec.js', filename: 'borkenSpec.js',
lineno: 42, lineno: 42
matcherName: undefined,
stack: jasmine.any(String)
}, },
{ {
passed: false, passed: false,
globalErrorType: 'load', globalErrorType: 'load',
message: 'ENOCHEESE', message: 'ENOCHEESE',
matcherName: undefined, stack: error.stack,
stack: jasmine.any(String) filename: undefined,
lineno: undefined
} }
]); ]);
}); });
describe('If suppressLoadErrors: true was passed', function() { describe('If suppressLoadErrors: true was passed', function() {
it('does not install a global error handler during loading', async function() { it('does not install a global error handler during loading', async function() {
const global = mockGlobal();
const originalOnerror = jasmine.createSpy('original onerror'); const originalOnerror = jasmine.createSpy('original onerror');
global.onerror = originalOnerror; const global = {
const globalErrors = new privateUnderTest.GlobalErrors(global); ...browserEventMethods(),
setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
},
onerror: originalOnerror
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
const globalErrors = new jasmineUnderTest.GlobalErrors(global);
const onerror = jasmine.createSpy('onerror'); const onerror = jasmine.createSpy('onerror');
globalErrors.pushListener(onerror); globalErrors.pushListener(onerror);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ env = new jasmineUnderTest.Env({
suppressLoadErrors: true, suppressLoadErrors: true,
global,
GlobalErrors: function() { GlobalErrors: function() {
return globalErrors; return globalErrors;
} }
@@ -113,9 +115,21 @@ describe('Global error handling (integration)', function() {
describe('Handling unhandled exceptions', function() { describe('Handling unhandled exceptions', function() {
it('routes unhandled exceptions to the running spec', async function() { it('routes unhandled exceptions to the running spec', async function() {
const global = mockGlobal(); const global = {
...browserEventMethods(),
setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
const reporter = jasmine.createSpyObj('fakeReporter', [ const reporter = jasmine.createSpyObj('fakeReporter', [
'specDone', 'specDone',
'suiteDone' 'suiteDone'
@@ -142,12 +156,24 @@ describe('Global error handling (integration)', function() {
describe('When the most recently running spec has reported specDone', function() { describe('When the most recently running spec has reported specDone', function() {
it('routes unhandled exceptions to an ancestor suite', async function() { it('routes unhandled exceptions to an ancestor suite', async function() {
const global = mockGlobal(); const global = {
const stackClearer = privateUnderTest.getStackClearer(global); ...browserEventMethods(),
const realClearStack = stackClearer.clearStack; setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn) {
clearTimeout(fn);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
const realClearStack = jasmineUnderTest.getClearStack(global);
const clearStackCallbacks = {}; const clearStackCallbacks = {};
let clearStackCallCount = 0; let clearStackCallCount = 0;
spyOn(stackClearer, 'clearStack').and.callFake(function(fn) { spyOn(jasmineUnderTest, 'getClearStack').and.returnValue(function(fn) {
clearStackCallCount++; clearStackCallCount++;
if (clearStackCallbacks[clearStackCallCount]) { if (clearStackCallbacks[clearStackCallCount]) {
@@ -156,12 +182,9 @@ describe('Global error handling (integration)', function() {
realClearStack(fn); realClearStack(fn);
}); });
spyOn(privateUnderTest, 'getStackClearer').and.returnValue(
stackClearer
);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
let suiteErrors = []; let suiteErrors = [];
env.addReporter({ env.addReporter({
@@ -197,9 +220,21 @@ describe('Global error handling (integration)', function() {
}); });
it('routes unhandled exceptions to the running suite', async function() { it('routes unhandled exceptions to the running suite', async function() {
const global = mockGlobal(); const global = {
...browserEventMethods(),
setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
const reporter = jasmine.createSpyObj('fakeReporter', [ const reporter = jasmine.createSpyObj('fakeReporter', [
'specDone', 'specDone',
'suiteDone' 'suiteDone'
@@ -238,12 +273,24 @@ describe('Global error handling (integration)', function() {
describe('When the most recently suite has reported suiteDone', function() { describe('When the most recently suite has reported suiteDone', function() {
it('routes unhandled exceptions to an ancestor suite', async function() { it('routes unhandled exceptions to an ancestor suite', async function() {
const global = mockGlobal(); const global = {
const stackClearer = privateUnderTest.getStackClearer(global); ...browserEventMethods(),
const realClearStack = stackClearer.clearStack; setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
const realClearStack = jasmineUnderTest.getClearStack(global);
const clearStackCallbacks = {}; const clearStackCallbacks = {};
let clearStackCallCount = 0; let clearStackCallCount = 0;
spyOn(stackClearer, 'clearStack').and.callFake(function(fn) { spyOn(jasmineUnderTest, 'getClearStack').and.returnValue(function(fn) {
clearStackCallCount++; clearStackCallCount++;
if (clearStackCallbacks[clearStackCallCount]) { if (clearStackCallbacks[clearStackCallCount]) {
@@ -252,12 +299,9 @@ describe('Global error handling (integration)', function() {
realClearStack(fn); realClearStack(fn);
}); });
spyOn(privateUnderTest, 'getStackClearer').and.returnValue(
stackClearer
);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
let suiteErrors = []; let suiteErrors = [];
env.addReporter({ env.addReporter({
@@ -297,9 +341,21 @@ describe('Global error handling (integration)', function() {
describe('When the env has started reporting jasmineDone', function() { describe('When the env has started reporting jasmineDone', function() {
it('logs the error to the console', async function() { it('logs the error to the console', async function() {
const global = mockGlobal(); const global = {
...browserEventMethods(),
setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
spyOn(console, 'error'); spyOn(console, 'error');
@@ -328,14 +384,26 @@ describe('Global error handling (integration)', function() {
}); });
it('routes all errors that occur during stack clearing somewhere', async function() { it('routes all errors that occur during stack clearing somewhere', async function() {
const global = mockGlobal(); const global = {
const stackClearer = privateUnderTest.getStackClearer(global); ...browserEventMethods(),
const realClearStack = stackClearer.clearStack; setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn) {
clearTimeout(fn);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
const realClearStack = jasmineUnderTest.getClearStack(global);
let clearStackCallCount = 0; let clearStackCallCount = 0;
let jasmineDone = false; let jasmineDone = false;
const expectedErrors = []; const expectedErrors = [];
const expectedErrorsAfterJasmineDone = []; const expectedErrorsAfterJasmineDone = [];
spyOn(stackClearer, 'clearStack').and.callFake(function(fn) { spyOn(jasmineUnderTest, 'getClearStack').and.returnValue(function(fn) {
clearStackCallCount++; clearStackCallCount++;
const msg = `Error in clearStack #${clearStackCallCount}`; const msg = `Error in clearStack #${clearStackCallCount}`;
@@ -348,11 +416,10 @@ describe('Global error handling (integration)', function() {
dispatchErrorEvent(global, 'error', { error: msg }); dispatchErrorEvent(global, 'error', { error: msg });
realClearStack(fn); realClearStack(fn);
}); });
spyOn(privateUnderTest, 'getStackClearer').and.returnValue(stackClearer);
spyOn(console, 'error'); spyOn(console, 'error');
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
const receivedErrors = []; const receivedErrors = [];
function logErrors(event) { function logErrors(event) {
@@ -392,9 +459,21 @@ describe('Global error handling (integration)', function() {
describe('Handling unhandled promise rejections', function() { describe('Handling unhandled promise rejections', function() {
it('routes unhandled promise rejections to the running spec', async function() { it('routes unhandled promise rejections to the running spec', async function() {
const global = mockGlobal(); const global = {
...browserEventMethods(),
setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
const reporter = jasmine.createSpyObj('fakeReporter', [ const reporter = jasmine.createSpyObj('fakeReporter', [
'specDone', 'specDone',
'suiteDone' 'suiteDone'
@@ -423,12 +502,24 @@ describe('Global error handling (integration)', function() {
describe('When the most recently running spec has reported specDone', function() { describe('When the most recently running spec has reported specDone', function() {
it('routes unhandled promise rejections to an ancestor suite', async function() { it('routes unhandled promise rejections to an ancestor suite', async function() {
const global = mockGlobal(); const global = {
const stackClearer = privateUnderTest.getStackClearer(global); ...browserEventMethods(),
const realClearStack = stackClearer.clearStack; setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn) {
clearTimeout(fn);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
const realClearStack = jasmineUnderTest.getClearStack(global);
const clearStackCallbacks = {}; const clearStackCallbacks = {};
let clearStackCallCount = 0; let clearStackCallCount = 0;
spyOn(stackClearer, 'clearStack').and.callFake(function(fn) { spyOn(jasmineUnderTest, 'getClearStack').and.returnValue(function(fn) {
clearStackCallCount++; clearStackCallCount++;
if (clearStackCallbacks[clearStackCallCount]) { if (clearStackCallbacks[clearStackCallCount]) {
@@ -437,12 +528,9 @@ describe('Global error handling (integration)', function() {
realClearStack(fn); realClearStack(fn);
}); });
spyOn(privateUnderTest, 'getStackClearer').and.returnValue(
stackClearer
);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
let suiteErrors = []; let suiteErrors = [];
env.addReporter({ env.addReporter({
@@ -478,9 +566,21 @@ describe('Global error handling (integration)', function() {
}); });
it('routes unhandled promise rejections to the running suite', async function() { it('routes unhandled promise rejections to the running suite', async function() {
const global = mockGlobal(); const global = {
...browserEventMethods(),
setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
const reporter = jasmine.createSpyObj('fakeReporter', [ const reporter = jasmine.createSpyObj('fakeReporter', [
'specDone', 'specDone',
'suiteDone' 'suiteDone'
@@ -521,12 +621,24 @@ describe('Global error handling (integration)', function() {
describe('When the most recently suite has reported suiteDone', function() { describe('When the most recently suite has reported suiteDone', function() {
it('routes unhandled promise rejections to an ancestor suite', async function() { it('routes unhandled promise rejections to an ancestor suite', async function() {
const global = mockGlobal(); const global = {
const stackClearer = privateUnderTest.getStackClearer(global); ...browserEventMethods(),
const realClearStack = stackClearer.clearStack; setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
const realClearStack = jasmineUnderTest.getClearStack(global);
const clearStackCallbacks = {}; const clearStackCallbacks = {};
let clearStackCallCount = 0; let clearStackCallCount = 0;
spyOn(stackClearer, 'clearStack').and.callFake(function(fn) { spyOn(jasmineUnderTest, 'getClearStack').and.returnValue(function(fn) {
clearStackCallCount++; clearStackCallCount++;
if (clearStackCallbacks[clearStackCallCount]) { if (clearStackCallbacks[clearStackCallCount]) {
@@ -535,12 +647,9 @@ describe('Global error handling (integration)', function() {
realClearStack(fn); realClearStack(fn);
}); });
spyOn(privateUnderTest, 'getStackClearer').and.returnValue(
stackClearer
);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
let suiteErrors = []; let suiteErrors = [];
env.addReporter({ env.addReporter({
@@ -580,9 +689,21 @@ describe('Global error handling (integration)', function() {
describe('When the env has started reporting jasmineDone', function() { describe('When the env has started reporting jasmineDone', function() {
it('logs the rejection to the console', async function() { it('logs the rejection to the console', async function() {
const global = mockGlobal(); const global = {
...browserEventMethods(),
setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
spyOn(console, 'error'); spyOn(console, 'error');
@@ -613,14 +734,26 @@ describe('Global error handling (integration)', function() {
}); });
it('routes all unhandled promise rejections that occur during stack clearing somewhere', async function() { it('routes all unhandled promise rejections that occur during stack clearing somewhere', async function() {
const global = mockGlobal(); const global = {
const stackClearer = privateUnderTest.getStackClearer(global); ...browserEventMethods(),
const realClearStack = stackClearer.clearStack; setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn) {
clearTimeout(fn);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
const realClearStack = jasmineUnderTest.getClearStack(global);
let clearStackCallCount = 0; let clearStackCallCount = 0;
let jasmineDone = false; let jasmineDone = false;
const expectedErrors = []; const expectedErrors = [];
const expectedErrorsAfterJasmineDone = []; const expectedErrorsAfterJasmineDone = [];
spyOn(stackClearer, 'clearStack').and.callFake(function(fn) { spyOn(jasmineUnderTest, 'getClearStack').and.returnValue(function(fn) {
clearStackCallCount++; clearStackCallCount++;
const reason = `Error in clearStack #${clearStackCallCount}`; const reason = `Error in clearStack #${clearStackCallCount}`;
const expectedMsg = `Unhandled promise rejection: ${reason} thrown`; const expectedMsg = `Unhandled promise rejection: ${reason} thrown`;
@@ -634,11 +767,10 @@ describe('Global error handling (integration)', function() {
dispatchErrorEvent(global, 'unhandledrejection', { reason }); dispatchErrorEvent(global, 'unhandledrejection', { reason });
realClearStack(fn); realClearStack(fn);
}); });
spyOn(privateUnderTest, 'getStackClearer').and.returnValue(stackClearer);
spyOn(console, 'error'); spyOn(console, 'error');
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
const receivedErrors = []; const receivedErrors = [];
function logErrors(event) { function logErrors(event) {
@@ -687,9 +819,21 @@ describe('Global error handling (integration)', function() {
let global, reporter; let global, reporter;
beforeEach(function() { beforeEach(function() {
global = mockGlobal(); global = {
...browserEventMethods(),
setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
env.configure({ detectLateRejectionHandling: true }); env.configure({ detectLateRejectionHandling: true });
reporter = jasmine.createSpyObj('fakeReporter', [ reporter = jasmine.createSpyObj('fakeReporter', [
@@ -822,8 +966,21 @@ describe('Global error handling (integration)', function() {
describe("When the unhandled rejection event doesn't have a promise", function() { describe("When the unhandled rejection event doesn't have a promise", function() {
it('reports the rejection', async function() { it('reports the rejection', async function() {
const global = mockGlobal(); const global = {
env = new privateUnderTest.Env({ global }); ...browserEventMethods(),
setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
env.cleanup_();
env = new jasmineUnderTest.Env();
env.configure({ detectLateRejectionHandling: true }); env.configure({ detectLateRejectionHandling: true });
const reporter = jasmine.createSpyObj('fakeReporter', [ const reporter = jasmine.createSpyObj('fakeReporter', [
'specDone', 'specDone',
@@ -855,9 +1012,21 @@ describe('Global error handling (integration)', function() {
}); });
it('works when the suite is run multiple times', async function() { it('works when the suite is run multiple times', async function() {
const global = mockGlobal(); const global = {
...browserEventMethods(),
setTimeout: function(fn, delay) {
return setTimeout(fn, delay);
},
clearTimeout: function(fn, delay) {
clearTimeout(fn, delay);
},
queueMicrotask: function(fn) {
queueMicrotask(fn);
}
};
spyOn(jasmineUnderTest, 'getGlobal').and.returnValue(global);
env.cleanup_(); env.cleanup_();
env = new privateUnderTest.Env({ global }); env = new jasmineUnderTest.Env();
env.configure({ autoCleanClosures: false }); env.configure({ autoCleanClosures: false });
const reporter = jasmine.createSpyObj('fakeReporter', ['specDone']); const reporter = jasmine.createSpyObj('fakeReporter', ['specDone']);
+2 -2
View File
@@ -2,7 +2,7 @@ describe('Matchers (Integration)', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
}); });
afterEach(function() { afterEach(function() {
@@ -143,7 +143,7 @@ describe('Matchers (Integration)', function() {
function verifyFailsWithCustomObjectFormattersAsync(config) { function verifyFailsWithCustomObjectFormattersAsync(config) {
it('uses custom object formatters', async function() { it('uses custom object formatters', async function() {
const env = new privateUnderTest.Env(); const env = new jasmineUnderTest.Env();
env.it('a spec', function() { env.it('a spec', function() {
env.addCustomObjectFormatter(config.formatter); env.addCustomObjectFormatter(config.formatter);
return config.expectations(env); return config.expectations(env);
+1 -1
View File
@@ -2,7 +2,7 @@ describe('Support for parallel execution', function() {
let env; let env;
beforeEach(function() { beforeEach(function() {
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
}); });
afterEach(function() { afterEach(function() {
+61 -6
View File
@@ -3,7 +3,7 @@ describe('spec running', function() {
beforeEach(function() { beforeEach(function() {
specHelpers.registerIntegrationMatchers(); specHelpers.registerIntegrationMatchers();
env = new privateUnderTest.Env(); env = new jasmineUnderTest.Env();
env.configure({ random: false }); env.configure({ random: false });
}); });
@@ -40,7 +40,7 @@ describe('spec running', function() {
env.it('should run nested suites', function() { env.it('should run nested suites', function() {
foo++; foo++;
}); });
env.it('should run nested suites 2', function() { env.it('should run nested suites', function() {
bar++; bar++;
}); });
}); });
@@ -601,7 +601,37 @@ describe('spec running', function() {
]); ]);
}); });
it('refuses to re-enter suites', async function() { it('re-enters suites that have no *Alls', async function() {
const actions = [];
let spec1;
let spec2;
let spec3;
env.describe('top', function() {
spec1 = env.it('spec1', function() {
actions.push('spec1');
});
spec2 = env.it('spec2', function() {
actions.push('spec2');
});
});
spec3 = env.it('spec3', function() {
actions.push('spec3');
});
spyOn(jasmineUnderTest.getEnv(), 'deprecated');
await env.execute([spec2.id, spec3.id, spec1.id]);
expect(actions).toEqual(['spec2', 'spec3', 'spec1']);
expect(jasmineUnderTest.getEnv().deprecated).toHaveBeenCalledWith(
'The specified spec/suite order splits up a suite, running unrelated specs in the middle of it. This will become an error in a future release.'
);
});
it('refuses to re-enter suites with a beforeAll', async function() {
const actions = []; const actions = [];
let spec1; let spec1;
let spec2; let spec2;
@@ -624,9 +654,34 @@ describe('spec running', function() {
}); });
const promise = env.execute([spec2.id, spec3.id, spec1.id]); const promise = env.execute([spec2.id, spec3.id, spec1.id]);
await expectAsync(promise).toBeRejectedWithError( await expectAsync(promise).toBeRejectedWithError(/beforeAll/);
'Invalid order: would split up a suite' expect(actions).toEqual([]);
); });
it('refuses to re-enter suites with a afterAll', async function() {
const actions = [];
let spec1;
let spec2;
let spec3;
env.describe('top', function() {
env.afterAll(function() {});
spec1 = env.it('spec1', function() {
actions.push('spec1');
});
spec2 = env.it('spec2', function() {
actions.push('spec2');
});
});
spec3 = env.it('spec3', function() {
actions.push('spec3');
});
const promise = env.execute([spec2.id, spec3.id, spec1.id]);
await expectAsync(promise).toBeRejectedWithError(/afterAll/);
expect(actions).toEqual([]); expect(actions).toEqual([]);
}); });
-79
View File
@@ -1,79 +0,0 @@
describe('The jasmine namespace', function() {
it('includes all expected properties', function() {
const actualKeys = new Set(Object.keys(jasmineUnderTest));
// toEqual doesn't generate diffs for set comparisons. Check this way
// instead so we get readable failure output.
expect(setDifference(expectedKeys(), actualKeys)).toEqual(new Set());
});
it('does not include any unexpected properties', function() {
const actualKeys = new Set(Object.keys(jasmineUnderTest));
// toEqual doesn't generate diffs for set comparisons. Check this way
// instead so we get readable failure output.
expect(setDifference(actualKeys, expectedKeys())).toEqual(new Set());
});
function expectedKeys() {
// Does not include properties added by requireInterface(), since that isn't
// called by defineJasmineUnderTest.js/nodeDefineJasmineUnderTest.js.
const result = new Set([
'MAX_PRETTY_PRINT_ARRAY_LENGTH',
'MAX_PRETTY_PRINT_CHARS',
'MAX_PRETTY_PRINT_DEPTH',
'debugLog',
'getEnv',
'isSpy',
'ParallelReportDispatcher',
'private',
'spyOnGlobalErrorsAsync',
'Timer',
'version',
// Asymmetric equality testers
'allOf',
'any',
'anything',
'arrayContaining',
'arrayWithExactContents',
'empty',
'falsy',
'is',
'mapContaining',
'notEmpty',
'objectContaining',
'setContaining',
'stringContaining',
'stringMatching',
'truthy',
// Currently undocumented but used in browser boot files, so it's
// effectively public
'getGlobal'
]);
if (typeof window !== 'undefined') {
// jasmine-html.js
result.add('HtmlReporter');
result.add('HtmlReporterV2');
result.add('HtmlReporterV2Urls');
result.add('HtmlSpecFilter');
result.add('QueryString');
}
return result;
}
// Can't use Set#difference yet because it isn't available in Node <22,
// Firefox <108, or Safari <17.
function setDifference(a, b) {
const result = new Set();
for (const v of a) {
if (!b.has(v)) {
result.add(v);
}
}
return result;
}
});
+20 -20
View File
@@ -1,6 +1,6 @@
describe('DiffBuilder', function() { describe('DiffBuilder', function() {
it('records the actual and expected objects', function() { it('records the actual and expected objects', function() {
const diffBuilder = new privateUnderTest.DiffBuilder(); const diffBuilder = new jasmineUnderTest.DiffBuilder();
diffBuilder.setRoots({ x: 'actual' }, { x: 'expected' }); diffBuilder.setRoots({ x: 'actual' }, { x: 'expected' });
diffBuilder.recordMismatch(); diffBuilder.recordMismatch();
@@ -10,7 +10,7 @@ describe('DiffBuilder', function() {
}); });
it('prints the path at which the difference was found', function() { it('prints the path at which the difference was found', function() {
const diffBuilder = new privateUnderTest.DiffBuilder(); const diffBuilder = new jasmineUnderTest.DiffBuilder();
diffBuilder.setRoots({ foo: { x: 'actual' } }, { foo: { x: 'expected' } }); diffBuilder.setRoots({ foo: { x: 'actual' } }, { foo: { x: 'expected' } });
diffBuilder.withPath('foo', function() { diffBuilder.withPath('foo', function() {
@@ -23,7 +23,7 @@ describe('DiffBuilder', function() {
}); });
it('prints multiple messages, separated by newlines', function() { it('prints multiple messages, separated by newlines', function() {
const diffBuilder = new privateUnderTest.DiffBuilder(); const diffBuilder = new jasmineUnderTest.DiffBuilder();
diffBuilder.setRoots({ foo: 1, bar: 3 }, { foo: 2, bar: 4 }); diffBuilder.setRoots({ foo: 1, bar: 3 }, { foo: 2, bar: 4 });
diffBuilder.withPath('foo', function() { diffBuilder.withPath('foo', function() {
@@ -40,7 +40,7 @@ describe('DiffBuilder', function() {
}); });
it('allows customization of the message', function() { it('allows customization of the message', function() {
const diffBuilder = new privateUnderTest.DiffBuilder(); const diffBuilder = new jasmineUnderTest.DiffBuilder();
diffBuilder.setRoots({ x: 'bar' }, { x: 'foo' }); diffBuilder.setRoots({ x: 'bar' }, { x: 'foo' });
function darthVaderFormatter(actual, expected, path) { function darthVaderFormatter(actual, expected, path) {
@@ -68,7 +68,7 @@ describe('DiffBuilder', function() {
const prettyPrinter = function(val) { const prettyPrinter = function(val) {
return '|' + val + '|'; return '|' + val + '|';
}, },
diffBuilder = new privateUnderTest.DiffBuilder({ diffBuilder = new jasmineUnderTest.DiffBuilder({
prettyPrinter: prettyPrinter prettyPrinter: prettyPrinter
}); });
prettyPrinter.customFormat_ = function() {}; prettyPrinter.customFormat_ = function() {};
@@ -86,7 +86,7 @@ describe('DiffBuilder', function() {
it('passes the injected pretty-printer to the diff formatter', function() { it('passes the injected pretty-printer to the diff formatter', function() {
const diffFormatter = jasmine.createSpy('diffFormatter'), const diffFormatter = jasmine.createSpy('diffFormatter'),
prettyPrinter = function() {}, prettyPrinter = function() {},
diffBuilder = new privateUnderTest.DiffBuilder({ diffBuilder = new jasmineUnderTest.DiffBuilder({
prettyPrinter: prettyPrinter prettyPrinter: prettyPrinter
}); });
prettyPrinter.customFormat_ = function() {}; prettyPrinter.customFormat_ = function() {};
@@ -112,8 +112,8 @@ describe('DiffBuilder', function() {
return '[number:' + x + ']'; return '[number:' + x + ']';
} }
}; };
const prettyPrinter = privateUnderTest.makePrettyPrinter([formatter]); const prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]);
const diffBuilder = new privateUnderTest.DiffBuilder({ const diffBuilder = new jasmineUnderTest.DiffBuilder({
prettyPrinter: prettyPrinter prettyPrinter: prettyPrinter
}); });
@@ -131,8 +131,8 @@ describe('DiffBuilder', function() {
return '[thing with a=' + x.a + ', b=' + JSON.stringify(x.b) + ']'; return '[thing with a=' + x.a + ', b=' + JSON.stringify(x.b) + ']';
} }
}; };
const prettyPrinter = privateUnderTest.makePrettyPrinter([formatter]); const prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]);
const diffBuilder = new privateUnderTest.DiffBuilder({ const diffBuilder = new jasmineUnderTest.DiffBuilder({
prettyPrinter: prettyPrinter prettyPrinter: prettyPrinter
}); });
const expectedMsg = const expectedMsg =
@@ -167,8 +167,8 @@ describe('DiffBuilder', function() {
return '[number:' + x + ']'; return '[number:' + x + ']';
} }
}; };
const prettyPrinter = privateUnderTest.makePrettyPrinter([formatter]); const prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]);
const diffBuilder = new privateUnderTest.DiffBuilder({ const diffBuilder = new jasmineUnderTest.DiffBuilder({
prettyPrinter: prettyPrinter prettyPrinter: prettyPrinter
}); });
@@ -186,8 +186,8 @@ describe('DiffBuilder', function() {
return '[number:' + x + ']'; return '[number:' + x + ']';
} }
}; };
const prettyPrinter = privateUnderTest.makePrettyPrinter([formatter]); const prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]);
const diffBuilder = new privateUnderTest.DiffBuilder({ const diffBuilder = new jasmineUnderTest.DiffBuilder({
prettyPrinter: prettyPrinter prettyPrinter: prettyPrinter
}); });
@@ -205,8 +205,8 @@ describe('DiffBuilder', function() {
return '[number:' + x + ']'; return '[number:' + x + ']';
} }
}; };
const prettyPrinter = privateUnderTest.makePrettyPrinter([formatter]); const prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]);
const diffBuilder = new privateUnderTest.DiffBuilder({ const diffBuilder = new jasmineUnderTest.DiffBuilder({
prettyPrinter: prettyPrinter prettyPrinter: prettyPrinter
}); });
@@ -219,8 +219,8 @@ describe('DiffBuilder', function() {
}); });
it('builds diffs involving asymmetric equality testers that implement valuesForDiff_ at the root', function() { it('builds diffs involving asymmetric equality testers that implement valuesForDiff_ at the root', function() {
const prettyPrinter = privateUnderTest.makePrettyPrinter([]), const prettyPrinter = jasmineUnderTest.makePrettyPrinter([]),
diffBuilder = new privateUnderTest.DiffBuilder({ diffBuilder = new jasmineUnderTest.DiffBuilder({
prettyPrinter: prettyPrinter prettyPrinter: prettyPrinter
}), }),
expectedMsg = expectedMsg =
@@ -243,8 +243,8 @@ describe('DiffBuilder', function() {
}); });
it('builds diffs involving asymmetric equality testers that implement valuesForDiff_ below the root', function() { it('builds diffs involving asymmetric equality testers that implement valuesForDiff_ below the root', function() {
const prettyPrinter = privateUnderTest.makePrettyPrinter([]), const prettyPrinter = jasmineUnderTest.makePrettyPrinter([]),
diffBuilder = new privateUnderTest.DiffBuilder({ diffBuilder = new jasmineUnderTest.DiffBuilder({
prettyPrinter: prettyPrinter prettyPrinter: prettyPrinter
}), }),
expectedMsg = expectedMsg =
+33 -33
View File
@@ -2,25 +2,25 @@ describe('MismatchTree', function() {
describe('#add', function() { describe('#add', function() {
describe('When the path is empty', function() { describe('When the path is empty', function() {
it('flags the root node as mismatched', function() { it('flags the root node as mismatched', function() {
const tree = new privateUnderTest.MismatchTree(); const tree = new jasmineUnderTest.MismatchTree();
tree.add(new privateUnderTest.ObjectPath([])); tree.add(new jasmineUnderTest.ObjectPath([]));
expect(tree.isMismatch).toBe(true); expect(tree.isMismatch).toBe(true);
}); });
}); });
describe('When the path is not empty', function() { describe('When the path is not empty', function() {
it('flags the node as mismatched', function() { it('flags the node as mismatched', function() {
const tree = new privateUnderTest.MismatchTree(); const tree = new jasmineUnderTest.MismatchTree();
tree.add(new privateUnderTest.ObjectPath(['a', 'b'])); tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']));
expect(tree.child('a').child('b').isMismatch).toBe(true); expect(tree.child('a').child('b').isMismatch).toBe(true);
}); });
it('does not flag ancestors as mismatched', function() { it('does not flag ancestors as mismatched', function() {
const tree = new privateUnderTest.MismatchTree(); const tree = new jasmineUnderTest.MismatchTree();
tree.add(new privateUnderTest.ObjectPath(['a', 'b'])); tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']));
expect(tree.isMismatch).toBe(false); expect(tree.isMismatch).toBe(false);
expect(tree.child('a').isMismatch).toBe(false); expect(tree.child('a').isMismatch).toBe(false);
@@ -28,9 +28,9 @@ describe('MismatchTree', function() {
}); });
it('stores the formatter on only the target node', function() { it('stores the formatter on only the target node', function() {
const tree = new privateUnderTest.MismatchTree(); const tree = new jasmineUnderTest.MismatchTree();
tree.add(new privateUnderTest.ObjectPath(['a', 'b']), formatter); tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']), formatter);
expect(tree.formatter).toBeFalsy(); expect(tree.formatter).toBeFalsy();
expect(tree.child('a').formatter).toBeFalsy(); expect(tree.child('a').formatter).toBeFalsy();
@@ -38,9 +38,9 @@ describe('MismatchTree', function() {
}); });
it('stores the path to the node', function() { it('stores the path to the node', function() {
const tree = new privateUnderTest.MismatchTree(); const tree = new jasmineUnderTest.MismatchTree();
tree.add(new privateUnderTest.ObjectPath(['a', 'b']), formatter); tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']), formatter);
expect(tree.child('a').child('b').path.components).toEqual(['a', 'b']); expect(tree.child('a').child('b').path.components).toEqual(['a', 'b']);
}); });
@@ -48,37 +48,37 @@ describe('MismatchTree', function() {
describe('#traverse', function() { describe('#traverse', function() {
it('calls the callback for all nodes that are or contain mismatches', function() { it('calls the callback for all nodes that are or contain mismatches', function() {
const tree = new privateUnderTest.MismatchTree(); const tree = new jasmineUnderTest.MismatchTree();
tree.add(new privateUnderTest.ObjectPath(['a', 'b']), formatter); tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']), formatter);
tree.add(new privateUnderTest.ObjectPath(['c'])); tree.add(new jasmineUnderTest.ObjectPath(['c']));
const visit = jasmine.createSpy('visit').and.returnValue(true); const visit = jasmine.createSpy('visit').and.returnValue(true);
tree.traverse(visit); tree.traverse(visit);
expect(visit).toHaveBeenCalledWith( expect(visit).toHaveBeenCalledWith(
new privateUnderTest.ObjectPath([]), new jasmineUnderTest.ObjectPath([]),
false, false,
undefined undefined
); );
expect(visit).toHaveBeenCalledWith( expect(visit).toHaveBeenCalledWith(
new privateUnderTest.ObjectPath(['a']), new jasmineUnderTest.ObjectPath(['a']),
false, false,
undefined undefined
); );
expect(visit).toHaveBeenCalledWith( expect(visit).toHaveBeenCalledWith(
new privateUnderTest.ObjectPath(['a', 'b']), new jasmineUnderTest.ObjectPath(['a', 'b']),
true, true,
formatter formatter
); );
expect(visit).toHaveBeenCalledWith( expect(visit).toHaveBeenCalledWith(
new privateUnderTest.ObjectPath(['c']), new jasmineUnderTest.ObjectPath(['c']),
true, true,
undefined undefined
); );
}); });
it('does not call the callback if there are no mismatches', function() { it('does not call the callback if there are no mismatches', function() {
const tree = new privateUnderTest.MismatchTree(); const tree = new jasmineUnderTest.MismatchTree();
const visit = jasmine.createSpy('visit'); const visit = jasmine.createSpy('visit');
tree.traverse(visit); tree.traverse(visit);
@@ -87,8 +87,8 @@ describe('MismatchTree', function() {
}); });
it('visits parents before children', function() { it('visits parents before children', function() {
const tree = new privateUnderTest.MismatchTree(); const tree = new jasmineUnderTest.MismatchTree();
tree.add(new privateUnderTest.ObjectPath(['a', 'b'])); tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']));
const visited = []; const visited = [];
tree.traverse(function(path) { tree.traverse(function(path) {
@@ -97,16 +97,16 @@ describe('MismatchTree', function() {
}); });
expect(visited).toEqual([ expect(visited).toEqual([
new privateUnderTest.ObjectPath([]), new jasmineUnderTest.ObjectPath([]),
new privateUnderTest.ObjectPath(['a']), new jasmineUnderTest.ObjectPath(['a']),
new privateUnderTest.ObjectPath(['a', 'b']) new jasmineUnderTest.ObjectPath(['a', 'b'])
]); ]);
}); });
it('visits children in the order they were recorded', function() { it('visits children in the order they were recorded', function() {
const tree = new privateUnderTest.MismatchTree(); const tree = new jasmineUnderTest.MismatchTree();
tree.add(new privateUnderTest.ObjectPath(['length'])); tree.add(new jasmineUnderTest.ObjectPath(['length']));
tree.add(new privateUnderTest.ObjectPath([1])); tree.add(new jasmineUnderTest.ObjectPath([1]));
const visited = []; const visited = [];
tree.traverse(function(path) { tree.traverse(function(path) {
@@ -115,15 +115,15 @@ describe('MismatchTree', function() {
}); });
expect(visited).toEqual([ expect(visited).toEqual([
new privateUnderTest.ObjectPath([]), new jasmineUnderTest.ObjectPath([]),
new privateUnderTest.ObjectPath(['length']), new jasmineUnderTest.ObjectPath(['length']),
new privateUnderTest.ObjectPath([1]) new jasmineUnderTest.ObjectPath([1])
]); ]);
}); });
it('does not visit children if the callback returns falsy', function() { it('does not visit children if the callback returns falsy', function() {
const tree = new privateUnderTest.MismatchTree(); const tree = new jasmineUnderTest.MismatchTree();
tree.add(new privateUnderTest.ObjectPath(['a', 'b'])); tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']));
const visited = []; const visited = [];
tree.traverse(function(path) { tree.traverse(function(path) {
@@ -132,8 +132,8 @@ describe('MismatchTree', function() {
}); });
expect(visited).toEqual([ expect(visited).toEqual([
new privateUnderTest.ObjectPath([]), new jasmineUnderTest.ObjectPath([]),
new privateUnderTest.ObjectPath(['a']) new jasmineUnderTest.ObjectPath(['a'])
]); ]);
}); });
}); });
+1 -1
View File
@@ -1,7 +1,7 @@
describe('NullDiffBuilder', function() { describe('NullDiffBuilder', function() {
it('responds to withPath() by calling the passed function', function() { it('responds to withPath() by calling the passed function', function() {
const spy = jasmine.createSpy('callback'); const spy = jasmine.createSpy('callback');
privateUnderTest.NullDiffBuilder().withPath('does not matter', spy); jasmineUnderTest.NullDiffBuilder().withPath('does not matter', spy);
expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalled();
}); });
}); });
+1 -1
View File
@@ -1,5 +1,5 @@
describe('ObjectPath', function() { describe('ObjectPath', function() {
const ObjectPath = privateUnderTest.ObjectPath; const ObjectPath = jasmineUnderTest.ObjectPath;
it('represents the path to a node in an object tree', function() { it('represents the path to a node in an object tree', function() {
expect(new ObjectPath(['foo', 'bar']).toString()).toEqual('$.foo.bar'); expect(new ObjectPath(['foo', 'bar']).toString()).toEqual('$.foo.bar');
+8 -8
View File
@@ -1,7 +1,7 @@
describe('toBePending', function() { describe('toBePending', function() {
it('passes if the actual promise is pending', function() { it('passes if the actual promise is pending', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBePending(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBePending(matchersUtil),
actual = new Promise(function() {}); actual = new Promise(function() {});
return matcher.compare(actual).then(function(result) { return matcher.compare(actual).then(function(result) {
@@ -10,8 +10,8 @@ describe('toBePending', function() {
}); });
it('fails if the actual promise is resolved', function() { it('fails if the actual promise is resolved', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBePending(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBePending(matchersUtil),
actual = Promise.resolve(); actual = Promise.resolve();
return matcher.compare(actual).then(function(result) { return matcher.compare(actual).then(function(result) {
@@ -20,8 +20,8 @@ describe('toBePending', function() {
}); });
it('fails if the actual promise is rejected', function() { it('fails if the actual promise is rejected', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBePending(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBePending(matchersUtil),
actual = Promise.reject(new Error('promise was rejected')); actual = Promise.reject(new Error('promise was rejected'));
return matcher.compare(actual).then(function(result) { return matcher.compare(actual).then(function(result) {
@@ -30,8 +30,8 @@ describe('toBePending', function() {
}); });
it('fails if actual is not a promise', function() { it('fails if actual is not a promise', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBePending(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBePending(matchersUtil),
actual = 'not a promise'; actual = 'not a promise';
function f() { function f() {
+6 -6
View File
@@ -1,7 +1,7 @@
describe('toBeRejected', function() { describe('toBeRejected', function() {
it('passes if the actual is rejected', function() { it('passes if the actual is rejected', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBeRejected(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejected(matchersUtil),
actual = Promise.reject('AsyncExpectationSpec rejection'); actual = Promise.reject('AsyncExpectationSpec rejection');
return matcher.compare(actual).then(function(result) { return matcher.compare(actual).then(function(result) {
@@ -10,8 +10,8 @@ describe('toBeRejected', function() {
}); });
it('fails if the actual is resolved', function() { it('fails if the actual is resolved', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBeRejected(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejected(matchersUtil),
actual = Promise.resolve(); actual = Promise.resolve();
return matcher.compare(actual).then(function(result) { return matcher.compare(actual).then(function(result) {
@@ -20,8 +20,8 @@ describe('toBeRejected', function() {
}); });
it('fails if actual is not a promise', function() { it('fails if actual is not a promise', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBeRejected(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejected(matchersUtil),
actual = 'not a promise'; actual = 'not a promise';
function f() { function f() {
@@ -1,9 +1,9 @@
describe('#toBeRejectedWithError', function() { describe('#toBeRejectedWithError', function() {
it('passes when Error type matches', function() { it('passes when Error type matches', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.reject(new TypeError('foo')); actual = Promise.reject(new TypeError('foo'));
@@ -20,10 +20,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('passes when Error type and message matches', function() { it('passes when Error type and message matches', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.reject(new TypeError('foo')); actual = Promise.reject(new TypeError('foo'));
@@ -40,10 +40,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('passes when Error matches and is exactly Error', function() { it('passes when Error matches and is exactly Error', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.reject(new Error()); actual = Promise.reject(new Error());
@@ -60,10 +60,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('passes when Error message matches a string', function() { it('passes when Error message matches a string', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.reject(new Error('foo')); actual = Promise.reject(new Error('foo'));
@@ -80,10 +80,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('passes when Error message matches a RegExp', function() { it('passes when Error message matches a RegExp', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.reject(new Error('foo')); actual = Promise.reject(new Error('foo'));
@@ -100,10 +100,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('passes when Error message is empty', function() { it('passes when Error message is empty', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.reject(new Error()); actual = Promise.reject(new Error());
@@ -120,10 +120,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('passes when no arguments', function() { it('passes when no arguments', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.reject(new Error()); actual = Promise.reject(new Error());
@@ -140,10 +140,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('fails when resolved', function() { it('fails when resolved', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.resolve(new Error('foo')); actual = Promise.resolve(new Error('foo'));
@@ -159,10 +159,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('fails when rejected with non Error type', function() { it('fails when rejected with non Error type', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.reject('foo'); actual = Promise.reject('foo');
@@ -179,10 +179,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('fails when Error type mismatches', function() { it('fails when Error type mismatches', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.reject(new Error('foo')); actual = Promise.reject(new Error('foo'));
@@ -199,10 +199,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('fails when Error message mismatches', function() { it('fails when Error message mismatches', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = Promise.reject(new Error('foo')); actual = Promise.reject(new Error('foo'));
@@ -219,10 +219,10 @@ describe('#toBeRejectedWithError', function() {
}); });
it('fails if actual is not a promise', function() { it('fails if actual is not a promise', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWithError( matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(
matchersUtil matchersUtil
), ),
actual = 'not a promise'; actual = 'not a promise';
@@ -1,7 +1,7 @@
describe('#toBeRejectedWith', function() { describe('#toBeRejectedWith', function() {
it('should return true if the promise is rejected with the expected value', function() { it('should return true if the promise is rejected with the expected value', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.reject({ error: 'PEBCAK' }); actual = Promise.reject({ error: 'PEBCAK' });
return matcher.compare(actual, { error: 'PEBCAK' }).then(function(result) { return matcher.compare(actual, { error: 'PEBCAK' }).then(function(result) {
@@ -10,8 +10,8 @@ describe('#toBeRejectedWith', function() {
}); });
it('should fail if the promise resolves', function() { it('should fail if the promise resolves', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.resolve(); actual = Promise.resolve();
return matcher.compare(actual, '').then(function(result) { return matcher.compare(actual, '').then(function(result) {
@@ -20,10 +20,10 @@ describe('#toBeRejectedWith', function() {
}); });
it('should fail if the promise is rejected with a different value', function() { it('should fail if the promise is rejected with a different value', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.reject('A Bad Apple'); actual = Promise.reject('A Bad Apple');
return matcher.compare(actual, 'Some Cool Thing').then(function(result) { return matcher.compare(actual, 'Some Cool Thing').then(function(result) {
@@ -38,10 +38,10 @@ describe('#toBeRejectedWith', function() {
}); });
it('should build its error correctly when negated', function() { it('should build its error correctly when negated', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.reject(true); actual = Promise.reject(true);
return matcher.compare(actual, true).then(function(result) { return matcher.compare(actual, true).then(function(result) {
@@ -60,10 +60,10 @@ describe('#toBeRejectedWith', function() {
return true; return true;
} }
], ],
matchersUtil = new privateUnderTest.MatchersUtil({ matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: customEqualityTesters customTesters: customEqualityTesters
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.reject('actual'); actual = Promise.reject('actual');
return matcher.compare(actual, 'expected').then(function(result) { return matcher.compare(actual, 'expected').then(function(result) {
@@ -72,10 +72,10 @@ describe('#toBeRejectedWith', function() {
}); });
it('fails if actual is not a promise', function() { it('fails if actual is not a promise', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = 'not a promise'; actual = 'not a promise';
function f() { function f() {
+7 -7
View File
@@ -1,7 +1,7 @@
describe('toBeResolved', function() { describe('toBeResolved', function() {
it('passes if the actual is resolved', function() { it('passes if the actual is resolved', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBeResolved(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolved(matchersUtil),
actual = Promise.resolve(); actual = Promise.resolve();
return matcher.compare(actual).then(function(result) { return matcher.compare(actual).then(function(result) {
@@ -10,10 +10,10 @@ describe('toBeResolved', function() {
}); });
it('fails if the actual is rejected', function() { it('fails if the actual is rejected', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter([]) pp: jasmineUnderTest.makePrettyPrinter([])
}), }),
matcher = privateUnderTest.asyncMatchers.toBeResolved(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolved(matchersUtil),
actual = Promise.reject(new Error('AsyncExpectationSpec rejection')); actual = Promise.reject(new Error('AsyncExpectationSpec rejection'));
return matcher.compare(actual).then(function(result) { return matcher.compare(actual).then(function(result) {
@@ -27,8 +27,8 @@ describe('toBeResolved', function() {
}); });
it('fails if actual is not a promise', function() { it('fails if actual is not a promise', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBeResolved(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolved(matchersUtil),
actual = 'not a promise'; actual = 'not a promise';
function f() { function f() {
+17 -17
View File
@@ -1,7 +1,7 @@
describe('#toBeResolvedTo', function() { describe('#toBeResolvedTo', function() {
it('passes if the promise is resolved to the expected value', function() { it('passes if the promise is resolved to the expected value', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = privateUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.resolve({ foo: 42 }); actual = Promise.resolve({ foo: 42 });
return matcher.compare(actual, { foo: 42 }).then(function(result) { return matcher.compare(actual, { foo: 42 }).then(function(result) {
@@ -10,10 +10,10 @@ describe('#toBeResolvedTo', function() {
}); });
it('fails if the promise is rejected', function() { it('fails if the promise is rejected', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.reject(new Error('AsyncExpectationSpec error')); actual = Promise.reject(new Error('AsyncExpectationSpec error'));
return matcher.compare(actual, '').then(function(result) { return matcher.compare(actual, '').then(function(result) {
@@ -29,10 +29,10 @@ describe('#toBeResolvedTo', function() {
}); });
it('fails if the promise is resolved to a different value', function() { it('fails if the promise is resolved to a different value', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.resolve({ foo: 17 }); actual = Promise.resolve({ foo: 17 });
return matcher.compare(actual, { foo: 42 }).then(function(result) { return matcher.compare(actual, { foo: 42 }).then(function(result) {
@@ -47,10 +47,10 @@ describe('#toBeResolvedTo', function() {
}); });
it('builds its message correctly when negated', function() { it('builds its message correctly when negated', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.resolve(true); actual = Promise.resolve(true);
return matcher.compare(actual, true).then(function(result) { return matcher.compare(actual, true).then(function(result) {
@@ -69,11 +69,11 @@ describe('#toBeResolvedTo', function() {
return true; return true;
} }
], ],
matchersUtil = new privateUnderTest.MatchersUtil({ matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: customEqualityTesters, customTesters: customEqualityTesters,
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.resolve('actual'); actual = Promise.resolve('actual');
return matcher.compare(actual, 'expected').then(function(result) { return matcher.compare(actual, 'expected').then(function(result) {
@@ -82,10 +82,10 @@ describe('#toBeResolvedTo', function() {
}); });
it('fails if actual is not a promise', function() { it('fails if actual is not a promise', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
matcher = privateUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = 'not a promise'; actual = 'not a promise';
function f() { function f() {
+130 -115
View File
@@ -1,79 +1,79 @@
describe('matchersUtil', function() { describe('matchersUtil', function() {
it('exposes the injected pretty-printer as .pp', function() { it('exposes the injected pretty-printer as .pp', function() {
const pp = function() {}, const pp = function() {},
matchersUtil = new privateUnderTest.MatchersUtil({ pp: pp }); matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: pp });
expect(matchersUtil.pp).toBe(pp); expect(matchersUtil.pp).toBe(pp);
}); });
describe('equals', function() { describe('equals', function() {
it('passes for literals that are triple-equal', function() { it('passes for literals that are triple-equal', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(null, null)).toBe(true); expect(matchersUtil.equals(null, null)).toBe(true);
expect(matchersUtil.equals(void 0, void 0)).toBe(true); expect(matchersUtil.equals(void 0, void 0)).toBe(true);
}); });
it('fails for things that are not equivalent', function() { it('fails for things that are not equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals({ a: 'foo' }, 1)).toBe(false); expect(matchersUtil.equals({ a: 'foo' }, 1)).toBe(false);
}); });
it('passes for Strings that are equivalent', function() { it('passes for Strings that are equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals('foo', 'foo')).toBe(true); expect(matchersUtil.equals('foo', 'foo')).toBe(true);
}); });
it('fails for Strings that are not equivalent', function() { it('fails for Strings that are not equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals('foo', 'bar')).toBe(false); expect(matchersUtil.equals('foo', 'bar')).toBe(false);
}); });
it('passes for Numbers that are equivalent', function() { it('passes for Numbers that are equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(123, 123)).toBe(true); expect(matchersUtil.equals(123, 123)).toBe(true);
}); });
it('fails for Numbers that are not equivalent', function() { it('fails for Numbers that are not equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(123, 456)).toBe(false); expect(matchersUtil.equals(123, 456)).toBe(false);
}); });
it('fails for a Number and a String that have equivalent values', function() { it('fails for a Number and a String that have equivalent values', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(123, '123')).toBe(false); expect(matchersUtil.equals(123, '123')).toBe(false);
}); });
it('passes for Dates that are equivalent', function() { it('passes for Dates that are equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect( expect(
matchersUtil.equals(new Date('Jan 1, 1970'), new Date('Jan 1, 1970')) matchersUtil.equals(new Date('Jan 1, 1970'), new Date('Jan 1, 1970'))
).toBe(true); ).toBe(true);
}); });
it('fails for Dates that are not equivalent', function() { it('fails for Dates that are not equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect( expect(
matchersUtil.equals(new Date('Jan 1, 1970'), new Date('Feb 3, 1991')) matchersUtil.equals(new Date('Jan 1, 1970'), new Date('Feb 3, 1991'))
).toBe(false); ).toBe(false);
}); });
it('passes for Booleans that are equivalent', function() { it('passes for Booleans that are equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(true, true)).toBe(true); expect(matchersUtil.equals(true, true)).toBe(true);
}); });
it('fails for Booleans that are not equivalent', function() { it('fails for Booleans that are not equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(true, false)).toBe(false); expect(matchersUtil.equals(true, false)).toBe(false);
}); });
it('passes for RegExps that are equivalent', function() { it('passes for RegExps that are equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(/foo/, /foo/)).toBe(true); expect(matchersUtil.equals(/foo/, /foo/)).toBe(true);
}); });
it('fails for RegExps that are not equivalent', function() { it('fails for RegExps that are not equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(/foo/, /bar/)).toBe(false); expect(matchersUtil.equals(/foo/, /bar/)).toBe(false);
expect( expect(
matchersUtil.equals(new RegExp('foo', 'i'), new RegExp('foo')) matchersUtil.equals(new RegExp('foo', 'i'), new RegExp('foo'))
@@ -81,32 +81,32 @@ describe('matchersUtil', function() {
}); });
it('passes for Arrays that are equivalent', function() { it('passes for Arrays that are equivalent', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals([1, 2], [1, 2])).toBe(true); expect(matchersUtil.equals([1, 2], [1, 2])).toBe(true);
}); });
it('passes for Arrays that are equivalent, with elements added by changing length', function() { it('passes for Arrays that are equivalent, with elements added by changing length', function() {
const foo = [], const foo = [],
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
foo.length = 1; foo.length = 1;
expect(matchersUtil.equals(foo, [undefined])).toBe(true); expect(matchersUtil.equals(foo, [undefined])).toBe(true);
}); });
it('fails for Arrays that have different lengths', function() { it('fails for Arrays that have different lengths', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals([1, 2], [1, 2, 3])).toBe(false); expect(matchersUtil.equals([1, 2], [1, 2, 3])).toBe(false);
}); });
it('fails for Arrays that have different elements', function() { it('fails for Arrays that have different elements', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals([1, 2, 3], [1, 5, 3])).toBe(false); expect(matchersUtil.equals([1, 2, 3], [1, 5, 3])).toBe(false);
}); });
it('fails for Arrays whose contents are equivalent, but have differing properties', function() { it('fails for Arrays whose contents are equivalent, but have differing properties', function() {
const one = [1, 2, 3], const one = [1, 2, 3],
two = [1, 2, 3], two = [1, 2, 3],
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
one.foo = 'bar'; one.foo = 'bar';
two.foo = 'baz'; two.foo = 'baz';
@@ -117,7 +117,7 @@ describe('matchersUtil', function() {
it('passes for Arrays with equivalent contents and properties', function() { it('passes for Arrays with equivalent contents and properties', function() {
const one = [1, 2, 3], const one = [1, 2, 3],
two = [1, 2, 3], two = [1, 2, 3],
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
one.foo = 'bar'; one.foo = 'bar';
two.foo = 'bar'; two.foo = 'bar';
@@ -126,7 +126,7 @@ describe('matchersUtil', function() {
}); });
it('handles symbol keys in Arrays', function() { it('handles symbol keys in Arrays', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
sym = Symbol('foo'), sym = Symbol('foo'),
arr1 = []; arr1 = [];
let arr2 = []; let arr2 = [];
@@ -148,21 +148,21 @@ describe('matchersUtil', function() {
}); });
it('passes for Errors that are the same type and have the same message', function() { it('passes for Errors that are the same type and have the same message', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(new Error('foo'), new Error('foo'))).toBe( expect(matchersUtil.equals(new Error('foo'), new Error('foo'))).toBe(
true true
); );
}); });
it('fails for Errors that are the same type and have different messages', function() { it('fails for Errors that are the same type and have different messages', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(new Error('foo'), new Error('bar'))).toBe( expect(matchersUtil.equals(new Error('foo'), new Error('bar'))).toBe(
false false
); );
}); });
it('fails for objects with different constructors', function() { it('fails for objects with different constructors', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
function One() {} function One() {}
function Two() {} function Two() {}
@@ -170,17 +170,17 @@ describe('matchersUtil', function() {
}); });
it('passes for Objects that are equivalent (simple case)', function() { it('passes for Objects that are equivalent (simple case)', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals({ a: 'foo' }, { a: 'foo' })).toBe(true); expect(matchersUtil.equals({ a: 'foo' }, { a: 'foo' })).toBe(true);
}); });
it('fails for Objects that are not equivalent (simple case)', function() { it('fails for Objects that are not equivalent (simple case)', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals({ a: 'foo' }, { a: 'bar' })).toBe(false); expect(matchersUtil.equals({ a: 'foo' }, { a: 'bar' })).toBe(false);
}); });
it('passes for Objects that are equivalent (deep case)', function() { it('passes for Objects that are equivalent (deep case)', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect( expect(
matchersUtil.equals( matchersUtil.equals(
{ a: 'foo', b: { c: 'bar' } }, { a: 'foo', b: { c: 'bar' } },
@@ -190,7 +190,7 @@ describe('matchersUtil', function() {
}); });
it('fails for Objects that are not equivalent (deep case)', function() { it('fails for Objects that are not equivalent (deep case)', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect( expect(
matchersUtil.equals( matchersUtil.equals(
{ a: 'foo', b: { c: 'baz' } }, { a: 'foo', b: { c: 'baz' } },
@@ -202,7 +202,7 @@ describe('matchersUtil', function() {
it('passes for Objects that are equivalent (with cycles)', function() { it('passes for Objects that are equivalent (with cycles)', function() {
const actual = { a: 'foo' }, const actual = { a: 'foo' },
expected = { a: 'foo' }, expected = { a: 'foo' },
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
actual.b = actual; actual.b = actual;
expected.b = actual; expected.b = actual;
@@ -213,7 +213,7 @@ describe('matchersUtil', function() {
it('fails for Objects that are not equivalent (with cycles)', function() { it('fails for Objects that are not equivalent (with cycles)', function() {
const actual = { a: 'foo' }, const actual = { a: 'foo' },
expected = { a: 'bar' }, expected = { a: 'bar' },
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
actual.b = actual; actual.b = actual;
expected.b = actual; expected.b = actual;
@@ -224,7 +224,7 @@ describe('matchersUtil', function() {
it('fails for Objects that have the same number of keys, but different keys/values', function() { it('fails for Objects that have the same number of keys, but different keys/values', function() {
const expected = { a: undefined }, const expected = { a: undefined },
actual = { b: 1 }, actual = { b: 1 },
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(actual, expected)).toBe(false); expect(matchersUtil.equals(actual, expected)).toBe(false);
}); });
@@ -232,7 +232,7 @@ describe('matchersUtil', function() {
it('fails when comparing an empty object to an empty array (issue #114)', function() { it('fails when comparing an empty object to an empty array (issue #114)', function() {
const emptyObject = {}, const emptyObject = {},
emptyArray = [], emptyArray = [],
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(emptyObject, emptyArray)).toBe(false); expect(matchersUtil.equals(emptyObject, emptyArray)).toBe(false);
expect(matchersUtil.equals(emptyArray, emptyObject)).toBe(false); expect(matchersUtil.equals(emptyArray, emptyObject)).toBe(false);
@@ -241,7 +241,7 @@ describe('matchersUtil', function() {
it('passes for equivalent frozen objects (GitHub issue #266)', function() { it('passes for equivalent frozen objects (GitHub issue #266)', function() {
const a = { foo: 1 }, const a = { foo: 1 },
b = { foo: 1 }, b = { foo: 1 },
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
Object.freeze(a); Object.freeze(a);
Object.freeze(b); Object.freeze(b);
@@ -252,7 +252,7 @@ describe('matchersUtil', function() {
it('passes for equivalent Promises (GitHub issue #1314)', function() { it('passes for equivalent Promises (GitHub issue #1314)', function() {
const p1 = new Promise(function() {}), const p1 = new Promise(function() {}),
p2 = new Promise(function() {}), p2 = new Promise(function() {}),
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(p1, p1)).toBe(true); expect(matchersUtil.equals(p1, p1)).toBe(true);
expect(matchersUtil.equals(p1, p2)).toBe(false); expect(matchersUtil.equals(p1, p2)).toBe(false);
@@ -267,7 +267,7 @@ describe('matchersUtil', function() {
it('passes for equivalent DOM nodes', function() { it('passes for equivalent DOM nodes', function() {
const a = document.createElement('div'); const a = document.createElement('div');
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
a.setAttribute('test-attr', 'attr-value'); a.setAttribute('test-attr', 'attr-value');
a.appendChild(document.createTextNode('test')); a.appendChild(document.createTextNode('test'));
@@ -280,7 +280,7 @@ describe('matchersUtil', function() {
}); });
it('passes for equivalent objects from different frames', function() { it('passes for equivalent objects from different frames', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const iframe = document.createElement('iframe'); const iframe = document.createElement('iframe');
document.body.appendChild(iframe); document.body.appendChild(iframe);
iframe.contentWindow.eval('window.testObject = {}'); iframe.contentWindow.eval('window.testObject = {}');
@@ -291,7 +291,7 @@ describe('matchersUtil', function() {
}); });
it('fails for DOM nodes with different attributes or child nodes', function() { it('fails for DOM nodes with different attributes or child nodes', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const a = document.createElement('div'); const a = document.createElement('div');
a.setAttribute('test-attr', 'attr-value'); a.setAttribute('test-attr', 'attr-value');
a.appendChild(document.createTextNode('test')); a.appendChild(document.createTextNode('test'));
@@ -321,7 +321,7 @@ describe('matchersUtil', function() {
}); });
it('passes for equivalent objects from different vm contexts', function() { it('passes for equivalent objects from different vm contexts', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const vm = require('vm'); const vm = require('vm');
const sandbox = { const sandbox = {
obj: null obj: null
@@ -332,7 +332,7 @@ describe('matchersUtil', function() {
}); });
it('passes for equivalent arrays from different vm contexts', function() { it('passes for equivalent arrays from different vm contexts', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const vm = require('vm'); const vm = require('vm');
const sandbox = { const sandbox = {
arr: null arr: null
@@ -345,8 +345,8 @@ describe('matchersUtil', function() {
it('passes when Any is used', function() { it('passes when Any is used', function() {
const number = 3, const number = 3,
anyNumber = new privateUnderTest.Any(Number), anyNumber = new jasmineUnderTest.Any(Number),
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(number, anyNumber)).toBe(true); expect(matchersUtil.equals(number, anyNumber)).toBe(true);
expect(matchersUtil.equals(anyNumber, number)).toBe(true); expect(matchersUtil.equals(anyNumber, number)).toBe(true);
@@ -354,8 +354,8 @@ describe('matchersUtil', function() {
it('fails when Any is compared to something unexpected', function() { it('fails when Any is compared to something unexpected', function() {
const number = 3, const number = 3,
anyString = new privateUnderTest.Any(String), anyString = new jasmineUnderTest.Any(String),
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(number, anyString)).toBe(false); expect(matchersUtil.equals(number, anyString)).toBe(false);
expect(matchersUtil.equals(anyString, number)).toBe(false); expect(matchersUtil.equals(anyString, number)).toBe(false);
@@ -366,19 +366,19 @@ describe('matchersUtil', function() {
foo: 3, foo: 3,
bar: 7 bar: 7
}, },
containing = new privateUnderTest.ObjectContaining({ foo: 3 }), containing = new jasmineUnderTest.ObjectContaining({ foo: 3 }),
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(obj, containing)).toBe(true); expect(matchersUtil.equals(obj, containing)).toBe(true);
expect(matchersUtil.equals(containing, obj)).toBe(true); expect(matchersUtil.equals(containing, obj)).toBe(true);
}); });
it('passes when MapContaining is used', function() { it('passes when MapContaining is used', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const obj = new Map(); const obj = new Map();
obj.set(1, 2); obj.set(1, 2);
obj.set('foo', 'bar'); obj.set('foo', 'bar');
const containing = new privateUnderTest.MapContaining(new Map()); const containing = new jasmineUnderTest.MapContaining(new Map());
containing.sample.set('foo', 'bar'); containing.sample.set('foo', 'bar');
expect(matchersUtil.equals(obj, containing)).toBe(true); expect(matchersUtil.equals(obj, containing)).toBe(true);
@@ -386,11 +386,11 @@ describe('matchersUtil', function() {
}); });
it('passes when SetContaining is used', function() { it('passes when SetContaining is used', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const obj = new Set(); const obj = new Set();
obj.add(1); obj.add(1);
obj.add('foo'); obj.add('foo');
const containing = new privateUnderTest.SetContaining(new Set()); const containing = new jasmineUnderTest.SetContaining(new Set());
containing.sample.add(1); containing.sample.add(1);
expect(matchersUtil.equals(obj, containing)).toBe(true); expect(matchersUtil.equals(obj, containing)).toBe(true);
@@ -403,7 +403,7 @@ describe('matchersUtil', function() {
return true; return true;
} }
}, },
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(false, tester)).toBe(true); expect(matchersUtil.equals(false, tester)).toBe(true);
expect(matchersUtil.equals(tester, false)).toBe(true); expect(matchersUtil.equals(tester, false)).toBe(true);
@@ -415,7 +415,7 @@ describe('matchersUtil', function() {
return false; return false;
} }
}, },
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(true, tester)).toBe(false); expect(matchersUtil.equals(true, tester)).toBe(false);
expect(matchersUtil.equals(tester, true)).toBe(false); expect(matchersUtil.equals(tester, true)).toBe(false);
@@ -423,10 +423,10 @@ describe('matchersUtil', function() {
it('passes when ArrayContaining is used', function() { it('passes when ArrayContaining is used', function() {
const arr = ['foo', 'bar'], const arr = ['foo', 'bar'],
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect( expect(
matchersUtil.equals(arr, new privateUnderTest.ArrayContaining(['bar'])) matchersUtil.equals(arr, new jasmineUnderTest.ArrayContaining(['bar']))
).toBe(true); ).toBe(true);
}); });
@@ -434,7 +434,7 @@ describe('matchersUtil', function() {
const tester = function() { const tester = function() {
return true; return true;
}, },
matchersUtil = new privateUnderTest.MatchersUtil({ matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [tester], customTesters: [tester],
pp: function() {} pp: function() {}
}); });
@@ -443,7 +443,7 @@ describe('matchersUtil', function() {
}); });
it('passes for two empty Objects', function() { it('passes for two empty Objects', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals({}, {})).toBe(true); expect(matchersUtil.equals({}, {})).toBe(true);
}); });
@@ -453,7 +453,7 @@ describe('matchersUtil', function() {
}; };
it('passes for two empty Objects', function() { it('passes for two empty Objects', function() {
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [tester], customTesters: [tester],
pp: function() {} pp: function() {}
}); });
@@ -465,7 +465,7 @@ describe('matchersUtil', function() {
const tester = function() { const tester = function() {
return false; return false;
}, },
matchersUtil = new privateUnderTest.MatchersUtil({ matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [tester], customTesters: [tester],
pp: function() {} pp: function() {}
}); });
@@ -482,7 +482,7 @@ describe('matchersUtil', function() {
symmetricTester = function() { symmetricTester = function() {
return false; return false;
}, },
matchersUtil = new privateUnderTest.MatchersUtil({ matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [symmetricTester()], customTesters: [symmetricTester()],
pp: function() {} pp: function() {}
}); });
@@ -492,9 +492,9 @@ describe('matchersUtil', function() {
}); });
it('passes when an Any is compared to an Any that checks for the same type', function() { it('passes when an Any is compared to an Any that checks for the same type', function() {
const any1 = new privateUnderTest.Any(Function), const any1 = new jasmineUnderTest.Any(Function),
any2 = new privateUnderTest.Any(Function), any2 = new jasmineUnderTest.Any(Function),
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(any1, any2)).toBe(true); expect(matchersUtil.equals(any1, any2)).toBe(true);
}); });
@@ -502,7 +502,7 @@ describe('matchersUtil', function() {
it('passes for null prototype objects with same properties', function() { it('passes for null prototype objects with same properties', function() {
const objA = Object.create(null), const objA = Object.create(null),
objB = Object.create(null), objB = Object.create(null),
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
objA.name = 'test'; objA.name = 'test';
objB.name = 'test'; objB.name = 'test';
@@ -513,7 +513,7 @@ describe('matchersUtil', function() {
it('fails for null prototype objects with different properties', function() { it('fails for null prototype objects with different properties', function() {
const objA = Object.create(null), const objA = Object.create(null),
objB = Object.create(null), objB = Object.create(null),
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
objA.name = 'test'; objA.name = 'test';
objB.test = 'name'; objB.test = 'name';
@@ -522,12 +522,12 @@ describe('matchersUtil', function() {
}); });
it('passes when comparing two empty sets', function() { it('passes when comparing two empty sets', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(new Set(), new Set())).toBe(true); expect(matchersUtil.equals(new Set(), new Set())).toBe(true);
}); });
it('passes when comparing identical sets', function() { it('passes when comparing identical sets', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const setA = new Set(); const setA = new Set();
setA.add(6); setA.add(6);
setA.add(5); setA.add(5);
@@ -539,7 +539,7 @@ describe('matchersUtil', function() {
}); });
it('passes when comparing identical sets with different insertion order and simple elements', function() { it('passes when comparing identical sets with different insertion order and simple elements', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const setA = new Set(); const setA = new Set();
setA.add(3); setA.add(3);
setA.add(6); setA.add(6);
@@ -551,7 +551,7 @@ describe('matchersUtil', function() {
}); });
it('passes when comparing identical sets with different insertion order and complex elements 1', function() { it('passes when comparing identical sets with different insertion order and complex elements 1', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const setA1 = new Set(); const setA1 = new Set();
setA1.add(['a', 3]); setA1.add(['a', 3]);
setA1.add([6, 1]); setA1.add([6, 1]);
@@ -576,7 +576,7 @@ describe('matchersUtil', function() {
}); });
it('passes when comparing identical sets with different insertion order and complex elements 2', function() { it('passes when comparing identical sets with different insertion order and complex elements 2', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const setA = new Set(); const setA = new Set();
setA.add([[1, 2], [3, 4]]); setA.add([[1, 2], [3, 4]]);
setA.add([[5, 6], [7, 8]]); setA.add([[5, 6], [7, 8]]);
@@ -588,7 +588,7 @@ describe('matchersUtil', function() {
}); });
it('fails for sets with different elements', function() { it('fails for sets with different elements', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const setA = new Set(); const setA = new Set();
setA.add(6); setA.add(6);
setA.add(3); setA.add(3);
@@ -602,7 +602,7 @@ describe('matchersUtil', function() {
}); });
it('fails for sets of different size', function() { it('fails for sets of different size', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const setA = new Set(); const setA = new Set();
setA.add(6); setA.add(6);
setA.add(3); setA.add(3);
@@ -615,12 +615,12 @@ describe('matchersUtil', function() {
}); });
it('passes when comparing two empty maps', function() { it('passes when comparing two empty maps', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(new Map(), new Map())).toBe(true); expect(matchersUtil.equals(new Map(), new Map())).toBe(true);
}); });
it('passes when comparing identical maps', function() { it('passes when comparing identical maps', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const mapA = new Map(); const mapA = new Map();
mapA.set(6, 5); mapA.set(6, 5);
const mapB = new Map(); const mapB = new Map();
@@ -629,7 +629,7 @@ describe('matchersUtil', function() {
}); });
it('passes when comparing identical maps with different insertion order', function() { it('passes when comparing identical maps with different insertion order', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const mapA = new Map(); const mapA = new Map();
mapA.set('a', 3); mapA.set('a', 3);
mapA.set(6, 1); mapA.set(6, 1);
@@ -640,7 +640,7 @@ describe('matchersUtil', function() {
}); });
it('fails for maps with different elements', function() { it('fails for maps with different elements', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const mapA = new Map(); const mapA = new Map();
mapA.set(6, 3); mapA.set(6, 3);
mapA.set(5, 1); mapA.set(5, 1);
@@ -652,7 +652,7 @@ describe('matchersUtil', function() {
}); });
it('fails for maps of different size', function() { it('fails for maps of different size', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const mapA = new Map(); const mapA = new Map();
mapA.set(6, 3); mapA.set(6, 3);
const mapB = new Map(); const mapB = new Map();
@@ -662,7 +662,7 @@ describe('matchersUtil', function() {
}); });
it('passes when comparing two identical URLs', function() { it('passes when comparing two identical URLs', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect( expect(
matchersUtil.equals( matchersUtil.equals(
@@ -673,7 +673,7 @@ describe('matchersUtil', function() {
}); });
it('fails when comparing two different URLs', function() { it('fails when comparing two different URLs', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(), const matchersUtil = new jasmineUnderTest.MatchersUtil(),
url1 = new URL('http://localhost/1'); url1 = new URL('http://localhost/1');
expect(matchersUtil.equals(url1, new URL('http://localhost/2'))).toBe( expect(matchersUtil.equals(url1, new URL('http://localhost/2'))).toBe(
@@ -699,7 +699,7 @@ describe('matchersUtil', function() {
it('passes for ArrayBuffers with same length and content', function() { it('passes for ArrayBuffers with same length and content', function() {
const buffer1 = new ArrayBuffer(4); const buffer1 = new ArrayBuffer(4);
const buffer2 = new ArrayBuffer(4); const buffer2 = new ArrayBuffer(4);
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(buffer1, buffer2)).toBe(true); expect(matchersUtil.equals(buffer1, buffer2)).toBe(true);
}); });
@@ -708,13 +708,13 @@ describe('matchersUtil', function() {
const buffer2 = new ArrayBuffer(4); const buffer2 = new ArrayBuffer(4);
const array1 = new Uint8Array(buffer1); const array1 = new Uint8Array(buffer1);
array1[0] = 1; array1[0] = 1;
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals(buffer1, buffer2)).toBe(false); expect(matchersUtil.equals(buffer1, buffer2)).toBe(false);
}); });
describe('Typed arrays', function() { describe('Typed arrays', function() {
it('fails for typed arrays of same length and contents but different types', function() { it('fails for typed arrays of same length and contents but different types', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const a1 = new Int8Array(1); const a1 = new Int8Array(1);
const a2 = new Uint8Array(1); const a2 = new Uint8Array(1);
a1[0] = a2[0] = 0; a1[0] = a2[0] = 0;
@@ -737,23 +737,23 @@ describe('matchersUtil', function() {
it( it(
'passes for ' + typeName + 's with same length and content', 'passes for ' + typeName + 's with same length and content',
function() { function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const a1 = new TypedArrayCtor(2); const a1 = new TypedArrayCtor(2);
const a2 = new TypedArrayCtor(2); const a2 = new TypedArrayCtor(2);
a1[0] = a2[0] = 0; a1[0] = a2[0] = 0;
a1[1] = a2[1] = 1; a1[1] = a2[1] = 1;
const diffBuilder = new privateUnderTest.DiffBuilder(); const diffBuilder = new jasmineUnderTest.DiffBuilder();
expect(matchersUtil.equals(a1, a2, diffBuilder)).toBe(true); expect(matchersUtil.equals(a1, a2, diffBuilder)).toBe(true);
jasmine.debugLog('Diff: ' + diffBuilder.getMessage()); jasmine.debugLog('Diff: ' + diffBuilder.getMessage());
} }
); );
it('fails for ' + typeName + 's with different length', function() { it('fails for ' + typeName + 's with different length', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const a1 = new TypedArrayCtor(2); const a1 = new TypedArrayCtor(2);
const a2 = new TypedArrayCtor(1); const a2 = new TypedArrayCtor(1);
a1[0] = a1[1] = a2[0] = 0; a1[0] = a1[1] = a2[0] = 0;
const diffBuilder = new privateUnderTest.DiffBuilder(); const diffBuilder = new jasmineUnderTest.DiffBuilder();
expect(matchersUtil.equals(a1, a2, diffBuilder)).toBe(false); expect(matchersUtil.equals(a1, a2, diffBuilder)).toBe(false);
jasmine.debugLog('Diff: ' + diffBuilder.getMessage()); jasmine.debugLog('Diff: ' + diffBuilder.getMessage());
}); });
@@ -761,19 +761,34 @@ describe('matchersUtil', function() {
it( it(
'fails for ' + typeName + 's with same length but different content', 'fails for ' + typeName + 's with same length but different content',
function() { function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const a1 = new TypedArrayCtor(1); const a1 = new TypedArrayCtor(1);
const a2 = new TypedArrayCtor(1); const a2 = new TypedArrayCtor(1);
a1[0] = 0; a1[0] = 0;
a2[0] = 1; a2[0] = 1;
const diffBuilder = new privateUnderTest.DiffBuilder(); const diffBuilder = new jasmineUnderTest.DiffBuilder();
expect(matchersUtil.equals(a1, a2, diffBuilder)).toBe(false); expect(matchersUtil.equals(a1, a2, diffBuilder)).toBe(false);
jasmine.debugLog('Diff: ' + diffBuilder.getMessage()); jasmine.debugLog(
'a1 keys: ' +
jasmine.basicPrettyPrinter_(
jasmineUnderTest.MatchersUtil.keys(a1)
)
);
jasmine.debugLog(
'a2 keys: ' +
jasmine.basicPrettyPrinter_(
jasmineUnderTest.MatchersUtil.keys(a2)
)
);
jasmine.debugLog('a1 length:' + a1.length);
jasmine.debugLog('a2 length:' + a2.length);
jasmine.debugLog('a1[0]: ' + a1[0]);
jasmine.debugLog('a2[0]: ' + a2[0]);
} }
); );
it('checks nonstandard properties of ' + typeName, function() { it('checks nonstandard properties of ' + typeName, function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const a1 = new TypedArrayCtor(1); const a1 = new TypedArrayCtor(1);
const a2 = new TypedArrayCtor(1); const a2 = new TypedArrayCtor(1);
a1[0] = a2[0] = 0; a1[0] = a2[0] = 0;
@@ -784,7 +799,7 @@ describe('matchersUtil', function() {
it('works with custom equality testers with ' + typeName, function() { it('works with custom equality testers with ' + typeName, function() {
const a1 = new TypedArrayCtor(1); const a1 = new TypedArrayCtor(1);
const a2 = new TypedArrayCtor(1); const a2 = new TypedArrayCtor(1);
const matchersUtil = new privateUnderTest.MatchersUtil({ const matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [ customTesters: [
function() { function() {
return true; return true;
@@ -812,7 +827,7 @@ describe('matchersUtil', function() {
'passes for ' + typeName + 's with same length and content', 'passes for ' + typeName + 's with same length and content',
function() { function() {
const TypedArrayCtor = requireType(); const TypedArrayCtor = requireType();
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const a1 = new TypedArrayCtor(2); const a1 = new TypedArrayCtor(2);
const a2 = new TypedArrayCtor(2); const a2 = new TypedArrayCtor(2);
a1[0] = a2[0] = BigInt(0); a1[0] = a2[0] = BigInt(0);
@@ -823,7 +838,7 @@ describe('matchersUtil', function() {
it('fails for ' + typeName + 's with different length', function() { it('fails for ' + typeName + 's with different length', function() {
const TypedArrayCtor = requireType(); const TypedArrayCtor = requireType();
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const a1 = new TypedArrayCtor(2); const a1 = new TypedArrayCtor(2);
const a2 = new TypedArrayCtor(1); const a2 = new TypedArrayCtor(1);
a1[0] = a1[1] = a2[0] = BigInt(0); a1[0] = a1[1] = a2[0] = BigInt(0);
@@ -834,7 +849,7 @@ describe('matchersUtil', function() {
'fails for ' + typeName + 's with same length but different content', 'fails for ' + typeName + 's with same length but different content',
function() { function() {
const TypedArrayCtor = requireType(); const TypedArrayCtor = requireType();
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const a1 = new TypedArrayCtor(2); const a1 = new TypedArrayCtor(2);
const a2 = new TypedArrayCtor(2); const a2 = new TypedArrayCtor(2);
a1[0] = a1[1] = a2[0] = BigInt(0); a1[0] = a1[1] = a2[0] = BigInt(0);
@@ -922,7 +937,7 @@ describe('matchersUtil', function() {
'withPath', 'withPath',
'setRoots' 'setRoots'
]), ]),
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
diffBuilder.withPath.and.callFake(function(p, block) { diffBuilder.withPath.and.callFake(function(p, block) {
block(); block();
@@ -950,7 +965,7 @@ describe('matchersUtil', function() {
'withPath', 'withPath',
'setRoots' 'setRoots'
]), ]),
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
diffBuilder.withPath.and.callFake(function(p, block) { diffBuilder.withPath.and.callFake(function(p, block) {
block(); block();
@@ -967,8 +982,8 @@ describe('matchersUtil', function() {
}); });
it('uses a diffBuilder if one is provided as the third argument', function() { it('uses a diffBuilder if one is provided as the third argument', function() {
const diffBuilder = new privateUnderTest.DiffBuilder(), const diffBuilder = new jasmineUnderTest.DiffBuilder(),
matchersUtil = new privateUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
spyOn(diffBuilder, 'recordMismatch'); spyOn(diffBuilder, 'recordMismatch');
spyOn(diffBuilder, 'withPath').and.callThrough(); spyOn(diffBuilder, 'withPath').and.callThrough();
@@ -988,27 +1003,27 @@ describe('matchersUtil', function() {
describe('contains', function() { describe('contains', function() {
it('passes when expected is a substring of actual', function() { it('passes when expected is a substring of actual', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.contains('ABC', 'BC')).toBe(true); expect(matchersUtil.contains('ABC', 'BC')).toBe(true);
}); });
it('fails when expected is a not substring of actual', function() { it('fails when expected is a not substring of actual', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.contains('ABC', 'X')).toBe(false); expect(matchersUtil.contains('ABC', 'X')).toBe(false);
}); });
it('passes when expected is an element in an actual array', function() { it('passes when expected is an element in an actual array', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.contains(['foo', 'bar'], 'foo')).toBe(true); expect(matchersUtil.contains(['foo', 'bar'], 'foo')).toBe(true);
}); });
it('fails when expected is not an element in an actual array', function() { it('fails when expected is not an element in an actual array', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.contains(['foo', 'bar'], 'baz')).toBe(false); expect(matchersUtil.contains(['foo', 'bar'], 'baz')).toBe(false);
}); });
it('passes with mixed-element arrays', function() { it('passes with mixed-element arrays', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.contains(['foo', { some: 'bar' }], 'foo')).toBe(true); expect(matchersUtil.contains(['foo', { some: 'bar' }], 'foo')).toBe(true);
expect( expect(
matchersUtil.contains(['foo', { some: 'bar' }], { some: 'bar' }) matchersUtil.contains(['foo', { some: 'bar' }], { some: 'bar' })
@@ -1019,7 +1034,7 @@ describe('matchersUtil', function() {
const customTester = function() { const customTester = function() {
return true; return true;
}, },
matchersUtil = new privateUnderTest.MatchersUtil({ matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: [customTester], customTesters: [customTester],
pp: function() {} pp: function() {}
}); });
@@ -1028,18 +1043,18 @@ describe('matchersUtil', function() {
}); });
it('fails when actual is undefined', function() { it('fails when actual is undefined', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.contains(undefined, 'A')).toBe(false); expect(matchersUtil.contains(undefined, 'A')).toBe(false);
}); });
it('fails when actual is null', function() { it('fails when actual is null', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.contains(null, 'A')).toBe(false); expect(matchersUtil.contains(null, 'A')).toBe(false);
}); });
it('works with array-like objects that implement iterable', function() { it('works with array-like objects that implement iterable', function() {
let capturedArgs = null; let capturedArgs = null;
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
function testFunction() { function testFunction() {
capturedArgs = arguments; capturedArgs = arguments;
@@ -1056,14 +1071,14 @@ describe('matchersUtil', function() {
1: 'b', 1: 'b',
length: 2 length: 2
}; };
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.contains(arrayLike, 'b')).toBe(true); expect(matchersUtil.contains(arrayLike, 'b')).toBe(true);
expect(matchersUtil.contains(arrayLike, 'c')).toBe(false); expect(matchersUtil.contains(arrayLike, 'c')).toBe(false);
}); });
it('passes for set members', function() { it('passes for set members', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const setItem = { foo: 'bar' }; const setItem = { foo: 'bar' };
const set = new Set(); const set = new Set();
set.add(setItem); set.add(setItem);
@@ -1072,7 +1087,7 @@ describe('matchersUtil', function() {
}); });
it('passes for objects that equal to a set member', function() { it('passes for objects that equal to a set member', function() {
const matchersUtil = new privateUnderTest.MatchersUtil(); const matchersUtil = new jasmineUnderTest.MatchersUtil();
const set = new Set(); const set = new Set();
set.add({ foo: 'bar' }); set.add({ foo: 'bar' });
@@ -1084,8 +1099,8 @@ describe('matchersUtil', function() {
it('builds an English sentence for a failure case', function() { it('builds an English sentence for a failure case', function() {
const actual = 'foo', const actual = 'foo',
name = 'toBar', name = 'toBar',
pp = privateUnderTest.makePrettyPrinter(), pp = jasmineUnderTest.makePrettyPrinter(),
matchersUtil = new privateUnderTest.MatchersUtil({ pp: pp }), matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: pp }),
message = matchersUtil.buildFailureMessage(name, false, actual); message = matchersUtil.buildFailureMessage(name, false, actual);
expect(message).toEqual("Expected 'foo' to bar."); expect(message).toEqual("Expected 'foo' to bar.");
@@ -1095,8 +1110,8 @@ describe('matchersUtil', function() {
const actual = 'foo', const actual = 'foo',
name = 'toBar', name = 'toBar',
isNot = true, isNot = true,
pp = privateUnderTest.makePrettyPrinter(), pp = jasmineUnderTest.makePrettyPrinter(),
matchersUtil = new privateUnderTest.MatchersUtil({ pp: pp }), matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: pp }),
message = matchersUtil.buildFailureMessage(name, isNot, actual); message = matchersUtil.buildFailureMessage(name, isNot, actual);
expect(message).toEqual("Expected 'foo' not to bar."); expect(message).toEqual("Expected 'foo' not to bar.");
@@ -1105,8 +1120,8 @@ describe('matchersUtil', function() {
it('builds an English sentence for an arbitrary array of expected arguments', function() { it('builds an English sentence for an arbitrary array of expected arguments', function() {
const actual = 'foo', const actual = 'foo',
name = 'toBar', name = 'toBar',
pp = privateUnderTest.makePrettyPrinter(), pp = jasmineUnderTest.makePrettyPrinter(),
matchersUtil = new privateUnderTest.MatchersUtil({ pp: pp }), matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: pp }),
message = matchersUtil.buildFailureMessage( message = matchersUtil.buildFailureMessage(
name, name,
false, false,
@@ -1127,7 +1142,7 @@ describe('matchersUtil', function() {
pp = function(value) { pp = function(value) {
return '<' + value + '>'; return '<' + value + '>';
}, },
matchersUtil = new privateUnderTest.MatchersUtil({ pp: pp }), matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: pp }),
message = matchersUtil.buildFailureMessage( message = matchersUtil.buildFailureMessage(
name, name,
isNot, isNot,
+1 -1
View File
@@ -1,6 +1,6 @@
describe('nothing', function() { describe('nothing', function() {
it('should pass', function() { it('should pass', function() {
const matcher = privateUnderTest.matchers.nothing(), const matcher = jasmineUnderTest.matchers.nothing(),
result = matcher.compare(); result = matcher.compare();
expect(result.pass).toBe(true); expect(result.pass).toBe(true);
+12 -12
View File
@@ -1,6 +1,6 @@
describe('toBeCloseTo', function() { describe('toBeCloseTo', function() {
it('passes when within two decimal places by default', function() { it('passes when within two decimal places by default', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
let result; let result;
result = matcher.compare(0, 0); result = matcher.compare(0, 0);
@@ -14,7 +14,7 @@ describe('toBeCloseTo', function() {
}); });
it('fails when not within two decimal places by default', function() { it('fails when not within two decimal places by default', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
let result; let result;
result = matcher.compare(0, 0.01); result = matcher.compare(0, 0.01);
@@ -25,7 +25,7 @@ describe('toBeCloseTo', function() {
}); });
it('accepts an optional precision argument', function() { it('accepts an optional precision argument', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
let result; let result;
result = matcher.compare(0, 0.1, 0); result = matcher.compare(0, 0.1, 0);
@@ -48,7 +48,7 @@ describe('toBeCloseTo', function() {
}); });
it('fails when one of the arguments is null', function() { it('fails when one of the arguments is null', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
expect(function() { expect(function() {
matcher.compare(null, null); matcher.compare(null, null);
@@ -70,7 +70,7 @@ describe('toBeCloseTo', function() {
}); });
it('rounds expected values', function() { it('rounds expected values', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
let result; let result;
result = matcher.compare(1.23, 1.229); result = matcher.compare(1.23, 1.229);
@@ -98,7 +98,7 @@ describe('toBeCloseTo', function() {
}); });
it('handles edge cases with rounding', function() { it('handles edge cases with rounding', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
let result; let result;
// these cases resulted in false negatives in version of V8 // these cases resulted in false negatives in version of V8
@@ -113,37 +113,37 @@ describe('toBeCloseTo', function() {
describe('Infinity handling', function() { describe('Infinity handling', function() {
it('passes when the actual and expected are both Infinity', function() { it('passes when the actual and expected are both Infinity', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
const result = matcher.compare(Infinity, Infinity, 0); const result = matcher.compare(Infinity, Infinity, 0);
expect(result.pass).toBe(true); expect(result.pass).toBe(true);
}); });
it('passes when the actual and expected are both -Infinity', function() { it('passes when the actual and expected are both -Infinity', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
const result = matcher.compare(-Infinity, -Infinity, 0); const result = matcher.compare(-Infinity, -Infinity, 0);
expect(result.pass).toBe(true); expect(result.pass).toBe(true);
}); });
it('fails when the actual is Infinity and the expected is -Infinity', function() { it('fails when the actual is Infinity and the expected is -Infinity', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
const result = matcher.compare(Infinity, -Infinity, 0); const result = matcher.compare(Infinity, -Infinity, 0);
expect(result.pass).toBe(false); expect(result.pass).toBe(false);
}); });
it('fails when the actual is -Infinity and the expected is Infinity', function() { it('fails when the actual is -Infinity and the expected is Infinity', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
const result = matcher.compare(-Infinity, Infinity, 0); const result = matcher.compare(-Infinity, Infinity, 0);
expect(result.pass).toBe(false); expect(result.pass).toBe(false);
}); });
it('fails when the actual is a number and the expected is Infinity', function() { it('fails when the actual is a number and the expected is Infinity', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
const result = matcher.compare(42, Infinity, 0); const result = matcher.compare(42, Infinity, 0);
expect(result.pass).toBe(false); expect(result.pass).toBe(false);
}); });
it('fails when the actual is a number and the expected is -Infinity', function() { it('fails when the actual is a number and the expected is -Infinity', function() {
const matcher = privateUnderTest.matchers.toBeCloseTo(); const matcher = jasmineUnderTest.matchers.toBeCloseTo();
const result = matcher.compare(42, -Infinity, 0); const result = matcher.compare(42, -Infinity, 0);
expect(result.pass).toBe(false); expect(result.pass).toBe(false);
}); });
+2 -2
View File
@@ -1,12 +1,12 @@
describe('toBeDefined', function() { describe('toBeDefined', function() {
it('matches for defined values', function() { it('matches for defined values', function() {
const matcher = privateUnderTest.matchers.toBeDefined(); const matcher = jasmineUnderTest.matchers.toBeDefined();
const result = matcher.compare('foo'); const result = matcher.compare('foo');
expect(result.pass).toBe(true); expect(result.pass).toBe(true);
}); });
it('fails when matching undefined values', function() { it('fails when matching undefined values', function() {
const matcher = privateUnderTest.matchers.toBeDefined(); const matcher = jasmineUnderTest.matchers.toBeDefined();
const result = matcher.compare(void 0); const result = matcher.compare(void 0);
expect(result.pass).toBe(false); expect(result.pass).toBe(false);
}); });
+3 -3
View File
@@ -1,18 +1,18 @@
describe('toBeFalse', function() { describe('toBeFalse', function() {
it('passes for false', function() { it('passes for false', function() {
const matcher = privateUnderTest.matchers.toBeFalse(); const matcher = jasmineUnderTest.matchers.toBeFalse();
const result = matcher.compare(false); const result = matcher.compare(false);
expect(result.pass).toBe(true); expect(result.pass).toBe(true);
}); });
it('fails for non-false', function() { it('fails for non-false', function() {
const matcher = privateUnderTest.matchers.toBeFalse(); const matcher = jasmineUnderTest.matchers.toBeFalse();
const result = matcher.compare('foo'); const result = matcher.compare('foo');
expect(result.pass).toBe(false); expect(result.pass).toBe(false);
}); });
it('fails for falsy', function() { it('fails for falsy', function() {
const matcher = privateUnderTest.matchers.toBeFalse(); const matcher = jasmineUnderTest.matchers.toBeFalse();
const result = matcher.compare(undefined); const result = matcher.compare(undefined);
expect(result.pass).toBe(false); expect(result.pass).toBe(false);
}); });
+2 -2
View File
@@ -1,6 +1,6 @@
describe('toBeFalsy', function() { describe('toBeFalsy', function() {
it("passes for 'falsy' values", function() { it("passes for 'falsy' values", function() {
const matcher = privateUnderTest.matchers.toBeFalsy(); const matcher = jasmineUnderTest.matchers.toBeFalsy();
let result; let result;
result = matcher.compare(false); result = matcher.compare(false);
@@ -23,7 +23,7 @@ describe('toBeFalsy', function() {
}); });
it("fails for 'truthy' values", function() { it("fails for 'truthy' values", function() {
const matcher = privateUnderTest.matchers.toBeFalsy(); const matcher = jasmineUnderTest.matchers.toBeFalsy();
let result; let result;
result = matcher.compare(true); result = matcher.compare(true);
@@ -1,6 +1,6 @@
describe('toBeGreaterThanOrEqual', function() { describe('toBeGreaterThanOrEqual', function() {
it('passes when actual >= expected', function() { it('passes when actual >= expected', function() {
const matcher = privateUnderTest.matchers.toBeGreaterThanOrEqual(); const matcher = jasmineUnderTest.matchers.toBeGreaterThanOrEqual();
let result; let result;
result = matcher.compare(2, 1); result = matcher.compare(2, 1);
@@ -17,7 +17,7 @@ describe('toBeGreaterThanOrEqual', function() {
}); });
it('fails when actual < expected', function() { it('fails when actual < expected', function() {
const matcher = privateUnderTest.matchers.toBeGreaterThanOrEqual(); const matcher = jasmineUnderTest.matchers.toBeGreaterThanOrEqual();
let result; let result;
result = matcher.compare(1, 2); result = matcher.compare(1, 2);
+2 -2
View File
@@ -1,12 +1,12 @@
describe('toBeGreaterThan', function() { describe('toBeGreaterThan', function() {
it('passes when actual > expected', function() { it('passes when actual > expected', function() {
const matcher = privateUnderTest.matchers.toBeGreaterThan(); const matcher = jasmineUnderTest.matchers.toBeGreaterThan();
const result = matcher.compare(2, 1); const result = matcher.compare(2, 1);
expect(result.pass).toBe(true); expect(result.pass).toBe(true);
}); });
it('fails when actual <= expected', function() { it('fails when actual <= expected', function() {
const matcher = privateUnderTest.matchers.toBeGreaterThan(); const matcher = jasmineUnderTest.matchers.toBeGreaterThan();
let result; let result;
result = matcher.compare(1, 1); result = matcher.compare(1, 1);
+24 -24
View File
@@ -1,7 +1,7 @@
describe('toBeInstanceOf', function() { describe('toBeInstanceOf', function() {
describe('when expecting Number', function() { describe('when expecting Number', function() {
it('passes for literal number', function() { it('passes for literal number', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(3, Number); const result = matcher.compare(3, Number);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -10,8 +10,8 @@ describe('toBeInstanceOf', function() {
}); });
it('passes for NaN', function() { it('passes for NaN', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf({ const matcher = jasmineUnderTest.matchers.toBeInstanceOf({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}); });
const result = matcher.compare(NaN, Number); const result = matcher.compare(NaN, Number);
expect(result).toEqual({ expect(result).toEqual({
@@ -21,7 +21,7 @@ describe('toBeInstanceOf', function() {
}); });
it('passes for Infinity', function() { it('passes for Infinity', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(Infinity, Number); const result = matcher.compare(Infinity, Number);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -30,7 +30,7 @@ describe('toBeInstanceOf', function() {
}); });
it('fails for a non-number', function() { it('fails for a non-number', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare('foo', Number); const result = matcher.compare('foo', Number);
expect(result).toEqual({ expect(result).toEqual({
pass: false, pass: false,
@@ -41,7 +41,7 @@ describe('toBeInstanceOf', function() {
describe('when expecting String', function() { describe('when expecting String', function() {
it('passes for a string', function() { it('passes for a string', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare('foo', String); const result = matcher.compare('foo', String);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -50,7 +50,7 @@ describe('toBeInstanceOf', function() {
}); });
it('fails for a non-string', function() { it('fails for a non-string', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare({}, String); const result = matcher.compare({}, String);
expect(result).toEqual({ expect(result).toEqual({
pass: false, pass: false,
@@ -61,7 +61,7 @@ describe('toBeInstanceOf', function() {
describe('when expecting Boolean', function() { describe('when expecting Boolean', function() {
it('passes for a boolean', function() { it('passes for a boolean', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(true, Boolean); const result = matcher.compare(true, Boolean);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -70,7 +70,7 @@ describe('toBeInstanceOf', function() {
}); });
it('fails for a non-boolean', function() { it('fails for a non-boolean', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare('false', Boolean); const result = matcher.compare('false', Boolean);
expect(result).toEqual({ expect(result).toEqual({
pass: false, pass: false,
@@ -81,7 +81,7 @@ describe('toBeInstanceOf', function() {
describe('when expecting RegExp', function() { describe('when expecting RegExp', function() {
it('passes for a literal regular expression', function() { it('passes for a literal regular expression', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(/foo/, RegExp); const result = matcher.compare(/foo/, RegExp);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -94,7 +94,7 @@ describe('toBeInstanceOf', function() {
it('passes for a function', function() { it('passes for a function', function() {
const fn = function() {}; const fn = function() {};
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(fn, Function); const result = matcher.compare(fn, Function);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -108,7 +108,7 @@ describe('toBeInstanceOf', function() {
return 'foo'; return 'foo';
} }
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(fn, Function); const result = matcher.compare(fn, Function);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -122,7 +122,7 @@ describe('toBeInstanceOf', function() {
function Animal() {} function Animal() {}
it('passes for any object', function() { it('passes for any object', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare({ foo: 'bar' }, Object); const result = matcher.compare({ foo: 'bar' }, Object);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -131,7 +131,7 @@ describe('toBeInstanceOf', function() {
}); });
it('passes for an Error object', function() { it('passes for an Error object', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(new Error('example'), Object); const result = matcher.compare(new Error('example'), Object);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -140,7 +140,7 @@ describe('toBeInstanceOf', function() {
}); });
it('passes for a user-defined class', function() { it('passes for a user-defined class', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(new Animal(), Object); const result = matcher.compare(new Animal(), Object);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -149,7 +149,7 @@ describe('toBeInstanceOf', function() {
}); });
it('fails for a non-object', function() { it('fails for a non-object', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare('foo', Object); const result = matcher.compare('foo', Object);
expect(result).toEqual({ expect(result).toEqual({
pass: false, pass: false,
@@ -160,8 +160,8 @@ describe('toBeInstanceOf', function() {
it('passes for objects with no constructor', function() { it('passes for objects with no constructor', function() {
const object = Object.create(null); const object = Object.create(null);
const matcher = privateUnderTest.matchers.toBeInstanceOf({ const matcher = jasmineUnderTest.matchers.toBeInstanceOf({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}); });
const result = matcher.compare(object, Object); const result = matcher.compare(object, Object);
expect(result).toEqual({ expect(result).toEqual({
@@ -190,7 +190,7 @@ describe('toBeInstanceOf', function() {
Cat.prototype.constructor = Cat; Cat.prototype.constructor = Cat;
it('passes for instances of that class', function() { it('passes for instances of that class', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(new Animal(), Animal); const result = matcher.compare(new Animal(), Animal);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -199,7 +199,7 @@ describe('toBeInstanceOf', function() {
}); });
it('passes for instances of a subclass', function() { it('passes for instances of a subclass', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(new Cat(), Animal); const result = matcher.compare(new Cat(), Animal);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -208,7 +208,7 @@ describe('toBeInstanceOf', function() {
}); });
it('does not pass for sibling classes', function() { it('does not pass for sibling classes', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
const result = matcher.compare(new Dog(), Cat); const result = matcher.compare(new Dog(), Cat);
expect(result).toEqual({ expect(result).toEqual({
pass: false, pass: false,
@@ -218,7 +218,7 @@ describe('toBeInstanceOf', function() {
}); });
it('raises an error if passed an invalid expected value', function() { it('raises an error if passed an invalid expected value', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf(); const matcher = jasmineUnderTest.matchers.toBeInstanceOf();
expect(function() { expect(function() {
matcher.compare({}, 'Error'); matcher.compare({}, 'Error');
}).toThrowError( }).toThrowError(
@@ -228,8 +228,8 @@ describe('toBeInstanceOf', function() {
}); });
it('raises an error if missing an expected value', function() { it('raises an error if missing an expected value', function() {
const matcher = privateUnderTest.matchers.toBeInstanceOf({ const matcher = jasmineUnderTest.matchers.toBeInstanceOf({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}); });
expect(function() { expect(function() {
matcher.compare({}, undefined); matcher.compare({}, undefined);
@@ -1,6 +1,6 @@
describe('toBeLessThanOrEqual', function() { describe('toBeLessThanOrEqual', function() {
it('passes when actual <= expected', function() { it('passes when actual <= expected', function() {
const matcher = privateUnderTest.matchers.toBeLessThanOrEqual(); const matcher = jasmineUnderTest.matchers.toBeLessThanOrEqual();
let result; let result;
result = matcher.compare(1, 2); result = matcher.compare(1, 2);
@@ -17,7 +17,7 @@ describe('toBeLessThanOrEqual', function() {
}); });
it('fails when actual < expected', function() { it('fails when actual < expected', function() {
const matcher = privateUnderTest.matchers.toBeLessThanOrEqual(); const matcher = jasmineUnderTest.matchers.toBeLessThanOrEqual();
let result; let result;
result = matcher.compare(2, 1); result = matcher.compare(2, 1);
+2 -2
View File
@@ -1,12 +1,12 @@
describe('toBeLessThan', function() { describe('toBeLessThan', function() {
it('passes when actual < expected', function() { it('passes when actual < expected', function() {
const matcher = privateUnderTest.matchers.toBeLessThan(); const matcher = jasmineUnderTest.matchers.toBeLessThan();
const result = matcher.compare(1, 2); const result = matcher.compare(1, 2);
expect(result.pass).toBe(true); expect(result.pass).toBe(true);
}); });
it('fails when actual <= expected', function() { it('fails when actual <= expected', function() {
const matcher = privateUnderTest.matchers.toBeLessThan(); const matcher = jasmineUnderTest.matchers.toBeLessThan();
let result; let result;
result = matcher.compare(1, 1); result = matcher.compare(1, 1);
+4 -4
View File
@@ -1,13 +1,13 @@
describe('toBeNaN', function() { describe('toBeNaN', function() {
it('passes for NaN with a custom .not fail', function() { it('passes for NaN with a custom .not fail', function() {
const matcher = privateUnderTest.matchers.toBeNaN(); const matcher = jasmineUnderTest.matchers.toBeNaN();
const result = matcher.compare(Number.NaN); const result = matcher.compare(Number.NaN);
expect(result.pass).toBe(true); expect(result.pass).toBe(true);
expect(result.message).toEqual('Expected actual not to be NaN.'); expect(result.message).toEqual('Expected actual not to be NaN.');
}); });
it('fails for anything not a NaN', function() { it('fails for anything not a NaN', function() {
const matcher = privateUnderTest.matchers.toBeNaN(); const matcher = jasmineUnderTest.matchers.toBeNaN();
let result; let result;
result = matcher.compare(1); result = matcher.compare(1);
@@ -27,8 +27,8 @@ describe('toBeNaN', function() {
}); });
it('has a custom message on failure', function() { it('has a custom message on failure', function() {
const matcher = privateUnderTest.matchers.toBeNaN({ const matcher = jasmineUnderTest.matchers.toBeNaN({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
result = matcher.compare(0); result = matcher.compare(0);
@@ -1,6 +1,6 @@
describe('toBeNegativeInfinity', function() { describe('toBeNegativeInfinity', function() {
it("fails for anything that isn't -Infinity", function() { it("fails for anything that isn't -Infinity", function() {
const matcher = privateUnderTest.matchers.toBeNegativeInfinity(); const matcher = jasmineUnderTest.matchers.toBeNegativeInfinity();
let result; let result;
result = matcher.compare(1); result = matcher.compare(1);
@@ -14,8 +14,8 @@ describe('toBeNegativeInfinity', function() {
}); });
it('has a custom message on failure', function() { it('has a custom message on failure', function() {
const matcher = privateUnderTest.matchers.toBeNegativeInfinity({ const matcher = jasmineUnderTest.matchers.toBeNegativeInfinity({
pp: privateUnderTest.makePrettyPrinter() pp: jasmineUnderTest.makePrettyPrinter()
}), }),
result = matcher.compare(0); result = matcher.compare(0);
@@ -23,7 +23,7 @@ describe('toBeNegativeInfinity', function() {
}); });
it('succeeds for -Infinity', function() { it('succeeds for -Infinity', function() {
const matcher = privateUnderTest.matchers.toBeNegativeInfinity(), const matcher = jasmineUnderTest.matchers.toBeNegativeInfinity(),
result = matcher.compare(Number.NEGATIVE_INFINITY); result = matcher.compare(Number.NEGATIVE_INFINITY);
expect(result.pass).toBe(true); expect(result.pass).toBe(true);
+2 -2
View File
@@ -1,12 +1,12 @@
describe('toBeNull', function() { describe('toBeNull', function() {
it('passes for null', function() { it('passes for null', function() {
const matcher = privateUnderTest.matchers.toBeNull(); const matcher = jasmineUnderTest.matchers.toBeNull();
const result = matcher.compare(null); const result = matcher.compare(null);
expect(result.pass).toBe(true); expect(result.pass).toBe(true);
}); });
it('fails for non-null', function() { it('fails for non-null', function() {
const matcher = privateUnderTest.matchers.toBeNull(); const matcher = jasmineUnderTest.matchers.toBeNull();
const result = matcher.compare('foo'); const result = matcher.compare('foo');
expect(result.pass).toBe(false); expect(result.pass).toBe(false);
}); });

Some files were not shown because too many files have changed in this diff Show More