diff --git a/.circleci/config.yml b/.circleci/config.yml index 1498ecb2..27551f34 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -15,13 +15,13 @@ executors: docker: - image: circleci/node:14 working_directory: ~/workspace - node12: + node12_latest: docker: - - image: circleci/node:12 + - image: circleci/node:12 working_directory: ~/workspace - node10: + node12_17: docker: - - image: circleci/node:10 + - image: circleci/node:12.17 working_directory: ~/workspace jobs: @@ -116,26 +116,26 @@ workflows: executor: node14 name: build_node_14 - build: - executor: node12 - name: build_node_12 + executor: node12_latest + name: build_node_12_latest - build: - executor: node10 - name: build_node_10 + executor: node12_17 + name: build_node_12_17 - test_node: executor: node16 name: test_node_16 requires: - build_node_16 - test_node: - executor: node12 - name: test_node_12 + executor: node12_latest + name: test_node_12_latest requires: - - build_node_12 + - build_node_12_latest - test_node: - executor: node10 - name: test_node_10 + executor: node12_17 + name: test_node_12_17 requires: - - build_node_10 + - build_node_12_17 - test_browsers: requires: - build_node_14 @@ -152,11 +152,11 @@ workflows: executor: node14 name: build_node_14 - build: - executor: node12 - name: build_node_12 + executor: node12_latest + name: build_node_12_latest - build: - executor: node10 - name: build_node_10 + executor: node12_17 + name: build_node_12_17 - test_node: executor: node16 name: test_node_16 @@ -168,15 +168,15 @@ workflows: requires: - build_node_14 - test_node: - executor: node12 - name: test_node_12 + executor: node12_latest + name: test_node_12_latest requires: - - build_node_12 + - build_node_12_latest - test_node: - executor: node10 - name: test_node_10 + executor: node12_17 + name: test_node_12_17 requires: - - build_node_10 + - build_node_12_17 - test_browsers: requires: - build_node_14 diff --git a/.editorconfig b/.editorconfig index 9582a3cc..12562f79 100644 --- a/.editorconfig +++ b/.editorconfig @@ -3,14 +3,6 @@ charset = utf-8 end_of_line = lf insert_final_newline = true -[*.{js, json, sh, yml, gemspec}] +[*.{js, json, sh, yml}] indent_style = space indent_size = 2 - -[{Rakefile, .jshintrc}] -indent_style = space -indent_size = 2 - -[*.{py}] -indent_style = space -indent_size = 4 diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 867de0e0..3fed0f43 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -12,24 +12,23 @@ should have enough detail to get started. - [Jasmine Google Group](http://groups.google.com/group/jasmine-js) - [Jasmine-dev Google Group](http://groups.google.com/group/jasmine-js-dev) -- [Jasmine on PivotalTracker](https://www.pivotaltracker.com/n/projects/10606) +- [Jasmine backlog](https://www.pivotaltracker.com/n/projects/10606) -## General Workflow +## Before Submitting a Pull Request -Please submit pull requests via feature branches using the semi-standard workflow of: +1. Ensure all specs are green in browsers *and* node. + * Use `npm test` to test in Node. + * Use `npm run serve` to test in browsers. +2. Fix any eslint or prettier errors reported at the end of `npm test`. Prettier + errors can be automatically fixed by running `npm run cleanup`. +3. Build `jasmine.js` with `npm run build` and run all specs again. This + ensures that your changes self-test well. +5. Revert your changes to `jasmine.js` and `jasmine-html.js`. When we accept + your pull request, we will generate these files as a separate commit and + merge the entire branch into master. -```bash -git clone git@github.com:yourUserName/jasmine.git # Clone your fork -cd jasmine # Change directory -git remote add upstream https://github.com/jasmine/jasmine.git # Assign original repository to a remote named 'upstream' -git fetch upstream # Fetch changes not present in your local repository -git merge upstream/main # Sync local main with upstream repository -git checkout -b my-new-feature # Create your feature branch -git commit -am 'Add some feature' # Commit your changes -git push origin my-new-feature # Push to the branch -``` - -Once you've pushed a feature branch to your forked repo, you're ready to open a pull request. We favor pull requests with very small, single commits with a single purpose. +We only accept green pull requests. If you see that the CI build failed, please +fix it. Feel free to ask for help if you're stuck. ## Background @@ -38,15 +37,16 @@ Once you've pushed a feature branch to your forked repo, you're ready to open a * `/src` contains all of the source files * `/src/core` - generic source files * `/src/html` - browser-specific files + * `/src/boot` - sources for boot files (see below) * `/spec` contains all of the tests * mirrors the source directory * there are some additional files * `/lib` contains the compiled copy of Jasmine. This is used to self-test and - distributed as the `jasmine-core` Node, Ruby, and Python packages. + distributed as the `jasmine-core` Node, and Ruby packages. ### Self-testing -Note that Jasmine tests itself. The files in `lib` are loaded first, defining the reference `jasmine`. Then the files in `src` are loaded, defining the reference `jasmineUnderTest`. So there are two copies of the code loaded under test. +Jasmine tests itself. The files in `lib` are loaded first, defining the reference `jasmine`. Then the files in `src` are loaded, defining the reference `jasmineUnderTest`. So there are two copies of the code loaded under test. The tests should always use `jasmineUnderTest` to refer to the objects and functions that are being tested. But the tests can use functions on `jasmine` as needed. _Be careful how you structure any new test code_. Copy the patterns you see in the existing code - this ensures that the code you're testing is not leaking into the `jasmine` reference and vice-versa. @@ -60,9 +60,8 @@ is appropriate for browsers, projects may wish to customize this file. ### Compatibility -Jasmine runs in both Node and browsers, including some older browsers that do -not support the latest JavaScript features. See the README for the list of -currently supported environments. +Jasmine runs in both Node and a variety of browsers. See the README for the +list of currently supported environments. ## Development @@ -88,51 +87,35 @@ Or, How to make a successful pull request * _Do not change the public interface_. Lots of projects depend on Jasmine and if you aren't careful you'll break them. -* _Be environment agnostic_ - server-side developers are just as important as - browser developers. +* _Be environment agnostic_. Some people run their specs in browsers, others in + Node. Jasmine should support them all as much as possible. * _Be browser agnostic_ - if you must rely on browser-specific functionality, please write it in a way that degrades gracefully. * _Write specs_ - Jasmine's a testing framework. Don't add functionality without test-driving it. * _Write code in the style of the rest of the repo_ - Jasmine should look like a cohesive whole. + + Key exceptions: + * Use `const` or `let` for new variable declarations, even if nearby code + uses `var`. + * New async specs should usually be async/await or promise-returning, not + callback based. + * _Ensure the *entire* test suite is green_ in all the big browsers, Node, and - ESLint. Your contribution shouldn't break Jasmine for other users. + ESLint/Prettier. Your contribution shouldn't break Jasmine for other users. Follow these tips and your pull request, patch, or suggestion is much more likely to be integrated. ### Running Specs Be sure to run the tests in at least one supported Node version and at least a -couple of supported browsers. It's also a good idea to run the tests in Internet -Explorer if you've touched code in `src/html`, if your change involves newer -JavaScript language/runtime features, or if you're unfamiliar with writing code -for older browsers. To run the tests in Node, simply use `npm test` as described -above. To run the tests in a browser, run `npm run serve` and then visit -`http://localhost:8888`. +couple of supported browsers. To run the tests in Node, simply use `npm test` +as described above. To run the tests in a browser, run `npm run serve` and then +visit `http://localhost:8888`. -If you have the necessary Selenium drivers installed, you can also use Jasmine's -CI tooling: +If you have the necessary Selenium drivers installed (e.g. geckodriver or +chromedriver), you can also use Jasmine's CI tooling: - $ JASMINE_BROWSER= node spec/support/ci.js - -The easiest way to run the tests in **Internet Explorer** is to run a VM that has IE installed. It's easy to do this with VirtualBox. - -1. Download and install [VirtualBox](https://www.virtualbox.org/wiki/Downloads). -1. Download a VM image [from Microsoft](https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/). Select "VirtualBox" as the platform. -1. Unzip the downloaded archive. There should be an OVA file inside. -1. In VirtualBox, choose `File > Import Appliance` and select the OVA file. Accept the default settings in the dialog that appears. Now you have a Windows VM! -1. Run the VM and start IE. -1. With `npm run serve` running on your host machine, navigate to `http://:8888` in IE. - -## Before Committing or Submitting a Pull Request - -1. Ensure all specs are green in browser *and* node. -1. Ensure eslint and prettier are clean as part of your `npm test` command. You can run `npm run cleanup` to have prettier re-write the files. -1. Build `jasmine.js` with `npm run build` and run all specs again - this ensures that your changes self-test well. -1. Revert your changes to `jasmine.js` and `jasmine-html.js` - * We do this because `jasmine.js` and `jasmine-html.js` are auto-generated (as you've seen in the previous steps) and accepting multiple pull requests when this auto-generated file changes causes lots of headaches - * When we accept your pull request, we will generate these files as a separate commit and merge the entire branch into main - -Note that we use Circle CI for Continuous Integration. We only accept green pull requests. + $ JASMINE_BROWSER= npm run ci diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 68876a5f..55507cc0 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -24,7 +24,7 @@ - [ ] My code follows the code style of this project. - [ ] My change requires a change to the documentation. - [ ] I have updated the documentation accordingly. -- [ ] I have read the **CONTRIBUTING** document. +- [ ] I have read the [**CONTRIBUTING**](https://github.com/jasmine/jasmine/blob/main/.github/CONTRIBUTING.md) guide. - [ ] I have added tests to cover my changes. - [ ] All new and existing tests passed. diff --git a/.gitignore b/.gitignore index 644ebecd..8dcc71a6 100644 --- a/.gitignore +++ b/.gitignore @@ -17,11 +17,9 @@ pkg/* .sass-cache/* src/html/.sass-cache/* node_modules/ -*.pyc sauce_connect.log *.swp build/ -*.egg-info/ dist nbproject/ *.iml diff --git a/.rspec b/.rspec deleted file mode 100644 index 4e1e0d2f..00000000 --- a/.rspec +++ /dev/null @@ -1 +0,0 @@ ---color diff --git a/Gemfile b/Gemfile deleted file mode 100644 index 851fabc2..00000000 --- a/Gemfile +++ /dev/null @@ -1,2 +0,0 @@ -source 'https://rubygems.org' -gemspec diff --git a/Gruntfile.js b/Gruntfile.js index e50595cd..9a04fccb 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -16,12 +16,6 @@ module.exports = function(grunt) { grunt.registerTask('default', ['sass:dist', "cssUrlEmbed"]); - var version = require('./grunt/tasks/version.js'); - - grunt.registerTask('build:copyVersionToGem', - "Propagates the version from package.json to version.rb", - version.copyToGem); - grunt.registerTask('buildDistribution', 'Builds and lints jasmine.js, jasmine-html.js, jasmine.css', [ @@ -34,18 +28,16 @@ module.exports = function(grunt) { grunt.registerTask("execSpecsInNode", "Run Jasmine core specs in Node.js", function() { - var done = this.async(), + verifyNoGlobals(() => require('./lib/jasmine-core.js').noGlobals()); + const done = this.async(), Jasmine = require('jasmine'), jasmineCore = require('./lib/jasmine-core.js'), jasmine = new Jasmine({jasmineCore: jasmineCore}); jasmine.loadConfigFile('./spec/support/jasmine.json'); - jasmine.exitOnCompletion = false; jasmine.execute().then( - result => { - done(result.overallStatus === 'passed'); - }, + result => done(result.overallStatus === 'passed'), err => { console.error(err); exit(1); @@ -61,3 +53,14 @@ module.exports = function(grunt) { } ); }; + +function verifyNoGlobals(fn) { + const initialGlobals = Object.keys(global); + fn(); + + const extras = Object.keys(global).filter(k => !initialGlobals.includes(k)); + + if (extras.length !== 0) { + throw new Error('Globals were unexpectedly created: ' + extras.join(', ')); + } +} diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index 122cd026..00000000 --- a/MANIFEST.in +++ /dev/null @@ -1,6 +0,0 @@ -recursive-include . *.py -prune node_modules -include lib/jasmine-core/*.js -include lib/jasmine-core/*.css -include images/*.png -include package.json diff --git a/README.md b/README.md index f900383e..f2d93f41 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,9 @@ Jasmine is a Behavior Driven Development testing framework for JavaScript. It do Documentation & guides live here: [http://jasmine.github.io](http://jasmine.github.io/) For a quick start guide of Jasmine, see the beginning of [http://jasmine.github.io/edge/introduction.html](http://jasmine.github.io/edge/introduction.html). +Upgrading from Jasmine 3.x? Check out the 4.0 release notes for a list of +what's new (including breaking changes). You can also read the [upgrade guide](https://jasmine.github.io/tutorials/upgrading_to_Jasmine_4.0). + ## Contributing Please read the [contributors' guide](https://github.com/jasmine/jasmine/blob/main/.github/CONTRIBUTING.md). @@ -23,9 +26,6 @@ For the Jasmine NPM module:
For the Jasmine browser runner:
[https://github.com/jasmine/jasmine-browser](https://github.com/jasmine/jasmine-browser). -For the Jasmine Ruby Gem:
-[https://github.com/jasmine/jasmine-gem](https://github.com/jasmine/jasmine-gem). - To install Jasmine standalone on your local box (where **_{#.#.#}_** below is substituted by the release number downloaded): * Download the standalone distribution for your desired release from the [releases page](https://github.com/jasmine/jasmine/releases). @@ -47,21 +47,24 @@ Add the following to your HTML file: ## Supported environments -Jasmine tests itself across many browsers (Safari, Chrome, Firefox, Microsoft Edge, and Internet Explorer) as well as nodejs. +Jasmine tests itself across popular browsers (Safari, Chrome, Firefox, and +Microsoft Edge) as well as nodejs. | Environment | Supported versions | |-------------------|--------------------| -| Node | 10, 12, 14, 16 | -| Safari | 8-14 | +| Node | 12.17+, 14, 16 | +| Safari | 14-15 | | Chrome | Evergreen | -| Firefox | Evergreen, 68, 78, 91 | +| Firefox | Evergreen, 91 | | Edge | Evergreen | -| Internet Explorer | 10, 11 | For evergreen browsers, each version of Jasmine is tested against the version of the browser that is available to us at the time of release. Other browsers, as well as older & newer versions of some supported browsers, are likely to work. However, Jasmine isn't tested against them and they aren't actively supported. +See the [release notes](https://github.com/jasmine/jasmine/tree/main/release_notes) +for the supported environments for each Jasmine release. + ## Support * Search past discussions: [http://groups.google.com/group/jasmine-js](http://groups.google.com/group/jasmine-js). diff --git a/RELEASE.md b/RELEASE.md index 7e3d959b..6762af90 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -13,13 +13,14 @@ Please attempt to keep commits to `main` small, but cohesive. If a feature is co We attempt to stick to [Semantic Versioning](http://semver.org/). Most of the time, development should be against a new minor version - fixing bugs and adding new features that are backwards compatible. -The current version lives in the file `/package.json`. This version will be the version number that is currently released. When releasing a new version, update `package.json` with the new version and `grunt build:copyVersionToGem` to update the gem version number. - -This version is used by both `jasmine.js` and the `jasmine-core` Ruby gem. +The current version lives in the file `/package.json`. This version will be +copied to `jasmine.js` when the distribution is built. When releasing a new +version, update `package.json` with the new version and `npm run build` to +update the gem version number. Note that Jasmine should only use the "patch" version number in the following cases: -* Changes related to packaging for a specific platform (npm, gem, or pip). +* Changes related to packaging for a specific binding library (npm or browser-runner) * Fixes for regressions. When jasmine-core revs its major or minor version, the binding libraries should also rev to that version. @@ -31,7 +32,6 @@ When ready to release - specs are all green and the stories are done: 1. Update the release notes in `release_notes` - use the Anchorman gem to generate the markdown file and edit accordingly. Include a list of supported environments. 1. Update the version in `package.json` 1. Run `npm run build`. -1. Copy version to the Ruby gem with `grunt build:copyVersionToGem` ### Commit and push core changes @@ -45,18 +45,6 @@ When ready to release - specs are all green and the stories are done: 1. Build the standalone distribution with `grunt buildStandaloneDist` 1. This will generate `dist/jasmine-standalone-.zip`, which you will upload later (see "Finally" below). -### Release the core Ruby gem - -1. __NOTE__: You will likely need to push a new jasmine gem with a dependent version right after this release. See below. -1. `rake release` - tags the repo with the version, builds the `jasmine-core` gem, pushes the gem to Rubygems.org. In order to release you will have to ensure you have rubygems creds locally. - -### Release the core Python egg - -Install [twine](https://github.com/pypa/twine) - -1. `python setup.py sdist` -1. `twine upload dist/jasmine-core-.tar.gz` You will need pypi credentials to upload the egg. - ### Release the core NPM module 1. Run the tests on Windows. (CI only tests on Linux.) @@ -83,15 +71,6 @@ Probably only need to do this when releasing a minor version, and not a patch ve 1. Run the tests on Windows locally. 1. `grunt release `. (Note: This will publish the package by running `npm publish`.) -#### Gem - -1. Create release notes using Anchorman as above -1. Update the version number in `lib/jasmine/version.rb`. -1. Update the jasmine-core dependency version in `jasmine.gemspec`. -1. Commit and push. -1. Wait for Circle CI to go green again. -1. `rake release` - ### Finally For each of the above GitHub repos: diff --git a/Rakefile b/Rakefile deleted file mode 100644 index 2480d0e6..00000000 --- a/Rakefile +++ /dev/null @@ -1,2 +0,0 @@ -require "bundler" -Bundler::GemHelper.install_tasks diff --git a/bower.json b/bower.json deleted file mode 100644 index 34157580..00000000 --- a/bower.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "jasmine-core", - "homepage": "https://jasmine.github.io", - "authors": [ - "slackersoft " - ], - "description": "Official packaging of Jasmine's core files", - "keywords": [ - "test", - "jasmine", - "tdd", - "bdd" - ], - "license": "MIT", - "moduleType": "globals", - "main": "lib/jasmine-core/jasmine.js", - "ignore": [ - "**/.*", - "dist", - "grunt", - "node_modules", - "pkg", - "release_notes", - "spec", - "src", - "Gemfile", - "Gemfile.lock", - "Rakefile", - "jasmine-core.gemspec", - "*.sh", - "*.py", - "Gruntfile.js", - "lib/jasmine-core.rb", - "lib/jasmine-core/boot/", - "lib/jasmine-core/spec", - "lib/jasmine-core/version.rb", - "lib/jasmine-core/*.py", - "sauce_connect.log" - ] -} diff --git a/grunt/config/compress.js b/grunt/config/compress.js index d8905113..551b50b4 100644 --- a/grunt/config/compress.js +++ b/grunt/config/compress.js @@ -32,7 +32,7 @@ module.exports = { src: [ "boot0.js", "boot1.js" ], dest: standaloneLibDir, expand: true, - cwd: libJasmineCore("boot") + cwd: libJasmineCore("") }, { src: [ "SpecRunner.html" ], diff --git a/grunt/config/concat.js b/grunt/config/concat.js index 098aa2a8..23997b48 100644 --- a/grunt/config/concat.js +++ b/grunt/config/concat.js @@ -37,20 +37,16 @@ module.exports = { ], dest: 'lib/jasmine-core/jasmine.js' }, - boot: { - src: ['lib/jasmine-core/boot/boot.js'], - dest: 'lib/jasmine-core/boot.js' - }, boot0: { - src: ['lib/jasmine-core/boot/boot0.js'], + src: ['src/boot/boot0.js'], dest: 'lib/jasmine-core/boot0.js' }, boot1: { - src: ['lib/jasmine-core/boot/boot1.js'], + src: ['src/boot/boot1.js'], dest: 'lib/jasmine-core/boot1.js' }, nodeBoot: { - src: ['lib/jasmine-core/boot/node_boot.js'], + src: ['src/boot/node_boot.js'], dest: 'lib/jasmine-core/node_boot.js' }, options: { diff --git a/grunt/tasks/version.js b/grunt/tasks/version.js deleted file mode 100644 index f8ff6a10..00000000 --- a/grunt/tasks/version.js +++ /dev/null @@ -1,14 +0,0 @@ -var grunt = require("grunt"); - -function gemLib(path) { return './lib/jasmine-core/' + path; } -function nodeToRuby(version) { return version.replace('-', '.'); } - -module.exports = { - copyToGem: function() { - var versionRb = grunt.template.process( - grunt.file.read("grunt/templates/version.rb.jst"), - { data: { jasmineVersion: nodeToRuby(global.jasmineVersion) }}); - - grunt.file.write(gemLib("version.rb"), versionRb); - } -}; diff --git a/grunt/templates/version.rb.jst b/grunt/templates/version.rb.jst deleted file mode 100644 index 411403c2..00000000 --- a/grunt/templates/version.rb.jst +++ /dev/null @@ -1,9 +0,0 @@ -# -# DO NOT Edit this file. Canonical version of Jasmine lives in the repo's package.json. This file is generated -# by a grunt task when the standalone release is built. -# -module Jasmine - module Core - VERSION = "<%= jasmineVersion %>" - end -end diff --git a/images/__init__.py b/images/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/jasmine-core.gemspec b/jasmine-core.gemspec deleted file mode 100644 index fece3c1c..00000000 --- a/jasmine-core.gemspec +++ /dev/null @@ -1,30 +0,0 @@ -# -*- encoding: utf-8 -*- -$:.push File.expand_path("../lib", __FILE__) -require "jasmine-core/version" - -Gem::Specification.new do |s| - s.name = "jasmine-core" - s.version = Jasmine::Core::VERSION - s.platform = Gem::Platform::RUBY - s.authors = ["Gregg Van Hove"] - s.summary = %q{JavaScript BDD framework} - s.description = <<~DESC - Test your JavaScript without any framework dependencies, in any environment, - and with a nice descriptive syntax. - - Jasmine for Ruby is deprecated. The direct replacment for the jasmine-core - gem is the jasmine-core NPM package. If you are also using the jasmine gem, - we recommend using the jasmine-browser-runner NPM package instead. It - supports all the same scenarios as the jasmine gem gem plus Webpacker. See - https://jasmine.github.io/setup/browser.html for setup instructions, and - https://github.com/jasmine/jasmine-gem/blob/main/release_notes/3.9.0.md - for other options. - DESC - s.email = %q{jasmine-js@googlegroups.com} - s.homepage = "http://jasmine.github.io" - s.license = "MIT" - - s.files = Dir.glob("./lib/**/*") - s.require_paths = ["lib"] - s.add_development_dependency "rake" -end diff --git a/lib/jasmine-core.js b/lib/jasmine-core.js index 886b7920..314ff9e7 100644 --- a/lib/jasmine-core.js +++ b/lib/jasmine-core.js @@ -1,6 +1,42 @@ -module.exports = require("./jasmine-core/jasmine.js"); +/** + * Note: Only available on Node. + * @module jasmine-core + */ + +const jasmineRequire = require('./jasmine-core/jasmine.js'); +module.exports = jasmineRequire; + +/** + * Boots a copy of Jasmine and returns an object as described in {@link jasmine}. + * @type {function} + * @return {jasmine} + */ module.exports.boot = require('./jasmine-core/node_boot.js'); +/** + * 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 + * multiple times, the same object is returned every time. + * + * Do not call boot() if you also call noGlobals(). + * + * @example + * const {describe, beforeEach, it, expect, jasmine} = require('jasmine-core').noGlobals(); + */ +module.exports.noGlobals = (function() { + let jasmineInterface; + + return function bootWithoutGlobals() { + if (!jasmineInterface) { + const jasmine = jasmineRequire.core(jasmineRequire); + const env = jasmine.getEnv({ suppressLoadErrors: true }); + jasmineInterface = jasmineRequire.interface(jasmine, env); + } + + return jasmineInterface; + }; +}()); + var path = require('path'), fs = require('fs'); diff --git a/lib/jasmine-core.rb b/lib/jasmine-core.rb deleted file mode 100644 index 55a03fba..00000000 --- a/lib/jasmine-core.rb +++ /dev/null @@ -1,78 +0,0 @@ -if ENV["SUPPRESS_JASMINE_DEPRECATION"].nil? - puts <<~END_DEPRECATION_MSG - The Jasmine Ruby gems are deprecated. There will be no further releases after - the end of the Jasmine 3.x series. We recommend that most users migrate to the - jasmine-browser-runner npm package, which is the direct replacement for the - jasmine gem. See for setup - instructions, including for Rails applications that use either Sprockets or - Webpacker. - - If jasmine-browser-runner doesn't meet your needs, one of these might: - - * The jasmine npm package to run specs in Node.js: - - * The standalone distribution to run specs in browsers with no additional - tools: - * The jasmine-core npm package if all you need is the Jasmine assets: - . This is the direct equivalent of the - jasmine-core Ruby gem. - - To prevent this message from appearing, set the SUPPRESS_JASMINE_DEPRECATION - environment variable. - - END_DEPRECATION_MSG -end - -module Jasmine - module Core - class << self - def path - File.join(File.dirname(__FILE__), "jasmine-core") - end - - def js_files - (["jasmine.js"] + Dir.glob(File.join(path, "*.js"))).map { |f| File.basename(f) }.uniq - boot_files - ["boot0.js", "boot1.js"] - node_boot_files - end - - SPEC_TYPES = ["core", "html", "node"] - - def core_spec_files - spec_files("core") - end - - def html_spec_files - spec_files("html") - end - - def node_spec_files - spec_files("node") - end - - def boot_files - ["boot0.js", "boot1.js"] - end - - def node_boot_files - ["node_boot.js"] - end - - def boot_dir - path - end - - def spec_files(type) - raise ArgumentError.new("Unrecognized spec type") unless SPEC_TYPES.include?(type) - (Dir.glob(File.join(path, "spec", type, "*.js"))).map { |f| File.join("spec", type, File.basename(f)) }.uniq - end - - def css_files - Dir.glob(File.join(path, "*.css")).map { |f| File.basename(f) } - end - - def images_dir - File.join(File.dirname(__FILE__), '../images') - end - - end - end -end diff --git a/lib/jasmine-core/__init__.py b/lib/jasmine-core/__init__.py deleted file mode 100644 index a8d584aa..00000000 --- a/lib/jasmine-core/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .core import Core \ No newline at end of file diff --git a/lib/jasmine-core/boot.js b/lib/jasmine-core/boot.js deleted file mode 100644 index 0fa3379e..00000000 --- a/lib/jasmine-core/boot.js +++ /dev/null @@ -1,167 +0,0 @@ -/* -Copyright (c) 2008-2022 Pivotal Labs - -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. -*/ -/** - - NOTE: This file is deprecated and will be removed in a future release. - Include both boot0.js and boot1.js (in that order) instead. - - Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js` and `jasmine_html.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. - - If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. - - The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. - - [jasmine-gem]: http://github.com/pivotal/jasmine-gem - */ - -(function() { - var jasmineRequire = window.jasmineRequire || require('./jasmine.js'); - - /** - * ## Require & Instantiate - * - * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. - */ - var jasmine = jasmineRequire.core(jasmineRequire), - global = jasmine.getGlobal(); - global.jasmine = jasmine; - - /** - * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. - */ - jasmineRequire.html(jasmine); - - /** - * Create the Jasmine environment. This is used to run all specs in a project. - */ - var env = jasmine.getEnv(); - - /** - * ## The Global Interface - * - * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. - */ - var jasmineInterface = jasmineRequire.interface(jasmine, env); - - /** - * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. - */ - extend(global, jasmineInterface); - - /** - * ## 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. - */ - - var queryString = new jasmine.QueryString({ - getWindowLocation: function() { return window.location; } - }); - - var filterSpecs = !!queryString.getParam("spec"); - - var config = { - stopOnSpecFailure: queryString.getParam("failFast"), - stopSpecOnExpectationFailure: queryString.getParam("oneFailurePerSpec"), - hideDisabled: queryString.getParam("hideDisabled") - }; - - var random = queryString.getParam("random"); - - if (random !== undefined && random !== "") { - config.random = random; - } - - var seed = queryString.getParam("seed"); - if (seed) { - config.seed = seed; - } - - /** - * ## 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). - */ - var htmlReporter = new jasmine.HtmlReporter({ - env: env, - navigateWithNewParam: function(key, value) { return queryString.navigateWithNewParam(key, value); }, - addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); }, - getContainer: function() { 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 - }); - - /** - * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. - */ - env.addReporter(jasmineInterface.jsApiReporter); - env.addReporter(htmlReporter); - - /** - * Filter which specs will be run by matching the start of the full name against the `spec` query param. - */ - var specFilter = new jasmine.HtmlSpecFilter({ - filterString: function() { return queryString.getParam("spec"); } - }); - - config.specFilter = function(spec) { - return specFilter.matches(spec.getFullName()); - }; - - env.configure(config); - - /** - * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. - */ - window.setTimeout = window.setTimeout; - window.setInterval = window.setInterval; - window.clearTimeout = window.clearTimeout; - window.clearInterval = window.clearInterval; - - /** - * ## Execution - * - * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. - */ - var currentWindowOnload = window.onload; - - window.onload = function() { - if (currentWindowOnload) { - currentWindowOnload(); - } - htmlReporter.initialize(); - env.execute(); - }; - - /** - * Helper function for readability above. - */ - function extend(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; - } - - env.deprecated('boot.js is deprecated. Please use boot0.js and boot1.js instead.', - { ignoreRunnable: true }); -}()); diff --git a/lib/jasmine-core/boot/boot.js b/lib/jasmine-core/boot/boot.js deleted file mode 100644 index abed5b84..00000000 --- a/lib/jasmine-core/boot/boot.js +++ /dev/null @@ -1,145 +0,0 @@ -/** - - NOTE: This file is deprecated and will be removed in a future release. - Include both boot0.js and boot1.js (in that order) instead. - - Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js` and `jasmine_html.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. - - If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. - - The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. - - [jasmine-gem]: http://github.com/pivotal/jasmine-gem - */ - -(function() { - var jasmineRequire = window.jasmineRequire || require('./jasmine.js'); - - /** - * ## Require & Instantiate - * - * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. - */ - var jasmine = jasmineRequire.core(jasmineRequire), - global = jasmine.getGlobal(); - global.jasmine = jasmine; - - /** - * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. - */ - jasmineRequire.html(jasmine); - - /** - * Create the Jasmine environment. This is used to run all specs in a project. - */ - var env = jasmine.getEnv(); - - /** - * ## The Global Interface - * - * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. - */ - var jasmineInterface = jasmineRequire.interface(jasmine, env); - - /** - * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. - */ - extend(global, jasmineInterface); - - /** - * ## 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. - */ - - var queryString = new jasmine.QueryString({ - getWindowLocation: function() { return window.location; } - }); - - var filterSpecs = !!queryString.getParam("spec"); - - var config = { - stopOnSpecFailure: queryString.getParam("failFast"), - stopSpecOnExpectationFailure: queryString.getParam("oneFailurePerSpec"), - hideDisabled: queryString.getParam("hideDisabled") - }; - - var random = queryString.getParam("random"); - - if (random !== undefined && random !== "") { - config.random = random; - } - - var seed = queryString.getParam("seed"); - if (seed) { - config.seed = seed; - } - - /** - * ## 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). - */ - var htmlReporter = new jasmine.HtmlReporter({ - env: env, - navigateWithNewParam: function(key, value) { return queryString.navigateWithNewParam(key, value); }, - addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); }, - getContainer: function() { 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 - }); - - /** - * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. - */ - env.addReporter(jasmineInterface.jsApiReporter); - env.addReporter(htmlReporter); - - /** - * Filter which specs will be run by matching the start of the full name against the `spec` query param. - */ - var specFilter = new jasmine.HtmlSpecFilter({ - filterString: function() { return queryString.getParam("spec"); } - }); - - config.specFilter = function(spec) { - return specFilter.matches(spec.getFullName()); - }; - - env.configure(config); - - /** - * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. - */ - window.setTimeout = window.setTimeout; - window.setInterval = window.setInterval; - window.clearTimeout = window.clearTimeout; - window.clearInterval = window.clearInterval; - - /** - * ## Execution - * - * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. - */ - var currentWindowOnload = window.onload; - - window.onload = function() { - if (currentWindowOnload) { - currentWindowOnload(); - } - htmlReporter.initialize(); - env.execute(); - }; - - /** - * Helper function for readability above. - */ - function extend(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; - } - - env.deprecated('boot.js is deprecated. Please use boot0.js and boot1.js instead.', - { ignoreRunnable: true }); -}()); diff --git a/lib/jasmine-core/boot0.js b/lib/jasmine-core/boot0.js index 1f7ffd1d..03186b00 100644 --- a/lib/jasmine-core/boot0.js +++ b/lib/jasmine-core/boot0.js @@ -61,4 +61,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. for (var property in jasmineInterface) { global[property] = jasmineInterface[property]; } -}()); +})(); diff --git a/lib/jasmine-core/boot1.js b/lib/jasmine-core/boot1.js index d5a22151..7980a1bb 100644 --- a/lib/jasmine-core/boot1.js +++ b/lib/jasmine-core/boot1.js @@ -21,7 +21,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** - 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 specs. This file should be loaded after `boot0.js` but before any project source files or spec files are loaded. Thus this file can also be used to @@ -43,24 +43,28 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var queryString = new jasmine.QueryString({ - getWindowLocation: function() { return window.location; } + getWindowLocation: function() { + return window.location; + } }); - var filterSpecs = !!queryString.getParam("spec"); + var filterSpecs = !!queryString.getParam('spec'); var config = { - stopOnSpecFailure: queryString.getParam("failFast"), - stopSpecOnExpectationFailure: queryString.getParam("oneFailurePerSpec"), - hideDisabled: queryString.getParam("hideDisabled") + stopOnSpecFailure: queryString.getParam('stopOnSpecFailure'), + stopSpecOnExpectationFailure: queryString.getParam( + 'stopSpecOnExpectationFailure' + ), + hideDisabled: queryString.getParam('hideDisabled') }; - var random = queryString.getParam("random"); + var random = queryString.getParam('random'); - if (random !== undefined && random !== "") { + if (random !== undefined && random !== '') { config.random = random; } - var seed = queryString.getParam("seed"); + var seed = queryString.getParam('seed'); if (seed) { config.seed = seed; } @@ -71,11 +75,21 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var htmlReporter = new jasmine.HtmlReporter({ env: env, - navigateWithNewParam: function(key, value) { return queryString.navigateWithNewParam(key, value); }, - addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); }, - getContainer: function() { return document.body; }, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); }, + navigateWithNewParam: function(key, value) { + return queryString.navigateWithNewParam(key, value); + }, + addToExistingQueryString: function(key, value) { + return queryString.fullStringWithNewParam(key, value); + }, + getContainer: function() { + 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 }); @@ -90,7 +104,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * Filter which specs will be run by matching the start of the full name against the `spec` query param. */ var specFilter = new jasmine.HtmlSpecFilter({ - filterString: function() { return queryString.getParam("spec"); } + filterString: function() { + return queryString.getParam('spec'); + } }); config.specFilter = function(spec) { @@ -99,14 +115,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. env.configure(config); - /** - * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. - */ - window.setTimeout = window.setTimeout; - window.setInterval = window.setInterval; - window.clearTimeout = window.clearTimeout; - window.clearInterval = window.clearInterval; - /** * ## Execution * @@ -121,13 +129,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. htmlReporter.initialize(); env.execute(); }; - - /** - * Helper function for readability above. - */ - function extend(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; - } - -}()); +})(); diff --git a/lib/jasmine-core/core.py b/lib/jasmine-core/core.py deleted file mode 100644 index 51ef0b30..00000000 --- a/lib/jasmine-core/core.py +++ /dev/null @@ -1,94 +0,0 @@ -import pkg_resources -import os - -if 'SUPPRESS_JASMINE_DEPRECATION' not in os.environ: - print('DEPRECATION WARNING:\n' + - '\n' + - 'The Jasmine packages for Python are deprecated. There will be no further\n' + - 'releases after the end of the Jasmine 3.x series. We recommend migrating to the\n' + - 'following options:\n' + - '\n' + - '* jasmine-browser-runner (,\n' + - ' `npm install jasmine-browser-runner`) to run specs in browsers, including\n' + - ' headless Chrome and Saucelabs. This is the most direct replacement for the\n' + - ' jasmine server` and `jasmine ci` commands provided by the `jasmine` Python\n' + - ' package.\n' + - '* The jasmine npm package (,\n' + - ' `npm install jasmine`) to run specs under Node.js.\n' + - '* The standalone distribution from the latest Jasmine release\n' + - ' to run specs in browsers with\n' + - ' no additional tools.\n' + - '* The jasmine-core npm package (`npm install jasmine-core`) if all you need is\n' + - ' the Jasmine assets. This is the direct equivalent of the jasmine-core Python\n' + - ' package.\n' + - '\n' + - 'Except for the standalone distribution, all of the above are distributed through\n' + - 'npm.\n' + - '\n' + - 'To prevent this message from appearing, set the SUPPRESS_JASMINE_DEPRECATION\n' + - 'environment variable.\n') - - -try: - from collections import OrderedDict -except ImportError: - from ordereddict import OrderedDict - -class Core(object): - @classmethod - def js_package(cls): - return __package__ - - @classmethod - def css_package(cls): - return __package__ - - @classmethod - def image_package(cls): - return __package__ + ".images" - - @classmethod - def js_files(cls): - js_files = sorted(list(filter(lambda x: '.js' in x, pkg_resources.resource_listdir(cls.js_package(), '.')))) - - # jasmine.js needs to be first - js_files.insert(0, 'jasmine.js') - - # Remove the legacy boot file - js_files.remove('boot.js') - - # boot files need to be last - js_files.remove('boot0.js') - js_files.remove('boot1.js') - js_files.append('boot0.js') - js_files.append('boot1.js') - - return cls._uniq(js_files) - - @classmethod - def css_files(cls): - return cls._uniq(sorted(filter(lambda x: '.css' in x, pkg_resources.resource_listdir(cls.css_package(), '.')))) - - @classmethod - def favicon(cls): - return 'jasmine_favicon.png' - - @classmethod - def _uniq(self, items, idfun=None): - # order preserving - - if idfun is None: - def idfun(x): return x - seen = {} - result = [] - for item in items: - marker = idfun(item) - # in old Python versions: - # if seen.has_key(marker) - # but in new ones: - if marker in seen: - continue - - seen[marker] = 1 - result.append(item) - return result diff --git a/lib/jasmine-core/jasmine-html.js b/lib/jasmine-core/jasmine-html.js index 2d55148c..c4d7c8d2 100644 --- a/lib/jasmine-core/jasmine-html.js +++ b/lib/jasmine-core/jasmine-html.js @@ -72,6 +72,12 @@ jasmineRequire.HtmlReporter = function(j$) { } }; + ResultsStateBuilder.prototype.jasmineDone = function(result) { + if (result.failedExpectations) { + this.failureCount += result.failedExpectations.length; + } + }; + function HtmlReporter(options) { var config = function() { return (options.env && options.env.configuration()) || {}; @@ -187,6 +193,7 @@ jasmineRequire.HtmlReporter = function(j$) { }; this.jasmineDone = function(doneResult) { + stateBuilder.jasmineDone(doneResult); var banner = find('.jasmine-banner'); var alert = find('.jasmine-alert'); var order = doneResult && doneResult.order; @@ -303,8 +310,10 @@ jasmineRequire.HtmlReporter = function(j$) { } else { return prefix; } - } else { + } else if (failure.globalErrorType === 'afterAll') { return afterAllMessagePrefix + failure.message; + } else { + return failure.message; } } @@ -434,9 +443,53 @@ jasmineRequire.HtmlReporter = function(j$) { ); } + if (result.debugLogs) { + messages.appendChild(debugLogTable(result.debugLogs)); + } + return failure; } + function debugLogTable(debugLogs) { + var tbody = createDom('tbody'); + + debugLogs.forEach(function(entry) { + tbody.appendChild( + createDom( + 'tr', + {}, + createDom('td', {}, entry.timestamp.toString()), + createDom('td', {}, entry.message) + ) + ); + }); + + return createDom( + 'div', + { className: 'jasmine-debug-log' }, + createDom( + 'div', + { className: 'jasmine-debug-log-header' }, + 'Debug logs' + ), + createDom( + 'table', + {}, + createDom( + 'thead', + {}, + createDom( + 'tr', + {}, + createDom('th', {}, 'Time (ms)'), + createDom('th', {}, 'Message') + ) + ), + tbody + ) + ); + } + function summaryList(resultsTree, domParent) { var specListNode; for (var i = 0; i < resultsTree.children.length; i++) { @@ -571,7 +624,7 @@ jasmineRequire.HtmlReporter = function(j$) { var failFastCheckbox = optionsMenuDom.querySelector('#jasmine-fail-fast'); failFastCheckbox.checked = config.stopOnSpecFailure; failFastCheckbox.onclick = function() { - navigateWithNewParam('failFast', !config.stopOnSpecFailure); + navigateWithNewParam('stopOnSpecFailure', !config.stopOnSpecFailure); }; var throwCheckbox = optionsMenuDom.querySelector( @@ -580,7 +633,7 @@ jasmineRequire.HtmlReporter = function(j$) { throwCheckbox.checked = config.stopSpecOnExpectationFailure; throwCheckbox.onclick = function() { navigateWithNewParam( - 'oneFailurePerSpec', + 'stopSpecOnExpectationFailure', !config.stopSpecOnExpectationFailure ); }; diff --git a/lib/jasmine-core/jasmine.css b/lib/jasmine-core/jasmine.css index 18b6457c..70ab3592 100644 --- a/lib/jasmine-core/jasmine.css +++ b/lib/jasmine-core/jasmine.css @@ -287,4 +287,17 @@ body { display: block; margin-left: 14px; padding: 5px; +} +.jasmine_html-reporter .jasmine-debug-log { + margin: 5px 0 0 0; + padding: 5px; + color: #666; + border: 1px solid #ddd; + background: white; +} +.jasmine_html-reporter .jasmine-debug-log table { + border-spacing: 0; +} +.jasmine_html-reporter .jasmine-debug-log table, .jasmine_html-reporter .jasmine-debug-log th, .jasmine_html-reporter .jasmine-debug-log td { + border: 1px solid #ddd; } \ No newline at end of file diff --git a/lib/jasmine-core/jasmine.js b/lib/jasmine-core/jasmine.js index 4846279a..2f5ee9a4 100644 --- a/lib/jasmine-core/jasmine.js +++ b/lib/jasmine-core/jasmine.js @@ -66,9 +66,6 @@ var getJasmineRequireObj = (function(jasmineGlobal) { j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(j$); j$.Deprecator = jRequire.Deprecator(j$); j$.Env = jRequire.Env(j$); - j$.deprecatingThisProxy = jRequire.deprecatingThisProxy(j$); - j$.deprecatingSuiteProxy = jRequire.deprecatingSuiteProxy(j$); - j$.deprecatingSpecProxy = jRequire.deprecatingSpecProxy(j$); j$.StackTrace = jRequire.StackTrace(j$); j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); j$.ExpectationFilterChain = jRequire.ExpectationFilterChain(); @@ -76,46 +73,22 @@ var getJasmineRequireObj = (function(jasmineGlobal) { j$.Expectation = jRequire.Expectation(j$); j$.buildExpectationResult = jRequire.buildExpectationResult(j$); j$.JsApiReporter = jRequire.JsApiReporter(j$); - j$.asymmetricEqualityTesterArgCompatShim = jRequire.asymmetricEqualityTesterArgCompatShim( - j$ - ); j$.makePrettyPrinter = jRequire.makePrettyPrinter(j$); j$.basicPrettyPrinter_ = j$.makePrettyPrinter(); - Object.defineProperty(j$, 'pp', { - get: function() { - j$.getEnv().deprecated( - 'jasmine.pp is deprecated and will be removed in a future release. ' + - 'Use the pp method of the matchersUtil passed to the matcher factory ' + - "or the asymmetric equality tester's `asymmetricMatch` method " + - 'instead. See ' + - ' for details.' - ); - return j$.basicPrettyPrinter_; - } - }); j$.MatchersUtil = jRequire.MatchersUtil(j$); - var staticMatchersUtil = new j$.MatchersUtil({ - customTesters: [], - pp: j$.basicPrettyPrinter_ - }); - Object.defineProperty(j$, 'matchersUtil', { - get: function() { - j$.getEnv().deprecated( - 'jasmine.matchersUtil is deprecated and will be removed ' + - 'in a future release. Use the instance passed to the matcher factory or ' + - "the asymmetric equality tester's `asymmetricMatch` method instead. " + - 'See for details.' - ); - return staticMatchersUtil; - } - }); - j$.ObjectContaining = jRequire.ObjectContaining(j$); j$.ArrayContaining = jRequire.ArrayContaining(j$); j$.ArrayWithExactContents = jRequire.ArrayWithExactContents(j$); j$.MapContaining = jRequire.MapContaining(j$); j$.SetContaining = jRequire.SetContaining(j$); j$.QueueRunner = jRequire.QueueRunner(j$); + j$.NeverSkipPolicy = jRequire.NeverSkipPolicy(j$); + j$.SkipAfterBeforeAllErrorPolicy = jRequire.SkipAfterBeforeAllErrorPolicy( + j$ + ); + j$.CompleteOnFirstErrorSkipPolicy = jRequire.CompleteOnFirstErrorSkipPolicy( + j$ + ); j$.ReportDispatcher = jRequire.ReportDispatcher(j$); j$.Spec = jRequire.Spec(j$); j$.Spy = jRequire.Spy(j$); @@ -324,25 +297,8 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { if (value instanceof Error) { return true; } - if ( - typeof window !== 'undefined' && - typeof window.trustedTypes !== 'undefined' - ) { - return ( - typeof value.stack === 'string' && typeof value.message === 'string' - ); - } - if (value && value.constructor && value.constructor.constructor) { - var valueGlobal = value.constructor.constructor('return this'); - if (j$.isFunction_(valueGlobal)) { - valueGlobal = valueGlobal(); - } - if (valueGlobal.Error && value instanceof valueGlobal.Error) { - return true; - } - } - return false; + return typeof value.stack === 'string' && typeof value.message === 'string'; }; j$.isAsymmetricEqualityTester_ = function(obj) { @@ -368,7 +324,6 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return ( obj !== null && typeof obj !== 'undefined' && - typeof jasmineGlobal.Map !== 'undefined' && obj.constructor === jasmineGlobal.Map ); }; @@ -377,7 +332,6 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return ( obj !== null && typeof obj !== 'undefined' && - typeof jasmineGlobal.Set !== 'undefined' && obj.constructor === jasmineGlobal.Set ); }; @@ -386,7 +340,6 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return ( obj !== null && typeof obj !== 'undefined' && - typeof jasmineGlobal.WeakMap !== 'undefined' && obj.constructor === jasmineGlobal.WeakMap ); }; @@ -395,26 +348,24 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return ( obj !== null && typeof obj !== 'undefined' && - typeof jasmineGlobal.URL !== 'undefined' && obj.constructor === jasmineGlobal.URL ); }; + j$.isIterable_ = function(value) { + return value && !!value[Symbol.iterator]; + }; + j$.isDataView = function(obj) { return ( obj !== null && typeof obj !== 'undefined' && - typeof jasmineGlobal.DataView !== 'undefined' && obj.constructor === jasmineGlobal.DataView ); }; j$.isPromise = function(obj) { - return ( - typeof jasmineGlobal.Promise !== 'undefined' && - !!obj && - obj.constructor === jasmineGlobal.Promise - ); + return !!obj && obj.constructor === jasmineGlobal.Promise; }; j$.isPromiseLike = function(obj) { @@ -435,7 +386,6 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { j$.isPending_ = function(promise) { var sentinel = {}; - // eslint-disable-next-line compat/compat return Promise.race([promise, Promise.resolve(sentinel)]).then( function(result) { return result === sentinel; @@ -616,6 +566,22 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { putativeSpy.calls instanceof j$.CallTracker ); }; + + /** + * Logs a message for use in debugging. If the spec fails, trace messages + * will be included in the {@link SpecResult|result} passed to the + * reporter's specDone method. + * + * This method should be called only when a spec (including any associated + * beforeEach or afterEach functions) is running. + * @function + * @name jasmine.debugLog + * @since 4.0.0 + * @param {String} msg - The message to log + */ + j$.debugLog = function(msg) { + j$.getEnv().debugLog(msg); + }; }; getJasmineRequireObj().util = function(j$) { @@ -710,20 +676,10 @@ getJasmineRequireObj().util = function(j$) { }; util.errorWithStack = function errorWithStack() { - // Don't throw and catch if we don't have to, because it makes it harder - // for users to debug their code with exception breakpoints. - var error = new Error(); - - if (error.stack) { - return error; - } - - // But some browsers (e.g. Phantom) only provide a stack trace if we throw. - try { - throw new Error(); - } catch (e) { - return e; - } + // Don't throw and catch. That makes it harder for users to debug their + // code with exception breakpoints, and it's unnecessary since all + // supported environments populate new Error().stack + return new Error(); }; function callerFile() { @@ -747,21 +703,6 @@ getJasmineRequireObj().util = function(j$) { StopIteration.prototype = Object.create(Error.prototype); StopIteration.prototype.constructor = StopIteration; - // useful for maps and sets since `forEach` is the only IE11-compatible way to iterate them - util.forEachBreakable = function(iterable, iteratee) { - function breakLoop() { - throw new StopIteration(); - } - - try { - iterable.forEach(function(value, key) { - iteratee(breakLoop, value, key, iterable); - }); - } catch (error) { - if (!(error instanceof StopIteration)) throw error; - } - }; - util.validateTimeout = function(timeout, msgPrefix) { // Timeouts are implemented with setTimeout, which only supports a limited // range of values. The limit is unspecified, as is the behavior when it's @@ -827,7 +768,7 @@ getJasmineRequireObj().Spec = function(j$) { }; this.expectationResultFactory = attrs.expectationResultFactory || function() {}; - this.deprecated = attrs.deprecated || function() {}; + this.onLateError = attrs.onLateError || function() {}; this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; this.catchingExceptions = attrs.catchingExceptions || @@ -853,8 +794,9 @@ getJasmineRequireObj().Spec = function(j$) { * @property {String} status - Once the spec has completed, this string represents the pass/fail status of this spec. * @property {number} duration - The time in ms used by the spec execution, including any before/afterEach. * @property {Object} properties - User-supplied properties, if any, that were set using {@link Env#setSpecProperty} + * @property {DebugLogEntry[]|null} debugLogs - Messages, if any, that were logged using {@link jasmine.debugLog} during a failing spec. * @since 2.0.0 -x */ + */ this.result = { id: this.id, description: this.description, @@ -864,7 +806,8 @@ x */ deprecationWarnings: [], pendingReason: '', duration: null, - properties: null + properties: null, + debugLogs: null }; } @@ -911,17 +854,21 @@ x */ } self.result.status = self.status(excluded, failSpecWithNoExp); self.result.duration = self.timer.elapsed(); + + if (self.result.status !== 'failed') { + self.result.debugLogs = null; + } + self.resultCallback(self.result, done); - } + }, + type: 'specCleanup' }; var fns = this.beforeAndAfterFns(); - var regularFns = fns.befores.concat(this.queueableFn); var runnerConfig = { isLeaf: true, - queueableFns: regularFns, - cleanupFns: fns.afters, + queueableFns: [...fns.befores, this.queueableFn, ...fns.afters], onException: function() { self.onException.apply(self, arguments); }, @@ -929,17 +876,13 @@ x */ // Issue a deprecation. Include the context ourselves and pass // ignoreRunnable: true, since getting here always means that we've already // moved on and the current runnable isn't the one that caused the problem. - self.deprecated( - "An asynchronous function called its 'done' " + - 'callback more than once. This is a bug in the spec, beforeAll, ' + - 'beforeEach, afterAll, or afterEach function in question. This will ' + - 'be treated as an error in a future version. See' + - ' ' + - 'for more information.\n' + - '(in spec: ' + - self.getFullName() + - ')', - { ignoreRunnable: true } + self.onLateError( + new Error( + 'An asynchronous spec, beforeEach, or afterEach function called its ' + + "'done' callback more than once.\n(in spec: " + + self.getFullName() + + ')' + ) ); }, onComplete: function() { @@ -955,30 +898,15 @@ x */ if (this.markedPending || excluded === true) { runnerConfig.queueableFns = []; - runnerConfig.cleanupFns = []; } runnerConfig.queueableFns.unshift(onStart); - runnerConfig.cleanupFns.push(complete); + runnerConfig.queueableFns.push(complete); this.queueRunnerFactory(runnerConfig); }; Spec.prototype.reset = function() { - /** - * @typedef SpecResult - * @property {Int} id - The unique id of this spec. - * @property {String} description - The description passed to the {@link it} that created this spec. - * @property {String} fullName - The full description including all ancestors of this spec. - * @property {Expectation[]} failedExpectations - The list of expectations that failed during execution of this spec. - * @property {Expectation[]} passedExpectations - The list of expectations that passed during execution of this spec. - * @property {Expectation[]} deprecationWarnings - The list of deprecation warnings that occurred during execution this spec. - * @property {String} pendingReason - If the spec is {@link pending}, this will be the reason. - * @property {String} status - Once the spec has completed, this string represents the pass/fail status of this spec. - * @property {number} duration - The time in ms used by the spec execution, including any before/afterEach. - * @property {Object} properties - User-supplied properties, if any, that were set using {@link Env#setSpecProperty} - * @since 2.0.0 - */ this.result = { id: this.id, description: this.description, @@ -989,7 +917,7 @@ x */ pendingReason: this.excludeMessage, duration: null, properties: null, - trace: null + debugLogs: null }; this.markedPending = this.markedExcluding; }; @@ -1088,6 +1016,23 @@ x */ ); }; + Spec.prototype.debugLog = function(msg) { + if (!this.result.debugLogs) { + this.result.debugLogs = []; + } + + /** + * @typedef DebugLogEntry + * @property {String} message - The message that was passed to {@link jasmine.debugLog}. + * @property {number} timestamp - The time when the entry was added, in + * milliseconds from the spec's start time + */ + this.result.debugLogs.push({ + message: msg, + timestamp: this.timer.elapsed() + }); + }; + var extractCustomPendingMessage = function(e) { var fullMessage = e.toString(), boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), @@ -1107,14 +1052,47 @@ x */ ); }; + /** + * @interface Spec + * @see Configuration#specFilter + */ + Object.defineProperty(Spec.prototype, 'metadata', { + get: function() { + if (!this.metadata_) { + this.metadata_ = { + /** + * The unique ID of this spec. + * @name Spec#id + * @readonly + * @type {string} + */ + id: this.id, + + /** + * The description passed to the {@link it} that created this spec. + * @name Spec#description + * @readonly + * @type {string} + */ + description: this.description, + + /** + * The full description including all ancestors of this spec. + * @name Spec#getFullName + * @function + * @returns {string} + */ + getFullName: this.getFullName.bind(this) + }; + } + + return this.metadata_; + } + }); + return Spec; }; -if (typeof window == void 0 && typeof exports == 'object') { - /* globals exports */ - exports.Spec = jasmineRequire.Spec; -} - /*jshint bitwise: false*/ getJasmineRequireObj().Order = function() { @@ -1175,7 +1153,6 @@ getJasmineRequireObj().Env = function(j$) { var self = this; var global = options.global || j$.getGlobal(); - var customPromise; var totalSpecsDefined = 0; @@ -1222,15 +1199,6 @@ getJasmineRequireObj().Env = function(j$) { * @default null */ seed: null, - /** - * Whether to stop execution of the suite after the first spec failure - * @name Configuration#failFast - * @since 3.3.0 - * @type Boolean - * @default false - * @deprecated Use the `stopOnSpecFailure` config property instead. - */ - failFast: false, /** * Whether to stop execution of the suite after the first spec failure * @name Configuration#stopOnSpecFailure @@ -1249,15 +1217,6 @@ getJasmineRequireObj().Env = function(j$) { * @default false */ failSpecWithNoExpectations: false, - /** - * Whether to cause specs to only have one expectation failure. - * @name Configuration#oneFailurePerSpec - * @since 3.3.0 - * @type Boolean - * @default false - * @deprecated Use the `stopSpecOnExpectationFailure` config property instead. - */ - oneFailurePerSpec: false, /** * Whether to cause specs to only have one expectation failure. * @name Configuration#stopSpecOnExpectationFailure @@ -1292,18 +1251,6 @@ getJasmineRequireObj().Env = function(j$) { * @default false */ hideDisabled: false, - /** - * Set to provide a custom promise library that Jasmine will use if it needs - * to create a promise. If not set, it will default to whatever global Promise - * library is available (if any). - * @name Configuration#Promise - * @since 3.5.0 - * @type function - * @default undefined - * @deprecated In a future version, Jasmine will ignore the Promise config - * property and always create native promises instead. - */ - Promise: undefined, /** * Clean closures when a suite is done running (done by clearing the stored function reference). * This prevents memory leaks, but you won't be able to run jasmine multiple times. @@ -1378,6 +1325,8 @@ getJasmineRequireObj().Env = function(j$) { 'random', 'failSpecWithNoExpectations', 'hideDisabled', + 'stopOnSpecFailure', + 'stopSpecOnExpectationFailure', 'autoCleanClosures' ]; @@ -1387,70 +1336,6 @@ getJasmineRequireObj().Env = function(j$) { } }); - if (typeof configuration.failFast !== 'undefined') { - // We can't unconditionally issue a warning here because then users who - // get the configuration from Jasmine, modify it, and pass it back would - // see the warning. - if (configuration.failFast !== config.failFast) { - this.deprecated( - 'The `failFast` config property is deprecated and will be removed ' + - 'in a future version of Jasmine. Please use `stopOnSpecFailure` ' + - 'instead.', - { ignoreRunnable: true } - ); - } - - if (typeof configuration.stopOnSpecFailure !== 'undefined') { - if (configuration.stopOnSpecFailure !== configuration.failFast) { - throw new Error( - 'stopOnSpecFailure and failFast are aliases for ' + - "each other. Don't set failFast if you also set stopOnSpecFailure." - ); - } - } - - config.failFast = configuration.failFast; - config.stopOnSpecFailure = configuration.failFast; - } else if (typeof configuration.stopOnSpecFailure !== 'undefined') { - config.failFast = configuration.stopOnSpecFailure; - config.stopOnSpecFailure = configuration.stopOnSpecFailure; - } - - if (typeof configuration.oneFailurePerSpec !== 'undefined') { - // We can't unconditionally issue a warning here because then users who - // get the configuration from Jasmine, modify it, and pass it back would - // see the warning. - if (configuration.oneFailurePerSpec !== config.oneFailurePerSpec) { - this.deprecated( - 'The `oneFailurePerSpec` config property is deprecated and will be ' + - 'removed in a future version of Jasmine. Please use ' + - '`stopSpecOnExpectationFailure` instead.', - { ignoreRunnable: true } - ); - } - - if (typeof configuration.stopSpecOnExpectationFailure !== 'undefined') { - if ( - configuration.stopSpecOnExpectationFailure !== - configuration.oneFailurePerSpec - ) { - throw new Error( - 'stopSpecOnExpectationFailure and oneFailurePerSpec are aliases for ' + - "each other. Don't set oneFailurePerSpec if you also set stopSpecOnExpectationFailure." - ); - } - } - - config.oneFailurePerSpec = configuration.oneFailurePerSpec; - config.stopSpecOnExpectationFailure = configuration.oneFailurePerSpec; - } else if ( - typeof configuration.stopSpecOnExpectationFailure !== 'undefined' - ) { - config.oneFailurePerSpec = configuration.stopSpecOnExpectationFailure; - config.stopSpecOnExpectationFailure = - configuration.stopSpecOnExpectationFailure; - } - if (configuration.specFilter) { config.specFilter = configuration.specFilter; } @@ -1459,27 +1344,6 @@ getJasmineRequireObj().Env = function(j$) { config.seed = configuration.seed; } - // Don't use hasOwnProperty to check for Promise existence because Promise - // can be initialized to undefined, either explicitly or by using the - // object returned from Env#configuration. In particular, Karma does this. - if (configuration.Promise) { - if ( - typeof configuration.Promise.resolve === 'function' && - typeof configuration.Promise.reject === 'function' - ) { - customPromise = configuration.Promise; - self.deprecated( - 'The `Promise` config property is deprecated. Future versions ' + - 'of Jasmine will create native promises even if the `Promise` ' + - 'config property is set. Please remove it.' - ); - } else { - throw new Error( - 'Custom promise library missing `resolve`/`reject` functions' - ); - } - } - if (configuration.hasOwnProperty('verboseDeprecations')) { config.verboseDeprecations = configuration.verboseDeprecations; deprecator.verboseDeprecations(config.verboseDeprecations); @@ -1501,27 +1365,6 @@ getJasmineRequireObj().Env = function(j$) { return result; }; - Object.defineProperty(this, 'specFilter', { - get: function() { - self.deprecated( - 'Getting specFilter directly from Env is deprecated and will be ' + - 'removed in a future version of Jasmine. Please check the ' + - 'specFilter option from `configuration` instead.', - { ignoreRunnable: true } - ); - return config.specFilter; - }, - set: function(val) { - self.deprecated( - 'Setting specFilter directly on Env is deprecated and will be ' + - 'removed in a future version of Jasmine. Please use the ' + - 'specFilter option in `configure` instead.', - { ignoreRunnable: true } - ); - config.specFilter = val; - } - }); - this.setDefaultSpyStrategy = function(defaultStrategyFn) { if (!currentRunnable()) { throw new Error( @@ -1563,17 +1406,6 @@ getJasmineRequireObj().Env = function(j$) { runnableResources[currentRunnable().id].customMatchers; for (var matcherName in matchersToAdd) { - if (matchersToAdd[matcherName].length > 1) { - self.deprecated( - 'The matcher factory for "' + - matcherName + - '" ' + - 'accepts custom equality testers, but this parameter will no longer be ' + - 'passed in a future release. ' + - 'See for details.' - ); - } - customMatchers[matcherName] = matchersToAdd[matcherName]; } }; @@ -1588,17 +1420,6 @@ getJasmineRequireObj().Env = function(j$) { runnableResources[currentRunnable().id].customAsyncMatchers; for (var matcherName in matchersToAdd) { - if (matchersToAdd[matcherName].length > 1) { - self.deprecated( - 'The matcher factory for "' + - matcherName + - '" ' + - 'accepts custom equality testers, but this parameter will no longer be ' + - 'passed in a future release. ' + - 'See for details.' - ); - } - customAsyncMatchers[matcherName] = matchersToAdd[matcherName]; } }; @@ -1635,21 +1456,23 @@ getJasmineRequireObj().Env = function(j$) { }; var makeMatchersUtil = function() { - var customEqualityTesters = - runnableResources[currentRunnable().id].customEqualityTesters; - return new j$.MatchersUtil({ - customTesters: customEqualityTesters, - pp: makePrettyPrinter() - }); + const cr = currentRunnable(); + + if (cr) { + const customEqualityTesters = + runnableResources[cr.id].customEqualityTesters; + return new j$.MatchersUtil({ + customTesters: customEqualityTesters, + pp: makePrettyPrinter() + }); + } else { + return new j$.MatchersUtil({ pp: j$.basicPrettyPrinter_ }); + } }; var expectationFactory = function(actual, spec) { - var customEqualityTesters = - runnableResources[spec.id].customEqualityTesters; - return j$.Expectation.factory({ matchersUtil: makeMatchersUtil(), - customEqualityTesters: customEqualityTesters, customMatchers: runnableResources[spec.id].customMatchers, actual: actual, addExpectationResult: addExpectationResult @@ -1660,6 +1483,18 @@ getJasmineRequireObj().Env = function(j$) { } }; + function recordLateError(error) { + const result = expectationResultFactory({ + error, + passed: false, + matcherName: '', + expected: '', + actual: '' + }); + result.globalErrorType = 'lateError'; + topSuite.result.failedExpectations.push(result); + } + function recordLateExpectation(runable, runableType, result) { var delayedExpectationResult = {}; Object.keys(result).forEach(function(k) { @@ -1691,7 +1526,6 @@ getJasmineRequireObj().Env = function(j$) { var asyncExpectationFactory = function(actual, spec, runableType) { return j$.Expectation.asyncFactory({ matchersUtil: makeMatchersUtil(), - customEqualityTesters: runnableResources[spec.id].customEqualityTesters, customAsyncMatchers: runnableResources[spec.id].customAsyncMatchers, actual: actual, addExpectationResult: addExpectationResult @@ -1736,6 +1570,9 @@ getJasmineRequireObj().Env = function(j$) { resources.customObjectFormatters = j$.util.clone( runnableResources[parentRunnableId].customObjectFormatters ); + resources.customSpyStrategies = j$.util.clone( + runnableResources[parentRunnableId].customSpyStrategies + ); resources.defaultStrategyFn = runnableResources[parentRunnableId].defaultStrategyFn; } @@ -1788,138 +1625,6 @@ getJasmineRequireObj().Env = function(j$) { return buildExpectationResult(attrs); }; - /** - * Sets whether Jasmine should throw an Error when an expectation fails. - * This causes a spec to only have one expectation failure. - * @name Env#throwOnExpectationFailure - * @since 2.3.0 - * @function - * @param {Boolean} value Whether to throw when a expectation fails - * @deprecated Use the `stopSpecOnExpectationFailure` option with {@link Env#configure} - */ - this.throwOnExpectationFailure = function(value) { - this.deprecated( - 'Setting throwOnExpectationFailure directly on Env is deprecated and ' + - 'will be removed in a future version of Jasmine. Please use the ' + - 'stopSpecOnExpectationFailure option in `configure`.', - { ignoreRunnable: true } - ); - this.configure({ oneFailurePerSpec: !!value }); - }; - - this.throwingExpectationFailures = function() { - this.deprecated( - 'Getting throwingExpectationFailures directly from Env is deprecated ' + - 'and will be removed in a future version of Jasmine. Please check ' + - 'the stopSpecOnExpectationFailure option from `configuration`.', - { ignoreRunnable: true } - ); - return config.oneFailurePerSpec; - }; - - /** - * Set whether to stop suite execution when a spec fails - * @name Env#stopOnSpecFailure - * @since 2.7.0 - * @function - * @param {Boolean} value Whether to stop suite execution when a spec fails - * @deprecated Use the `stopOnSpecFailure` option with {@link Env#configure} - */ - this.stopOnSpecFailure = function(value) { - this.deprecated( - 'Setting stopOnSpecFailure directly is deprecated and will be ' + - 'removed in a future version of Jasmine. Please use the ' + - 'stopOnSpecFailure option in `configure`.', - { ignoreRunnable: true } - ); - this.configure({ stopOnSpecFailure: !!value }); - }; - - this.stoppingOnSpecFailure = function() { - this.deprecated( - 'Getting stoppingOnSpecFailure directly from Env is deprecated and ' + - 'will be removed in a future version of Jasmine. Please check the ' + - 'stopOnSpecFailure option from `configuration`.', - { ignoreRunnable: true } - ); - return config.failFast; - }; - - /** - * Set whether to randomize test execution order - * @name Env#randomizeTests - * @since 2.4.0 - * @function - * @param {Boolean} value Whether to randomize execution order - * @deprecated Use the `random` option with {@link Env#configure} - */ - this.randomizeTests = function(value) { - this.deprecated( - 'Setting randomizeTests directly is deprecated and will be removed ' + - 'in a future version of Jasmine. Please use the random option in ' + - '`configure` instead.', - { ignoreRunnable: true } - ); - config.random = !!value; - }; - - this.randomTests = function() { - this.deprecated( - 'Getting randomTests directly from Env is deprecated and will be ' + - 'removed in a future version of Jasmine. Please check the random ' + - 'option from `configuration` instead.', - { ignoreRunnable: true } - ); - return config.random; - }; - - /** - * Set the random number seed for spec randomization - * @name Env#seed - * @since 2.4.0 - * @function - * @param {Number} value The seed value - * @deprecated Use the `seed` option with {@link Env#configure} - */ - this.seed = function(value) { - this.deprecated( - 'Setting seed directly is deprecated and will be removed in a ' + - 'future version of Jasmine. Please use the seed option in ' + - '`configure` instead.', - { ignoreRunnable: true } - ); - if (value) { - config.seed = value; - } - return config.seed; - }; - - this.hidingDisabled = function(value) { - this.deprecated( - 'Getting hidingDisabled directly from Env is deprecated and will ' + - 'be removed in a future version of Jasmine. Please check the ' + - 'hideDisabled option from `configuration` instead.', - { ignoreRunnable: true } - ); - return config.hideDisabled; - }; - - /** - * @name Env#hideDisabled - * @since 3.2.0 - * @function - * @deprecated Use the `hideDisabled` option with {@link Env#configure} - */ - this.hideDisabled = function(value) { - this.deprecated( - 'Setting hideDisabled directly is deprecated and will be removed ' + - 'in a future version of Jasmine. Please use the hideDisabled option ' + - 'in `configure` instead.', - { ignoreRunnable: true } - ); - config.hideDisabled = !!value; - }; - /** * Causes a deprecation warning to be logged to the console and reported to * reporters. @@ -1948,12 +1653,21 @@ getJasmineRequireObj().Env = function(j$) { }; var queueRunnerFactory = function(options, args) { - var failFast = false; if (options.isLeaf) { - failFast = config.stopSpecOnExpectationFailure; - } else if (!options.isReporter) { - failFast = config.stopOnSpecFailure; + // A spec + options.SkipPolicy = j$.CompleteOnFirstErrorSkipPolicy; + } else if (options.isReporter) { + // A reporter queue + options.SkipPolicy = j$.NeverSkipPolicy; + } else { + // A suite + if (config.stopOnSpecFailure) { + options.SkipPolicy = j$.CompleteOnFirstErrorSkipPolicy; + } else { + options.SkipPolicy = j$.SkipAfterBeforeAllErrorPolicy; + } } + options.clearStack = options.clearStack || clearStack; options.timeout = { setTimeout: realSetTimeout, @@ -1961,7 +1675,6 @@ getJasmineRequireObj().Env = function(j$) { }; options.fail = self.fail; options.globalErrors = globalErrors; - options.completeOnFirstError = failFast; options.onException = options.onException || function(e) { @@ -1973,13 +1686,13 @@ getJasmineRequireObj().Env = function(j$) { }; var topSuite = new j$.Suite({ - env: this, id: getNextSuiteId(), description: 'Jasmine__TopLevel__Suite', expectationFactory: expectationFactory, asyncExpectationFactory: suiteAsyncExpectationFactory, expectationResultFactory: expectationResultFactory, - autoCleanClosures: config.autoCleanClosures + autoCleanClosures: config.autoCleanClosures, + onLateError: recordLateError }); var deprecator = new j$.Deprecator(topSuite); currentDeclarationSuite = topSuite; @@ -1993,7 +1706,7 @@ getJasmineRequireObj().Env = function(j$) { * @since 2.0.0 */ this.topSuite = function() { - return j$.deprecatingSuiteProxy(topSuite, null, this); + return topSuite.metadata; }; /** @@ -2069,7 +1782,7 @@ getJasmineRequireObj().Env = function(j$) { 'specDone' ], queueRunnerFactory, - self.deprecated + recordLateError ); /** @@ -2083,21 +1796,25 @@ getJasmineRequireObj().Env = function(j$) { * * Both parameters are optional, but a completion callback is only valid as * the second parameter. To specify a completion callback but not a list of - * specs/suites to run, pass null or undefined as the first parameter. + * specs/suites to run, pass null or undefined as the first parameter. The + * completion callback is supported for backward compatibility. In most + * cases it will be more convenient to use the returned promise instead. * - * execute should not be called more than once. + * execute should not be called more than once unless the env has been + * configured with `{autoCleanClosures: false}`. * - * If the environment supports promises, execute will return a promise that - * is resolved after the suite finishes executing. The promise will be - * resolved (not rejected) as long as the suite runs to completion. Use a - * {@link Reporter} to determine whether or not the suite passed. + * execute returns a promise. The promise will be resolved to the same + * {@link JasmineDoneInfo|overall result} that's passed to a reporter's + * `jasmineDone` method, even if the suite did not pass. To determine + * whether the suite passed, check the value that the promise resolves to + * or use a {@link Reporter}. * * @name Env#execute * @since 2.0.0 * @function * @param {(string[])=} runnablesToRun IDs of suites and/or specs to run * @param {Function=} onComplete Function that will be called after all specs have run - * @return {Promise} + * @return {Promise} */ this.execute = function(runnablesToRun, onComplete) { if (this._executedBefore) { @@ -2143,7 +1860,14 @@ getJasmineRequireObj().Env = function(j$) { hasFailures = true; } suite.endTimer(); - reporter.suiteDone(result, next); + + if (suite.hadBeforeAllFailure) { + reportChildrenOfBeforeAllFailure(suite).then(function() { + reporter.suiteDone(result, next); + }); + } else { + reporter.suiteDone(result, next); + } }, orderChildren: function(node) { return order.sort(node.children); @@ -2162,25 +1886,15 @@ getJasmineRequireObj().Env = function(j$) { var jasmineTimer = new j$.Timer(); jasmineTimer.start(); - var Promise = customPromise || global.Promise; - - if (Promise) { - return new Promise(function(resolve) { - runAll(function() { - if (onComplete) { - onComplete(); - } - - resolve(); - }); - }); - } else { - runAll(function() { + return new Promise(function(resolve) { + runAll(function(jasmineDoneInfo) { if (onComplete) { onComplete(); } + + resolve(jasmineDoneInfo); }); - } + }); function runAll(done) { /** @@ -2199,51 +1913,98 @@ getJasmineRequireObj().Env = function(j$) { currentlyExecutingSuites.push(topSuite); processor.execute(function() { - clearResourcesForRunnable(topSuite.id); - currentlyExecutingSuites.pop(); - var overallStatus, incompleteReason; + (async function() { + if (topSuite.hadBeforeAllFailure) { + await reportChildrenOfBeforeAllFailure(topSuite); + } - if ( - hasFailures || - topSuite.result.failedExpectations.length > 0 - ) { - overallStatus = 'failed'; - } else if (focusedRunnables.length > 0) { - overallStatus = 'incomplete'; - incompleteReason = 'fit() or fdescribe() was found'; - } else if (totalSpecsDefined === 0) { - overallStatus = 'incomplete'; - incompleteReason = 'No specs found'; - } else { - overallStatus = 'passed'; - } + clearResourcesForRunnable(topSuite.id); + currentlyExecutingSuites.pop(); + var overallStatus, incompleteReason; - /** - * Information passed to the {@link Reporter#jasmineDone} event. - * @typedef JasmineDoneInfo - * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. - * @property {Int} totalTime - The total time (in ms) that it took to execute the suite - * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. - * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. - * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. - * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. - * @since 2.4.0 - */ - reporter.jasmineDone( - { + if ( + hasFailures || + topSuite.result.failedExpectations.length > 0 + ) { + overallStatus = 'failed'; + } else if (focusedRunnables.length > 0) { + overallStatus = 'incomplete'; + incompleteReason = 'fit() or fdescribe() was found'; + } else if (totalSpecsDefined === 0) { + overallStatus = 'incomplete'; + incompleteReason = 'No specs found'; + } else { + overallStatus = 'passed'; + } + + /** + * Information passed to the {@link Reporter#jasmineDone} event. + * @typedef JasmineDoneInfo + * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. + * @property {Int} totalTime - The total time (in ms) that it took to execute the suite + * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. + * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. + * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. + * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. + * @since 2.4.0 + */ + const jasmineDoneInfo = { overallStatus: overallStatus, totalTime: jasmineTimer.elapsed(), incompleteReason: incompleteReason, order: order, failedExpectations: topSuite.result.failedExpectations, deprecationWarnings: topSuite.result.deprecationWarnings - }, - done - ); + }; + reporter.jasmineDone(jasmineDoneInfo, function() { + done(jasmineDoneInfo); + }); + })(); }); } ); } + + async function reportChildrenOfBeforeAllFailure(suite) { + for (const child of suite.children) { + if (child instanceof j$.Suite) { + await new Promise(function(resolve) { + reporter.suiteStarted(child.result, resolve); + }); + await reportChildrenOfBeforeAllFailure(child); + + // Marking the suite passed is consistent with how suites that + // contain failed specs but no suite-level failures are reported. + child.result.status = 'passed'; + + await new Promise(function(resolve) { + reporter.suiteDone(child.result, resolve); + }); + } else { + /* a spec */ + await new Promise(function(resolve) { + reporter.specStarted(child.result, resolve); + }); + + child.addExpectationResult( + false, + { + passed: false, + message: + 'Not run because a beforeAll function failed. The ' + + 'beforeAll failure will be reported on the suite that ' + + 'caused it.' + }, + true + ); + child.result.status = 'failed'; + + await new Promise(function(resolve) { + reporter.specDone(child.result, resolve); + }); + } + } + } }; /** @@ -2299,9 +2060,7 @@ getJasmineRequireObj().Env = function(j$) { return undefined; }, - function getPromise() { - return customPromise || global.Promise; - } + makeMatchersUtil ); var spyRegistry = new j$.SpyRegistry({ @@ -2383,7 +2142,6 @@ getJasmineRequireObj().Env = function(j$) { var suiteFactory = function(description) { var suite = new j$.Suite({ - env: self, id: getNextSuiteId(), description: description, parentSuite: currentDeclarationSuite, @@ -2391,8 +2149,9 @@ getJasmineRequireObj().Env = function(j$) { expectationFactory: expectationFactory, asyncExpectationFactory: suiteAsyncExpectationFactory, expectationResultFactory: expectationResultFactory, - throwOnExpectationFailure: config.oneFailurePerSpec, - autoCleanClosures: config.autoCleanClosures + throwOnExpectationFailure: config.stopSpecOnExpectationFailure, + autoCleanClosures: config.autoCleanClosures, + onLateError: recordLateError }); return suite; @@ -2410,13 +2169,9 @@ getJasmineRequireObj().Env = function(j$) { } addSpecsToSuite(suite, specDefinitions); if (suite.parentSuite && !suite.children.length) { - this.deprecated( - 'describe with no children (describe() or it()) is ' + - 'deprecated and will be removed in a future version of Jasmine. ' + - 'Please either remove the describe or add children to it.' - ); + throw new Error('describe with no children (describe() or it())'); } - return j$.deprecatingSuiteProxy(suite, suite.parentSuite, this); + return suite.metadata; }; this.xdescribe = function(description, specDefinitions) { @@ -2425,7 +2180,7 @@ getJasmineRequireObj().Env = function(j$) { var suite = suiteFactory(description); suite.exclude(); addSpecsToSuite(suite, specDefinitions); - return j$.deprecatingSuiteProxy(suite, suite.parentSuite, this); + return suite.metadata; }; var focusedRunnables = []; @@ -2440,7 +2195,7 @@ getJasmineRequireObj().Env = function(j$) { unfocusAncestor(); addSpecsToSuite(suite, specDefinitions); - return j$.deprecatingSuiteProxy(suite, suite.parentSuite, this); + return suite.metadata; }; function addSpecsToSuite(suite, specDefinitions) { @@ -2450,7 +2205,7 @@ getJasmineRequireObj().Env = function(j$) { var declarationError = null; try { - specDefinitions.call(j$.deprecatingThisProxy(suite, self)); + specDefinitions(); } catch (e) { declarationError = e; } @@ -2492,7 +2247,7 @@ getJasmineRequireObj().Env = function(j$) { beforeAndAfterFns: beforeAndAfterFns(suite), expectationFactory: expectationFactory, asyncExpectationFactory: specAsyncExpectationFactory, - deprecated: self.deprecated, + onLateError: recordLateError, resultCallback: specResultCallback, getSpecName: function(spec) { return getSpecName(spec, suite); @@ -2508,7 +2263,7 @@ getJasmineRequireObj().Env = function(j$) { fn: fn, timeout: timeout || 0 }, - throwOnExpectationFailure: config.oneFailurePerSpec, + throwOnExpectationFailure: config.stopSpecOnExpectationFailure, autoCleanClosures: config.autoCleanClosures, timer: new j$.Timer() }); @@ -2554,8 +2309,8 @@ getJasmineRequireObj().Env = function(j$) { }; this.it = function(description, fn, timeout) { - var spec = this.it_(description, fn, timeout); - return j$.deprecatingSpecProxy(spec, this); + const spec = this.it_(description, fn, timeout); + return spec.metadata; }; this.xit = function(description, fn, timeout) { @@ -2567,7 +2322,7 @@ getJasmineRequireObj().Env = function(j$) { } var spec = this.it_.apply(this, arguments); spec.exclude('Temporarily disabled with xit'); - return j$.deprecatingSpecProxy(spec, this); + return spec.metadata; }; this.fit = function(description, fn, timeout) { @@ -2581,7 +2336,7 @@ getJasmineRequireObj().Env = function(j$) { currentDeclarationSuite.addChild(spec); focusedRunnables.push(spec.id); unfocusAncestor(); - return j$.deprecatingSpecProxy(spec, this); + return spec.metadata; }; /** @@ -2618,6 +2373,16 @@ getJasmineRequireObj().Env = function(j$) { currentSuite().setSuiteProperty(key, value); }; + this.debugLog = function(msg) { + var maybeSpec = currentRunnable(); + + if (!maybeSpec || !maybeSpec.debugLog) { + throw new Error("'debugLog' was called when there was no current spec"); + } + + maybeSpec.debugLog(msg); + }; + this.expect = function(actual) { if (!currentRunnable()) { throw new Error( @@ -2732,7 +2497,7 @@ getJasmineRequireObj().Env = function(j$) { error: error && error.message ? error : null }); - if (config.oneFailurePerSpec) { + if (config.stopSpecOnExpectationFailure) { throw new Error(message); } }; @@ -3070,27 +2835,26 @@ getJasmineRequireObj().MapContaining = function(j$) { MapContaining.prototype.asymmetricMatch = function(other, matchersUtil) { if (!j$.isMap(other)) return false; - var hasAllMatches = true; - j$.util.forEachBreakable(this.sample, function(breakLoop, value, key) { + for (const [key, value] of this.sample) { // for each key/value pair in `sample` // there should be at least one pair in `other` whose key and value both match var hasMatch = false; - j$.util.forEachBreakable(other, function(oBreakLoop, oValue, oKey) { + for (const [oKey, oValue] of other) { if ( matchersUtil.equals(oKey, key) && matchersUtil.equals(oValue, value) ) { hasMatch = true; - oBreakLoop(); + break; } - }); - if (!hasMatch) { - hasAllMatches = false; - breakLoop(); } - }); - return hasAllMatches; + if (!hasMatch) { + return false; + } + } + + return true; }; MapContaining.prototype.jasmineToString = function(pp) { @@ -3131,18 +2895,6 @@ getJasmineRequireObj().ObjectContaining = function(j$) { this.sample = sample; } - function getPrototype(obj) { - if (Object.getPrototypeOf) { - return Object.getPrototypeOf(obj); - } - - if (obj.constructor.prototype == obj) { - return null; - } - - return obj.constructor.prototype; - } - function hasProperty(obj, property) { if (!obj || typeof obj !== 'object') { return false; @@ -3152,7 +2904,7 @@ getJasmineRequireObj().ObjectContaining = function(j$) { return true; } - return hasProperty(getPrototype(obj), property); + return hasProperty(Object.getPrototypeOf(obj), property); } ObjectContaining.prototype.asymmetricMatch = function(other, matchersUtil) { @@ -3222,25 +2974,24 @@ getJasmineRequireObj().SetContaining = function(j$) { SetContaining.prototype.asymmetricMatch = function(other, matchersUtil) { if (!j$.isSet(other)) return false; - var hasAllMatches = true; - j$.util.forEachBreakable(this.sample, function(breakLoop, item) { + for (const item of this.sample) { // for each item in `sample` there should be at least one matching item in `other` // (not using `matchersUtil.contains` because it compares set members by reference, // not by deep value equality) var hasMatch = false; - j$.util.forEachBreakable(other, function(oBreakLoop, oItem) { + for (const oItem of other) { if (matchersUtil.equals(oItem, item)) { hasMatch = true; - oBreakLoop(); + break; } - }); - if (!hasMatch) { - hasAllMatches = false; - breakLoop(); } - }); - return hasAllMatches; + if (!hasMatch) { + return false; + } + } + + return true; }; SetContaining.prototype.jasmineToString = function(pp) { @@ -3309,129 +3060,6 @@ getJasmineRequireObj().Truthy = function(j$) { return Truthy; }; -getJasmineRequireObj().asymmetricEqualityTesterArgCompatShim = function(j$) { - /* - Older versions of Jasmine passed an array of custom equality testers as the - second argument to each asymmetric equality tester's `asymmetricMatch` - method. Newer versions will pass a `MatchersUtil` instance. The - asymmetricEqualityTesterArgCompatShim allows for a graceful migration from - the old interface to the new by "being" both an array of custom equality - testers and a `MatchersUtil` at the same time. - - This code should be removed in the next major release. - */ - - var likelyArrayProps = [ - 'concat', - 'constructor', - 'copyWithin', - 'entries', - 'every', - 'fill', - 'filter', - 'find', - 'findIndex', - 'flat', - 'flatMap', - 'forEach', - 'includes', - 'indexOf', - 'join', - 'keys', - 'lastIndexOf', - 'length', - 'map', - 'pop', - 'push', - 'reduce', - 'reduceRight', - 'reverse', - 'shift', - 'slice', - 'some', - 'sort', - 'splice', - 'toLocaleString', - 'toSource', - 'toString', - 'unshift', - 'values' - ]; - - function asymmetricEqualityTesterArgCompatShim( - matchersUtil, - customEqualityTesters - ) { - var self = Object.create(matchersUtil); - - copyAndDeprecate(self, customEqualityTesters, 'length'); - - for (i = 0; i < customEqualityTesters.length; i++) { - copyAndDeprecate(self, customEqualityTesters, i); - } - - // Avoid copying array props if we've previously done so, - // to avoid triggering our own deprecation warnings. - if (!self.isAsymmetricEqualityTesterArgCompatShim_) { - copyAndDeprecateArrayMethods(self); - } - - self.isAsymmetricEqualityTesterArgCompatShim_ = true; - return self; - } - - function copyAndDeprecateArrayMethods(dest) { - var props = arrayProps(), - i, - k; - - for (i = 0; i < props.length; i++) { - k = props[i]; - - // Skip length (dealt with above), and anything that collides with - // MatchesUtil e.g. an Array.prototype.contains method added by user code - if (k !== 'length' && !dest[k]) { - copyAndDeprecate(dest, Array.prototype, k); - } - } - } - - function copyAndDeprecate(dest, src, propName) { - Object.defineProperty(dest, propName, { - get: function() { - j$.getEnv().deprecated( - 'The second argument to asymmetricMatch is now a ' + - 'MatchersUtil. Using it as an array of custom equality testers is ' + - 'deprecated and will stop working in a future release. ' + - 'See for details.' - ); - return src[propName]; - } - }); - } - - function arrayProps() { - var props, a, k; - - if (!Object.getOwnPropertyDescriptors) { - return likelyArrayProps.filter(function(k) { - return Array.prototype.hasOwnProperty(k); - }); - } - - props = Object.getOwnPropertyDescriptors(Array.prototype); // eslint-disable-line compat/compat - a = []; - - for (k in props) { - a.push(k); - } - - return a; - } - - return asymmetricEqualityTesterArgCompatShim; -}; - getJasmineRequireObj().CallTracker = function(j$) { /** * @namespace Spy#calls @@ -3871,6 +3499,58 @@ getJasmineRequireObj().Clock = function() { return Clock; }; +getJasmineRequireObj().CompleteOnFirstErrorSkipPolicy = function(j$) { + function CompleteOnFirstErrorSkipPolicy(queueableFns) { + this.queueableFns_ = queueableFns; + this.erroredFnIx_ = null; + } + + CompleteOnFirstErrorSkipPolicy.prototype.skipTo = function(lastRanFnIx) { + let i; + + for ( + i = lastRanFnIx + 1; + i < this.queueableFns_.length && this.shouldSkip_(i); + i++ + ) {} + return i; + }; + + CompleteOnFirstErrorSkipPolicy.prototype.fnErrored = function(fnIx) { + this.erroredFnIx_ = fnIx; + }; + + CompleteOnFirstErrorSkipPolicy.prototype.shouldSkip_ = function(fnIx) { + if (this.erroredFnIx_ === null) { + return false; + } + + const fn = this.queueableFns_[fnIx]; + const candidateSuite = fn.suite; + const errorSuite = this.queueableFns_[this.erroredFnIx_].suite; + const wasCleanupFn = + fn.type === 'afterEach' || + fn.type === 'afterAll' || + fn.type === 'specCleanup'; + return ( + !wasCleanupFn || + (candidateSuite && isDescendent(candidateSuite, errorSuite)) + ); + }; + + function isDescendent(candidate, ancestor) { + if (!candidate.parentSuite) { + return false; + } else if (candidate.parentSuite === ancestor) { + return true; + } else { + return isDescendent(candidate.parentSuite, ancestor); + } + } + + return CompleteOnFirstErrorSkipPolicy; +}; + getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { function DelayedFunctionScheduler() { var self = this; @@ -3879,31 +3559,12 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { var currentTime = 0; var delayedFnCount = 0; var deletedKeys = []; - var ticking = false; self.tick = function(millis, tickDate) { - if (ticking) { - j$.getEnv().deprecated( - 'The behavior of reentrant calls to jasmine.clock().tick() will ' + - 'change in a future version. Either modify the affected spec to ' + - 'not call tick() from within a setTimeout or setInterval handler, ' + - 'or be aware that it may behave differently in the future. See ' + - ' ' + - 'for details.' - ); - } + millis = millis || 0; + var endTime = currentTime + millis; - ticking = true; - - try { - millis = millis || 0; - var endTime = currentTime + millis; - - runScheduledFunctions(endTime, tickDate); - currentTime = endTime; - } finally { - ticking = false; - } + runScheduledFunctions(endTime, tickDate); }; self.scheduleFunction = function( @@ -4021,16 +3682,20 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { function runScheduledFunctions(endTime, tickDate) { tickDate = tickDate || function() {}; if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) { - tickDate(endTime - currentTime); + if (endTime >= currentTime) { + tickDate(endTime - currentTime); + currentTime = endTime; + } return; } do { deletedKeys = []; var newCurrentTime = scheduledLookup.shift(); - tickDate(newCurrentTime - currentTime); - - currentTime = newCurrentTime; + if (newCurrentTime >= currentTime) { + tickDate(newCurrentTime - currentTime); + currentTime = newCurrentTime; + } var funcsToRun = scheduledFunctions[currentTime]; @@ -4059,8 +3724,9 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { ); // ran out of functions to call, but still time left on the clock - if (currentTime !== endTime) { + if (endTime >= currentTime) { tickDate(endTime - currentTime); + currentTime = endTime; } } } @@ -4068,211 +3734,6 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { return DelayedFunctionScheduler; }; -/* eslint-disable compat/compat */ -// TODO: Remove this in the next major release. -getJasmineRequireObj().deprecatingSpecProxy = function(j$) { - function isMember(target, prop) { - return ( - Object.keys(target).indexOf(prop) !== -1 || - Object.keys(j$.Spec.prototype).indexOf(prop) !== -1 - ); - } - - function isAllowedMember(prop) { - return prop === 'id' || prop === 'description' || prop === 'getFullName'; - } - - function msg(member) { - var memberName = member.toString().replace(/^Symbol\((.+)\)$/, '$1'); - return ( - 'Access to private Spec members (in this case `' + - memberName + - '`) is not supported and will break in ' + - 'a future release. See ' + - 'for correct usage.' - ); - } - - try { - new Proxy({}, {}); - } catch (e) { - // Environment does not support Poxy. - return function(spec) { - return spec; - }; - } - - function DeprecatingSpecProxyHandler(env) { - this._env = env; - } - - DeprecatingSpecProxyHandler.prototype.get = function(target, prop, receiver) { - this._maybeDeprecate(target, prop); - - if (prop === 'getFullName') { - // getFullName calls a private method. Re-bind 'this' to avoid a bogus - // deprecation warning. - return target.getFullName.bind(target); - } else { - return target[prop]; - } - }; - - DeprecatingSpecProxyHandler.prototype.set = function(target, prop, value) { - this._maybeDeprecate(target, prop); - return (target[prop] = value); - }; - - DeprecatingSpecProxyHandler.prototype._maybeDeprecate = function( - target, - prop - ) { - if (isMember(target, prop) && !isAllowedMember(prop)) { - this._env.deprecated(msg(prop)); - } - }; - - function deprecatingSpecProxy(spec, env) { - return new Proxy(spec, new DeprecatingSpecProxyHandler(env)); - } - - return deprecatingSpecProxy; -}; - -/* eslint-disable compat/compat */ -// TODO: Remove this in the next major release. -getJasmineRequireObj().deprecatingSuiteProxy = function(j$) { - var allowedMembers = [ - 'id', - 'children', - 'description', - 'parentSuite', - 'getFullName' - ]; - - function isMember(target, prop) { - return ( - Object.keys(target).indexOf(prop) !== -1 || - Object.keys(j$.Suite.prototype).indexOf(prop) !== -1 - ); - } - - function isAllowedMember(prop) { - return allowedMembers.indexOf(prop) !== -1; - } - - function msg(member) { - var memberName = member.toString().replace(/^Symbol\((.+)\)$/, '$1'); - return ( - 'Access to private Suite members (in this case `' + - memberName + - '`) is not supported and will break in ' + - 'a future release. See ' + - 'for correct usage.' - ); - } - try { - new Proxy({}, {}); - } catch (e) { - // Environment does not support Poxy. - return function(suite) { - return suite; - }; - } - - function DeprecatingSuiteProxyHandler(parentSuite, env) { - this._parentSuite = parentSuite; - this._env = env; - } - - DeprecatingSuiteProxyHandler.prototype.get = function( - target, - prop, - receiver - ) { - if (prop === 'children') { - if (!this._children) { - this._children = target.children.map( - this._proxyForChild.bind(this, receiver) - ); - } - - return this._children; - } else if (prop === 'parentSuite') { - return this._parentSuite; - } else { - this._maybeDeprecate(target, prop); - return target[prop]; - } - }; - - DeprecatingSuiteProxyHandler.prototype.set = function(target, prop, value) { - this._maybeDeprecate(target, prop); - return (target[prop] = value); - }; - - DeprecatingSuiteProxyHandler.prototype._maybeDeprecate = function( - target, - prop - ) { - if (isMember(target, prop) && !isAllowedMember(prop)) { - this._env.deprecated(msg(prop)); - } - }; - - DeprecatingSuiteProxyHandler.prototype._proxyForChild = function( - ownProxy, - child - ) { - if (child.children) { - return deprecatingSuiteProxy(child, ownProxy, this._env); - } else { - return j$.deprecatingSpecProxy(child, this._env); - } - }; - - function deprecatingSuiteProxy(suite, parentSuite, env) { - return new Proxy(suite, new DeprecatingSuiteProxyHandler(parentSuite, env)); - } - - return deprecatingSuiteProxy; -}; - -/* eslint-disable compat/compat */ -// TODO: Remove this in the next major release. -getJasmineRequireObj().deprecatingThisProxy = function(j$) { - var msg = - "Access to 'this' in describe functions (and in arrow functions " + - 'inside describe functions) is deprecated.'; - - try { - new Proxy({}, {}); - } catch (e) { - // Environment does not support Poxy. - return function(suite) { - return suite; - }; - } - - function DeprecatingThisProxyHandler(env) { - this._env = env; - } - - DeprecatingThisProxyHandler.prototype.get = function(target, prop, receiver) { - this._env.deprecated(msg); - return target[prop]; - }; - - DeprecatingThisProxyHandler.prototype.set = function(target, prop, value) { - this._env.deprecated(msg); - return (target[prop] = value); - }; - - return function(suite, env) { - return new Proxy(suite, new DeprecatingThisProxyHandler(env)); - }; -}; - getJasmineRequireObj().Deprecator = function(j$) { function Deprecator(topSuite) { this.topSuite_ = topSuite; @@ -4415,7 +3876,7 @@ getJasmineRequireObj().ExceptionFormatter = function(j$) { return message; }; - this.stack = function(error) { + this.stack = function(error, { omitMessage } = {}) { if (!error || !error.stack) { return null; } @@ -4424,7 +3885,7 @@ getJasmineRequireObj().ExceptionFormatter = function(j$) { var lines = filterJasmine(stackTrace); var result = ''; - if (stackTrace.message) { + if (stackTrace.message && !omitMessage) { lines.unshift(stackTrace.message); } @@ -4554,15 +4015,8 @@ getJasmineRequireObj().Expectation = function(j$) { * @namespace async-matchers */ function AsyncExpectation(options) { - var global = options.global || j$.getGlobal(); this.expector = new j$.Expector(options); - if (!global.Promise) { - throw new Error( - 'expectAsync is unavailable because the environment does not support promises.' - ); - } - var customAsyncMatchers = options.customAsyncMatchers || {}; for (var matcherName in customAsyncMatchers) { this[matcherName] = wrapAsyncCompare( @@ -4817,6 +4271,9 @@ getJasmineRequireObj().buildExpectationResult = function(j$) { * @property {Boolean} passed - Whether the expectation passed or failed. * @property {Object} expected - If the expectation failed, what was the expected value. * @property {Object} actual - If the expectation failed, what actual value was produced. + * @property {String|undefined} globalErrorType - The type of an error that + * is reported on the top suite. Valid values are undefined, "afterAll", + * "load", "lateExpectation", and "lateError". */ var result = { matcherName: options.matcherName, @@ -4878,7 +4335,9 @@ getJasmineRequireObj().buildExpectationResult = function(j$) { } } } - return stackFormatter(error); + // Omit the message from the stack trace because it will be + // included elsewhere. + return stackFormatter(error, { omitMessage: true }); } } @@ -4890,7 +4349,6 @@ getJasmineRequireObj().Expector = function(j$) { this.matchersUtil = options.matchersUtil || { buildFailureMessage: function() {} }; - this.customEqualityTesters = options.customEqualityTesters || []; this.actual = options.actual; this.addExpectationResult = options.addExpectationResult || function() {}; this.filters = new j$.ExpectationFilterChain(); @@ -4907,14 +4365,7 @@ getJasmineRequireObj().Expector = function(j$) { this.args.unshift(this.actual); - // TODO: Remove support for passing customEqualityTesters in the next major release. - var matcher; - - if (matcherFactory.length >= 2) { - matcher = matcherFactory(this.matchersUtil, this.customEqualityTesters); - } else { - matcher = matcherFactory(this.matchersUtil); - } + var matcher = matcherFactory(this.matchersUtil); var comparisonFunc = this.filters.selectComparisonFunc(matcher); return comparisonFunc || matcher.compare; @@ -5132,7 +4583,6 @@ getJasmineRequireObj().GlobalErrors = function(j$) { return GlobalErrors; }; -/* eslint-disable compat/compat */ getJasmineRequireObj().toBePending = function(j$) { /** * Expect a promise to be pending, i.e. the promise is neither resolved nor rejected. @@ -5630,41 +5080,48 @@ getJasmineRequireObj().MatchersUtil = function(j$) { * @since 2.0.0 * @param {*} haystack The collection to search * @param {*} needle The value to search for - * @param [customTesters] An array of custom equality testers. Deprecated. - * As of 3.6 this parameter no longer needs to be passed. It will be removed in 4.0. * @returns {boolean} True if `needle` was found in `haystack` */ - MatchersUtil.prototype.contains = function(haystack, needle, customTesters) { - if (customTesters) { - j$.getEnv().deprecated( - 'Passing custom equality testers ' + - 'to MatchersUtil#contains is deprecated. ' + - 'See for details.' - ); - } - - if (j$.isSet(haystack)) { - return haystack.has(needle); - } - - if ( - Object.prototype.toString.apply(haystack) === '[object Array]' || - (!!haystack && !haystack.indexOf) - ) { - for (var i = 0; i < haystack.length; i++) { - try { - this.suppressDeprecation_ = true; - if (this.equals(haystack[i], needle, customTesters)) { - return true; - } - } finally { - this.suppressDeprecation_ = false; - } - } + MatchersUtil.prototype.contains = function(haystack, needle) { + if (!haystack) { return false; } - return !!haystack && haystack.indexOf(needle) >= 0; + if (j$.isSet(haystack)) { + // Try .has() first. It should be faster in cases where + // needle === something in haystack. Fall back to .equals() comparison + // if that fails. + if (haystack.has(needle)) { + return true; + } + } + + if (j$.isIterable_(haystack) && !j$.isString_(haystack)) { + // Arrays, Sets, etc. + for (const candidate of haystack) { + if (this.equals(candidate, needle)) { + return true; + } + } + + return false; + } + + if (haystack.indexOf) { + // Mainly strings + return haystack.indexOf(needle) >= 0; + } + + if (j$.isNumber_(haystack.length)) { + // Objects that are shaped like arrays but aren't iterable + for (var i = 0; i < haystack.length; i++) { + if (this.equals(haystack[i], needle)) { + return true; + } + } + } + + return false; }; MatchersUtil.prototype.buildFailureMessage = function() { @@ -5701,19 +5158,11 @@ getJasmineRequireObj().MatchersUtil = function(j$) { b, aStack, bStack, - customTesters, diffBuilder ) { if (j$.isFunction_(b.valuesForDiff_)) { var values = b.valuesForDiff_(a, this.pp); - this.eq_( - values.other, - values.self, - aStack, - bStack, - customTesters, - diffBuilder - ); + this.eq_(values.other, values.self, aStack, bStack, diffBuilder); } else { diffBuilder.recordMismatch(); } @@ -5724,22 +5173,18 @@ getJasmineRequireObj().MatchersUtil = function(j$) { b, aStack, bStack, - customTesters, diffBuilder ) { var asymmetricA = j$.isAsymmetricEqualityTester_(a), asymmetricB = j$.isAsymmetricEqualityTester_(b), - shim, result; if (asymmetricA === asymmetricB) { return undefined; } - shim = j$.asymmetricEqualityTesterArgCompatShim(this, customTesters); - if (asymmetricA) { - result = a.asymmetricMatch(b, shim); + result = a.asymmetricMatch(b, this); if (!result) { diffBuilder.recordMismatch(); } @@ -5747,9 +5192,9 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } if (asymmetricB) { - result = b.asymmetricMatch(a, shim); + result = b.asymmetricMatch(a, this); if (!result) { - this.asymmetricDiff_(a, b, aStack, bStack, customTesters, diffBuilder); + this.asymmetricDiff_(a, b, aStack, bStack, diffBuilder); } return result; } @@ -5762,58 +5207,18 @@ getJasmineRequireObj().MatchersUtil = function(j$) { * @since 2.0.0 * @param {*} a The first value to compare * @param {*} b The second value to compare - * @param [customTesters] An array of custom equality testers. Deprecated. - * As of 3.6 this parameter no longer needs to be passed. It will be removed in 4.0. * @returns {boolean} True if the values are equal */ - MatchersUtil.prototype.equals = function( - a, - b, - customTestersOrDiffBuilder, - diffBuilderOrNothing - ) { - var customTesters, diffBuilder; - - if (isDiffBuilder(customTestersOrDiffBuilder)) { - diffBuilder = customTestersOrDiffBuilder; - } else { - if (customTestersOrDiffBuilder && !this.suppressDeprecation_) { - j$.getEnv().deprecated( - 'Passing custom equality testers ' + - 'to MatchersUtil#equals is deprecated. ' + - 'See for details.' - ); - } - - if (diffBuilderOrNothing) { - j$.getEnv().deprecated( - 'Diff builder should be passed ' + - 'as the third argument to MatchersUtil#equals, not the fourth. ' + - 'See for details.' - ); - } - - customTesters = customTestersOrDiffBuilder; - diffBuilder = diffBuilderOrNothing; - } - - customTesters = customTesters || this.customTesters_; + MatchersUtil.prototype.equals = function(a, b, diffBuilder) { diffBuilder = diffBuilder || j$.NullDiffBuilder(); diffBuilder.setRoots(a, b); - return this.eq_(a, b, [], [], customTesters, diffBuilder); + return this.eq_(a, b, [], [], diffBuilder); }; // Equality function lovingly adapted from isEqual in // [Underscore](http://underscorejs.org) - MatchersUtil.prototype.eq_ = function( - a, - b, - aStack, - bStack, - customTesters, - diffBuilder - ) { + MatchersUtil.prototype.eq_ = function(a, b, aStack, bStack, diffBuilder) { var result = true, self = this, i; @@ -5823,15 +5228,14 @@ getJasmineRequireObj().MatchersUtil = function(j$) { b, aStack, bStack, - customTesters, diffBuilder ); if (!j$.util.isUndefined(asymmetricResult)) { return asymmetricResult; } - for (i = 0; i < customTesters.length; i++) { - var customTesterResult = customTesters[i](a, b); + for (i = 0; i < this.customTesters_.length; i++) { + var customTesterResult = this.customTesters_[i](a, b); if (!j$.util.isUndefined(customTesterResult)) { if (!customTesterResult) { diffBuilder.recordMismatch(); @@ -5903,11 +5307,10 @@ getJasmineRequireObj().MatchersUtil = function(j$) { // If we have an instance of ArrayBuffer the Uint8Array ctor // will be defined as well return self.eq_( - new Uint8Array(a), // eslint-disable-line compat/compat - new Uint8Array(b), // eslint-disable-line compat/compat + new Uint8Array(a), + new Uint8Array(b), aStack, bStack, - customTesters, diffBuilder ); // RegExps are compared by their source patterns and flags. @@ -5986,7 +5389,6 @@ getJasmineRequireObj().MatchersUtil = function(j$) { i < bLength ? b[i] : void 0, aStack, bStack, - customTesters, diffBuilder ) && result; } @@ -6031,14 +5433,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { if ( j$.isAsymmetricEqualityTester_(mapKey) || (j$.isAsymmetricEqualityTester_(cmpKey) && - this.eq_( - mapKey, - cmpKey, - aStack, - bStack, - customTesters, - j$.NullDiffBuilder() - )) + this.eq_(mapKey, cmpKey, aStack, bStack, j$.NullDiffBuilder())) ) { mapValueB = b.get(cmpKey); } else { @@ -6049,7 +5444,6 @@ getJasmineRequireObj().MatchersUtil = function(j$) { mapValueB, aStack, bStack, - customTesters, j$.NullDiffBuilder() ); } @@ -6100,7 +5494,6 @@ getJasmineRequireObj().MatchersUtil = function(j$) { otherValue, baseStack, otherStack, - customTesters, j$.NullDiffBuilder() ); if (!found && prevStackSize !== baseStack.length) { @@ -6165,9 +5558,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } diffBuilder.withPath(key, function() { - if ( - !self.eq_(a[key], b[key], aStack, bStack, customTesters, diffBuilder) - ) { + if (!self.eq_(a[key], b[key], aStack, bStack, diffBuilder)) { result = false; } }); @@ -6279,10 +5670,6 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return formatted; } - function isDiffBuilder(obj) { - return obj && typeof obj.recordMismatch === 'function'; - } - return MatchersUtil; }; @@ -7526,7 +6913,7 @@ getJasmineRequireObj().toHaveSize = function(j$) { }; } - var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // eslint-disable-line compat/compat + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; function isLength(value) { return ( typeof value == 'number' && @@ -7957,10 +7344,9 @@ getJasmineRequireObj().MockDate = function(j$) { currentTime = mockDate.getTime(); } else { if (!j$.util.isUndefined(mockDate)) { - j$.getEnv().deprecated( + throw new Error( 'The argument to jasmine.clock().mockDate(), if specified, ' + - 'should be a Date instance. Passing anything other than a Date ' + - 'will be treated as an error in a future release.' + 'should be a Date instance.' ); } @@ -8035,11 +7421,7 @@ getJasmineRequireObj().MockDate = function(j$) { FakeDate.prototype = GlobalDate.prototype; FakeDate.now = function() { - if (GlobalDate.now) { - return currentTime; - } else { - throw new Error('Browser does not support Date.now()'); - } + return currentTime; }; FakeDate.toSource = GlobalDate.toSource; @@ -8052,6 +7434,18 @@ getJasmineRequireObj().MockDate = function(j$) { return MockDate; }; +getJasmineRequireObj().NeverSkipPolicy = function(j$) { + function NeverSkipPolicy(queueableFns) {} + + NeverSkipPolicy.prototype.skipTo = function(lastRanFnIx) { + return lastRanFnIx + 1; + }; + + NeverSkipPolicy.prototype.fnErrored = function(fnIx) {}; + + return NeverSkipPolicy; +}; + getJasmineRequireObj().makePrettyPrinter = function(j$) { function SinglePrettyPrintRun(customObjectFormatters, pp) { this.customObjectFormatters_ = customObjectFormatters; @@ -8495,9 +7889,7 @@ getJasmineRequireObj().QueueRunner = function(j$) { function QueueRunner(attrs) { this.id_ = nextid++; - var queueableFns = attrs.queueableFns || []; - this.queueableFns = queueableFns.concat(attrs.cleanupFns || []); - this.firstCleanupIx = queueableFns.length; + this.queueableFns = attrs.queueableFns || []; this.onComplete = attrs.onComplete || emptyFn; this.clearStack = attrs.clearStack || @@ -8516,8 +7908,10 @@ getJasmineRequireObj().QueueRunner = function(j$) { pushListener: emptyFn, popListener: emptyFn }; - this.completeOnFirstError = !!attrs.completeOnFirstError; - this.errored = false; + + const SkipPolicy = attrs.SkipPolicy || j$.NeverSkipPolicy; + this.skipPolicy_ = new SkipPolicy(this.queueableFns); + this.errored_ = false; if (typeof this.onComplete !== 'function') { throw new Error('invalid onComplete ' + JSON.stringify(this.onComplete)); @@ -8537,14 +7931,6 @@ getJasmineRequireObj().QueueRunner = function(j$) { this.run(0); }; - QueueRunner.prototype.skipToCleanup = function(lastRanIndex) { - if (lastRanIndex < this.firstCleanupIx) { - this.run(this.firstCleanupIx); - } else { - this.run(lastRanIndex + 1); - } - }; - QueueRunner.prototype.clearTimeout = function(timeoutId) { Function.prototype.apply.apply(this.timeout.clearTimeout, [ j$.getGlobal(), @@ -8577,25 +7963,15 @@ getJasmineRequireObj().QueueRunner = function(j$) { function next(err) { cleanup(); - if (j$.isError_(err)) { + if (typeof err !== 'undefined') { if (!(err instanceof StopExecutionError) && !err.jasmineMessage) { self.fail(err); } - self.errored = errored = true; - } else if (typeof err !== 'undefined' && !self.errored) { - self.deprecated( - 'Any argument passed to a done callback will be treated as an ' + - 'error in a future release. Call the done callback without ' + - "arguments if you don't want to trigger a spec failure." - ); + self.recordError_(iterativeIndex); } function runNext() { - if (self.completeOnFirstError && errored) { - self.skipToCleanup(iterativeIndex); - } else { - self.run(iterativeIndex + 1); - } + self.run(self.nextFnIx_(iterativeIndex)); } if (completedSynchronously) { @@ -8617,7 +7993,6 @@ getJasmineRequireObj().QueueRunner = function(j$) { } } ), - errored = false, timedOut = false, queueableFn = self.queueableFns[iterativeIndex], timeoutId, @@ -8625,7 +8000,7 @@ getJasmineRequireObj().QueueRunner = function(j$) { next.fail = function nextFail() { self.fail.apply(null, arguments); - self.errored = errored = true; + self.recordError_(iterativeIndex); next(); }; @@ -8668,15 +8043,15 @@ getJasmineRequireObj().QueueRunner = function(j$) { } } catch (e) { onException(e); - self.errored = errored = true; + self.recordError_(iterativeIndex); } cleanup(); - return { completedSynchronously: true, errored: errored }; + return { completedSynchronously: true }; function onException(e) { self.onException(e); - self.errored = errored = true; + self.recordError_(iterativeIndex); } function onPromiseRejection(e) { @@ -8693,26 +8068,19 @@ getJasmineRequireObj().QueueRunner = function(j$) { for ( iterativeIndex = recursiveIndex; iterativeIndex < length; - iterativeIndex++ + iterativeIndex = this.nextFnIx_(iterativeIndex) ) { var result = this.attempt(iterativeIndex); if (!result.completedSynchronously) { return; } - - self.errored = self.errored || result.errored; - - if (this.completeOnFirstError && result.errored) { - this.skipToCleanup(iterativeIndex); - return; - } } this.clearStack(function() { self.globalErrors.popListener(self.handleFinalError); - if (self.errored) { + if (self.errored_) { self.onComplete(new StopExecutionError()); } else { self.onComplete(); @@ -8720,6 +8088,21 @@ getJasmineRequireObj().QueueRunner = function(j$) { }); }; + QueueRunner.prototype.nextFnIx_ = function(currentFnIx) { + const result = this.skipPolicy_.skipTo(currentFnIx); + + if (result === currentFnIx) { + throw new Error("Can't skip to the same queueable fn that just finished"); + } + + return result; + }; + + QueueRunner.prototype.recordError_ = function(currentFnIx) { + this.errored_ = true; + this.skipPolicy_.fnErrored(currentFnIx); + }; + QueueRunner.prototype.diagnoseConflictingAsync_ = function(fn, retval) { var msg; @@ -8728,19 +8111,19 @@ getJasmineRequireObj().QueueRunner = function(j$) { // Omit the stack trace because there's almost certainly no user code // on the stack at this point. if (j$.isAsyncFunction_(fn)) { - msg = + this.onException( 'An asynchronous before/it/after ' + - 'function was defined with the async keyword but also took a ' + - 'done callback. This is not supported and will stop working in' + - ' the future. Either remove the done callback (recommended) or ' + - 'remove the async keyword.'; + 'function was defined with the async keyword but also took a ' + + 'done callback. Either remove the done callback (recommended) or ' + + 'remove the async keyword.' + ); } else { - msg = + this.onException( 'An asynchronous before/it/after ' + - 'function took a done callback but also returned a promise. ' + - 'This is not supported and will stop working in the future. ' + - 'Either remove the done callback (recommended) or change the ' + - 'function to not return a promise.'; + 'function took a done callback but also returned a promise. ' + + 'Either remove the done callback (recommended) or change the ' + + 'function to not return a promise.' + ); } this.deprecated(msg, { omitStackTrace: true }); @@ -8751,7 +8134,7 @@ getJasmineRequireObj().QueueRunner = function(j$) { }; getJasmineRequireObj().ReportDispatcher = function(j$) { - function ReportDispatcher(methods, queueRunnerFactory, deprecated) { + function ReportDispatcher(methods, queueRunnerFactory, onLateError) { var dispatchedMethods = methods || []; for (var i = 0; i < dispatchedMethods.length; i++) { @@ -8797,14 +8180,11 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { onComplete: onComplete, isReporter: true, onMultipleDone: function() { - deprecated( - "An asynchronous reporter callback called its 'done' callback " + - 'more than once. This is a bug in the reporter callback in ' + - 'question. This will be treated as an error in a future ' + - 'version. See' + - ' ' + - 'for more information.', - { ignoreRunnable: true } + onLateError( + new Error( + "An asynchronous reporter callback called its 'done' callback " + + 'more than once.' + ) ); } }); @@ -9267,6 +8647,45 @@ getJasmineRequireObj().interface = function(jasmine, env) { return jasmineInterface; }; +getJasmineRequireObj().SkipAfterBeforeAllErrorPolicy = function(j$) { + function SkipAfterBeforeAllErrorPolicy(queueableFns) { + this.queueableFns_ = queueableFns; + this.skipping_ = false; + } + + SkipAfterBeforeAllErrorPolicy.prototype.skipTo = function(lastRanFnIx) { + if (this.skipping_) { + return this.nextAfterAllAfter_(lastRanFnIx); + } else { + return lastRanFnIx + 1; + } + }; + + SkipAfterBeforeAllErrorPolicy.prototype.nextAfterAllAfter_ = function(i) { + for ( + i++; + i < this.queueableFns_.length && + this.queueableFns_[i].type !== 'afterAll'; + i++ + ) {} + return i; + }; + + SkipAfterBeforeAllErrorPolicy.prototype.fnErrored = function(fnIx) { + if (this.queueableFns_[fnIx].type === 'beforeAll') { + this.skipping_ = true; + // Failures need to be reported for each contained spec. But we can't do + // that from here because reporting is async. This function isn't async + // (and can't be without greatly complicating QueueRunner). Mark the + // failure so that the code that reports the suite result (which is + // already async) can detect the failure and report the specs. + this.queueableFns_[fnIx].suite.hadBeforeAllFailure = true; + } + }; + + return SkipAfterBeforeAllErrorPolicy; +}; + getJasmineRequireObj().Spy = function(j$) { var nextOrder = (function() { var order = 0; @@ -9276,11 +8695,6 @@ getJasmineRequireObj().Spy = function(j$) { }; })(); - var matchersUtil = new j$.MatchersUtil({ - customTesters: [], - pp: j$.makePrettyPrinter() - }); - /** * @classdesc _Note:_ Do not construct this directly. Use {@link spyOn}, * {@link spyOnProperty}, {@link jasmine.createSpy}, or @@ -9288,26 +8702,24 @@ getJasmineRequireObj().Spy = function(j$) { * @class Spy * @hideconstructor */ - function Spy( - name, - originalFn, - customStrategies, - defaultStrategyFn, - getPromise - ) { + function Spy(name, matchersUtil, optionals) { + const { originalFn, customStrategies, defaultStrategyFn } = optionals || {}; + var numArgs = typeof originalFn === 'function' ? originalFn.length : 0, wrapper = makeFunc(numArgs, function(context, args, invokeNew) { return spy(context, args, invokeNew); }), - strategyDispatcher = new SpyStrategyDispatcher({ - name: name, - fn: originalFn, - getSpy: function() { - return wrapper; + strategyDispatcher = new SpyStrategyDispatcher( + { + name: name, + fn: originalFn, + getSpy: function() { + return wrapper; + }, + customStrategies: customStrategies }, - customStrategies: customStrategies, - getPromise: getPromise - }), + matchersUtil + ), callTracker = new j$.CallTracker(), spy = function(context, args, invokeNew) { /** @@ -9419,11 +8831,11 @@ getJasmineRequireObj().Spy = function(j$) { return wrapper; } - function SpyStrategyDispatcher(strategyArgs) { + function SpyStrategyDispatcher(strategyArgs, matchersUtil) { var baseStrategy = new j$.SpyStrategy(strategyArgs); var argsStrategies = new StrategyDict(function() { return new j$.SpyStrategy(strategyArgs); - }); + }, matchersUtil); this.and = baseStrategy; @@ -9452,9 +8864,10 @@ getJasmineRequireObj().Spy = function(j$) { }; } - function StrategyDict(strategyFactory) { + function StrategyDict(strategyFactory, matchersUtil) { this.strategies = []; this.strategyFactory = strategyFactory; + this.matchersUtil = matchersUtil; } StrategyDict.prototype.any = function() { @@ -9479,7 +8892,7 @@ getJasmineRequireObj().Spy = function(j$) { var i; for (i = 0; i < this.strategies.length; i++) { - if (matchersUtil.equals(args, this.strategies[i].args)) { + if (this.matchersUtil.equals(args, this.strategies[i].args)) { return this.strategies[i].strategy; } } @@ -9489,17 +8902,19 @@ getJasmineRequireObj().Spy = function(j$) { }; getJasmineRequireObj().SpyFactory = function(j$) { - function SpyFactory(getCustomStrategies, getDefaultStrategyFn, getPromise) { + function SpyFactory( + getCustomStrategies, + getDefaultStrategyFn, + getMatchersUtil + ) { var self = this; this.createSpy = function(name, originalFn) { - return j$.Spy( - name, + return j$.Spy(name, getMatchersUtil(), { originalFn, - getCustomStrategies(), - getDefaultStrategyFn(), - getPromise - ); + customStrategies: getCustomStrategies(), + defaultStrategyFn: getDefaultStrategyFn() + }); }; this.createSpyObj = function(baseName, methodNames, propertyNames) { @@ -9850,24 +9265,6 @@ getJasmineRequireObj().SpyStrategy = function(j$) { } } - var getPromise = - typeof options.getPromise === 'function' - ? options.getPromise - : function() {}; - - var requirePromise = function(name) { - var Promise = getPromise(); - - if (!Promise) { - throw new Error( - name + - ' requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`' - ); - } - - return Promise; - }; - /** * Tell the spy to return a promise resolving to the specified value when invoked. * @name SpyStrategy#resolveTo @@ -9876,7 +9273,6 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {*} value The value to return. */ this.resolveTo = function(value) { - var Promise = requirePromise('resolveTo'); self.plan = function() { return Promise.resolve(value); }; @@ -9891,8 +9287,6 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {*} value The value to return. */ this.rejectWith = function(value) { - var Promise = requirePromise('rejectWith'); - self.plan = function() { return Promise.reject(value); }; @@ -10043,7 +9437,7 @@ getJasmineRequireObj().StackTrace = function(j$) { } var framePatterns = [ - // PhantomJS on Linux, Node, Chrome, IE, Edge + // Node, Chrome, Edge // e.g. " at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)" // Note that the "function name" can include a surprisingly large set of // characters, including angle brackets and square brackets. @@ -10062,7 +9456,7 @@ getJasmineRequireObj().StackTrace = function(j$) { // e.g. "run@http://localhost:8888/__jasmine__/jasmine.js:4320:27" // or "http://localhost:8888/__jasmine__/jasmine.js:4320:27" { - re: /^(([^@\s]+)@)?([^\s]+)$/, + re: /^(?:(([^@\s]+)@)|@)?([^\s]+)$/, fnIx: 2, fileLineColIx: 3, style: 'webkit' @@ -10165,12 +9559,6 @@ getJasmineRequireObj().Suite = function(j$) { * @since 2.0.0 */ this.id = attrs.id; - /** - * The parent of this suite, or null if this is the top suite. - * @name Suite#parentSuite - * @readonly - * @type {Suite} - */ this.parentSuite = attrs.parentSuite; /** * The description passed to the {@link describe} that created this suite. @@ -10186,12 +9574,12 @@ getJasmineRequireObj().Suite = function(j$) { this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.autoCleanClosures = attrs.autoCleanClosures === undefined ? true : !!attrs.autoCleanClosures; + this.onLateError = attrs.onLateError; this.beforeFns = []; this.afterFns = []; this.beforeAllFns = []; this.afterAllFns = []; - this.timer = attrs.timer || new j$.Timer(); /** @@ -10256,19 +9644,19 @@ getJasmineRequireObj().Suite = function(j$) { }; Suite.prototype.beforeEach = function(fn) { - this.beforeFns.unshift(fn); + this.beforeFns.unshift({ ...fn, suite: this }); }; Suite.prototype.beforeAll = function(fn) { - this.beforeAllFns.push(fn); + this.beforeAllFns.push({ ...fn, type: 'beforeAll', suite: this }); }; Suite.prototype.afterEach = function(fn) { - this.afterFns.unshift(fn); + this.afterFns.unshift({ ...fn, suite: this, type: 'afterEach' }); }; Suite.prototype.afterAll = function(fn) { - this.afterAllFns.unshift(fn); + this.afterAllFns.unshift({ ...fn, type: 'afterAll' }); }; Suite.prototype.startTimer = function() { @@ -10383,33 +9771,25 @@ getJasmineRequireObj().Suite = function(j$) { }; Suite.prototype.onMultipleDone = function() { - var msg; + let msg; // Issue a deprecation. Include the context ourselves and pass // ignoreRunnable: true, since getting here always means that we've already // moved on and the current runnable isn't the one that caused the problem. if (this.parentSuite) { msg = - "An asynchronous function called its 'done' callback more than " + - 'once. This is a bug in the spec, beforeAll, beforeEach, afterAll, ' + - 'or afterEach function in question. This will be treated as an error ' + - 'in a future version. See' + - ' ' + - 'for more information.\n' + + "An asynchronous beforeAll or afterAll function called its 'done' " + + 'callback more than once.\n' + '(in suite: ' + this.getFullName() + ')'; } else { msg = 'A top-level beforeAll or afterAll function called its ' + - "'done' callback more than once. This is a bug in the beforeAll " + - 'or afterAll function in question. This will be treated as an ' + - 'error in a future version. See' + - ' ' + - 'for more information.'; + "'done' callback more than once."; } - this.env.deprecated(msg, { ignoreRunnable: true }); + this.onLateError(new Error(msg)); }; Suite.prototype.addExpectationResult = function() { @@ -10431,6 +9811,68 @@ getJasmineRequireObj().Suite = function(j$) { ); }; + Object.defineProperty(Suite.prototype, 'metadata', { + get: function() { + if (!this.metadata_) { + this.metadata_ = new SuiteMetadata(this); + } + + return this.metadata_; + } + }); + + /** + * @interface Suite + * @see Env#topSuite + */ + function SuiteMetadata(suite) { + this.suite_ = suite; + /** + * The unique ID of this suite. + * @name Suite#id + * @readonly + * @type {string} + */ + this.id = suite.id; + + /** + * The parent of this suite, or null if this is the top suite. + * @name Suite#parentSuite + * @readonly + * @type {Suite} + */ + this.parentSuite = suite.parentSuite ? suite.parentSuite.metadata : null; + + /** + * The description passed to the {@link describe} that created this suite. + * @name Suite#description + * @readonly + * @type {string} + */ + this.description = suite.description; + } + + /** + * The full description including all ancestors of this suite. + * @name Suite#getFullName + * @function + * @returns {string} + */ + SuiteMetadata.prototype.getFullName = function() { + return this.suite_.getFullName(); + }; + + /** + * The suite's children. + * @name Suite#children + * @type {Array.<(Spec|Suite)>} + */ + Object.defineProperty(SuiteMetadata.prototype, 'children', { + get: function() { + return this.suite_.children.map(child => child.metadata); + } + }); + function isFailure(args) { return !args[0]; } @@ -10438,11 +9880,6 @@ getJasmineRequireObj().Suite = function(j$) { return Suite; }; -if (typeof window == void 0 && typeof exports == 'object') { - /* globals exports */ - exports.Suite = jasmineRequire.Suite; -} - getJasmineRequireObj().Timer = function() { var defaultNow = (function(Date) { return function() { @@ -10749,5 +10186,5 @@ getJasmineRequireObj().UserContext = function(j$) { }; getJasmineRequireObj().version = function() { - return '3.99.0'; + return '4.0.0-dev'; }; diff --git a/lib/jasmine-core/json2.js b/lib/jasmine-core/json2.js deleted file mode 100644 index deb88ec9..00000000 --- a/lib/jasmine-core/json2.js +++ /dev/null @@ -1,489 +0,0 @@ -/* - json2.js - 2014-02-04 - - Public Domain. - - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - - See http://www.JSON.org/js.html - - - This code should be minified before deployment. - See http://javascript.crockford.com/jsmin.html - - USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO - NOT CONTROL. - - - This file creates a global JSON object containing two methods: stringify - and parse. - - JSON.stringify(value, replacer, space) - value any JavaScript value, usually an object or array. - - replacer an optional parameter that determines how object - values are stringified for objects. It can be a - function or an array of strings. - - space an optional parameter that specifies the indentation - of nested structures. If it is omitted, the text will - be packed without extra whitespace. If it is a number, - it will specify the number of spaces to indent at each - level. If it is a string (such as '\t' or ' '), - it contains the characters used to indent at each level. - - This method produces a JSON text from a JavaScript value. - - When an object value is found, if the object contains a toJSON - method, its toJSON method will be called and the result will be - stringified. A toJSON method does not serialize: it returns the - value represented by the name/value pair that should be serialized, - or undefined if nothing should be serialized. The toJSON method - will be passed the key associated with the value, and this will be - bound to the value - - For example, this would serialize Dates as ISO strings. - - Date.prototype.toJSON = function (key) { - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - return this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z'; - }; - - You can provide an optional replacer method. It will be passed the - key and value of each member, with this bound to the containing - object. The value that is returned from your method will be - serialized. If your method returns undefined, then the member will - be excluded from the serialization. - - If the replacer parameter is an array of strings, then it will be - used to select the members to be serialized. It filters the results - such that only members with keys listed in the replacer array are - stringified. - - Values that do not have JSON representations, such as undefined or - functions, will not be serialized. Such values in objects will be - dropped; in arrays they will be replaced with null. You can use - a replacer function to replace those with JSON values. - JSON.stringify(undefined) returns undefined. - - The optional space parameter produces a stringification of the - value that is filled with line breaks and indentation to make it - easier to read. - - If the space parameter is a non-empty string, then that string will - be used for indentation. If the space parameter is a number, then - the indentation will be that many spaces. - - Example: - - text = JSON.stringify(['e', {pluribus: 'unum'}]); - // text is '["e",{"pluribus":"unum"}]' - - - text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); - // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' - - text = JSON.stringify([new Date()], function (key, value) { - return this[key] instanceof Date ? - 'Date(' + this[key] + ')' : value; - }); - // text is '["Date(---current time---)"]' - - - JSON.parse(text, reviver) - This method parses a JSON text to produce an object or array. - It can throw a SyntaxError exception. - - The optional reviver parameter is a function that can filter and - transform the results. It receives each of the keys and values, - and its return value is used instead of the original value. - If it returns what it received, then the structure is not modified. - If it returns undefined then the member is deleted. - - Example: - - // Parse the text. Values that look like ISO date strings will - // be converted to Date objects. - - myData = JSON.parse(text, function (key, value) { - var a; - if (typeof value === 'string') { - a = -/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); - if (a) { - return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], - +a[5], +a[6])); - } - } - return value; - }); - - myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { - var d; - if (typeof value === 'string' && - value.slice(0, 5) === 'Date(' && - value.slice(-1) === ')') { - d = new Date(value.slice(5, -1)); - if (d) { - return d; - } - } - return value; - }); - - - This is a reference implementation. You are free to copy, modify, or - redistribute. -*/ - -/*jslint evil: true, regexp: true */ - -/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, - call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, - getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, - lastIndex, length, parse, prototype, push, replace, slice, stringify, - test, toJSON, toString, valueOf -*/ - - -// Create a JSON object only if one does not already exist. We create the -// methods in a closure to avoid creating global variables. - -if (typeof JSON !== 'object') { - JSON = {}; -} - -(function () { - 'use strict'; - - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } - - if (typeof Date.prototype.toJSON !== 'function') { - - Date.prototype.toJSON = function () { - - return isFinite(this.valueOf()) - ? this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z' - : null; - }; - - String.prototype.toJSON = - Number.prototype.toJSON = - Boolean.prototype.toJSON = function () { - return this.valueOf(); - }; - } - - var cx, - escapable, - gap, - indent, - meta, - rep; - - - function quote(string) { - -// If the string contains no control characters, no quote characters, and no -// backslash characters, then we can safely slap some quotes around it. -// Otherwise we must also replace the offending characters with safe escape -// sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' - ? c - : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } - - - function str(key, holder) { - -// Produce a string from holder[key]. - - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - -// If the value has a toJSON method, call it to obtain a replacement value. - - if (value && typeof value === 'object' && - typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - -// If we were called with a replacer function, then call the replacer to -// obtain a replacement value. - - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - -// What happens next depends on the value's type. - - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - -// JSON numbers must be finite. Encode non-finite numbers as null. - - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - -// If the value is a boolean or null, convert it to a string. Note: -// typeof null does not produce 'null'. The case is included here in -// the remote chance that this gets fixed someday. - - return String(value); - -// If the type is 'object', we might be dealing with an object or an array or -// null. - - case 'object': - -// Due to a specification blunder in ECMAScript, typeof null is 'object', -// so watch out for that case. - - if (!value) { - return 'null'; - } - -// Make an array to hold the partial results of stringifying this object value. - - gap += indent; - partial = []; - -// Is the value an array? - - if (Object.prototype.toString.apply(value) === '[object Array]') { - -// The value is an array. Stringify every element. Use null as a placeholder -// for non-JSON values. - - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - -// Join all of the elements together, separated with commas, and wrap them in -// brackets. - - v = partial.length === 0 - ? '[]' - : gap - ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' - : '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - -// If the replacer is an array, use it to select the members to be stringified. - - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { - -// Otherwise, iterate through all of the keys in the object. - - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - -// Join all of the member texts together, separated with commas, -// and wrap them in braces. - - v = partial.length === 0 - ? '{}' - : gap - ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' - : '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } - -// If the JSON object does not yet have a stringify method, give it one. - - if (typeof JSON.stringify !== 'function') { - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }; - JSON.stringify = function (value, replacer, space) { - -// The stringify method takes a value and an optional replacer, and an optional -// space parameter, and returns a JSON text. The replacer can be a function -// that can replace values, or an array of strings that will select the keys. -// A default replacer method can be provided. Use of the space parameter can -// produce text that is more easily readable. - - var i; - gap = ''; - indent = ''; - -// If the space parameter is a number, make an indent string containing that -// many spaces. - - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - -// If the space parameter is a string, it will be used as the indent string. - - } else if (typeof space === 'string') { - indent = space; - } - -// If there is a replacer, it must be a function or an array. -// Otherwise, throw an error. - - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - -// Make a fake root object containing our value under the key of ''. -// Return the result of stringifying the value. - - return str('', {'': value}); - }; - } - - -// If the JSON object does not yet have a parse method, give it one. - - if (typeof JSON.parse !== 'function') { - cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; - JSON.parse = function (text, reviver) { - -// The parse method takes a text and an optional reviver function, and returns -// a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - -// The walk method is used to recursively walk the resulting structure so -// that modifications can be made. - - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } - - -// Parsing happens in four stages. In the first stage, we replace certain -// Unicode characters with escape sequences. JavaScript handles many characters -// incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } - -// In the second stage, we run the text against regular expressions that look -// for non-JSON patterns. We are especially concerned with '()' and 'new' -// because they can cause invocation, and '=' because it can cause mutation. -// But just to be safe, we want to reject all unexpected forms. - -// We split the second stage into 4 regexp operations in order to work around -// crippling inefficiencies in IE's and Safari's regexp engines. First we -// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we -// replace all simple value tokens with ']' characters. Third, we delete all -// open brackets that follow a colon or comma or that begin the text. Finally, -// we look to see that the remaining characters are only whitespace or ']' or -// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { - -// In the third stage we use the eval function to compile the text into a -// JavaScript structure. The '{' operator is subject to a syntactic ambiguity -// in JavaScript: it can begin a block or an object literal. We wrap the text -// in parens to eliminate the ambiguity. - - j = eval('(' + text + ')'); - -// In the optional fourth stage, we recursively walk the new structure, passing -// each name/value pair to a reviver function for possible transformation. - - return typeof reviver === 'function' - ? walk({'': j}, '') - : j; - } - -// If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError('JSON.parse'); - }; - } -}()); diff --git a/lib/jasmine-core/node_boot.js b/lib/jasmine-core/node_boot.js index e0a8acee..40bffff3 100644 --- a/lib/jasmine-core/node_boot.js +++ b/lib/jasmine-core/node_boot.js @@ -23,7 +23,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. module.exports = function(jasmineRequire) { var jasmine = jasmineRequire.core(jasmineRequire); - var env = jasmine.getEnv({suppressLoadErrors: true}); + var env = jasmine.getEnv({ suppressLoadErrors: true }); var jasmineInterface = jasmineRequire.interface(jasmine, env); diff --git a/lib/jasmine-core/version.rb b/lib/jasmine-core/version.rb deleted file mode 100644 index 5209521b..00000000 --- a/lib/jasmine-core/version.rb +++ /dev/null @@ -1,9 +0,0 @@ -# -# DO NOT Edit this file. Canonical version of Jasmine lives in the repo's package.json. This file is generated -# by a grunt task when the standalone release is built. -# -module Jasmine - module Core - VERSION = "3.99.0" - end -end diff --git a/package.json b/package.json index 377cf6ba..1bd0fdc8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "jasmine-core", "license": "MIT", - "version": "3.99.0", + "version": "4.0.0-dev", "repository": { "type": "git", "url": "https://github.com/jasmine/jasmine.git" @@ -34,22 +34,21 @@ "package.json" ], "devDependencies": { - "ejs": "^2.5.5", - "eslint": "^6.8.0", - "eslint-plugin-compat": "^3.8.0", - "fast-glob": "^2.2.6", + "eslint": "^7.32.0", + "eslint-plugin-compat": "^4.0.0", + "glob": "^7.2.0", "grunt": "^1.0.4", "grunt-cli": "^1.3.2", - "grunt-contrib-compress": "^1.3.0", - "grunt-contrib-concat": "^1.0.1", + "grunt-contrib-compress": "^2.0.0", + "grunt-contrib-concat": "^2.0.0", "grunt-css-url-embed": "^1.11.1", "grunt-sass": "^3.0.2", - "jasmine": "^3.10.0", - "jasmine-browser-runner": "github:jasmine/jasmine-browser#main", - "jsdom": "^15.0.0", - "load-grunt-tasks": "^4.0.0", + "jasmine": "github:jasmine/jasmine-npm#4.0", + "jasmine-browser-runner": "github:jasmine/jasmine-browser#1.0", + "jsdom": "^19.0.0", + "load-grunt-tasks": "^5.1.0", "prettier": "1.17.1", - "sass": "^1.32.12", + "sass": "^1.45.1", "shelljs": "^0.8.3", "temp": "^0.9.0" }, @@ -60,8 +59,13 @@ "extends": [ "plugin:compat/recommended" ], + "env": { + "browser": true, + "node": true, + "es2017": true + }, "parserOptions": { - "ecmaVersion": 5 + "ecmaVersion": 2018 }, "rules": { "quotes": [ @@ -77,6 +81,7 @@ "args": "none" } ], + "no-implicit-globals": "error", "block-spacing": "error", "func-call-spacing": [ "error", @@ -94,11 +99,10 @@ } }, "browserslist": [ - "Safari >= 8", + "Safari >= 13", "last 2 Chrome versions", "last 2 Firefox versions", - "Firefox 68", - "last 2 Edge versions", - "IE >= 10" + "Firefox >= 68", + "last 2 Edge versions" ] } diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 591279c2..00000000 --- a/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -ordereddict==1.1 diff --git a/scripts/run-all-browsers b/scripts/run-all-browsers index 45d74aaa..d4fc6cce 100755 --- a/scripts/run-all-browsers +++ b/scripts/run-all-browsers @@ -23,18 +23,12 @@ run_browser() { passfile=`mktemp -t jasmine-results.XXXXXX` || exit 1 failfile=`mktemp -t jasmine-results.XXXXXX` || exit 1 -run_browser "internet explorer" 11 -run_browser "internet explorer" 10 run_browser chrome latest run_browser firefox latest run_browser firefox 91 -run_browser firefox 78 -run_browser firefox 68 -run_browser safari 14 -run_browser safari 13 -run_browser safari 9 -run_browser safari 8 -run_browser MicrosoftEdge latest +run_browser safari 15 +run_browser safari 14 +run_browser MicrosoftEdge latest echo cat "$passfile" "$failfile" diff --git a/setup.py b/setup.py deleted file mode 100644 index eab51064..00000000 --- a/setup.py +++ /dev/null @@ -1,70 +0,0 @@ -from setuptools import setup, find_packages, os -import json - -with open('package.json') as packageFile: - version = json.load(packageFile)['version'] - -short_description=('Jasmine is a Behavior Driven Development testing framework for JavaScript. It does not rely on '+ - 'browsers, DOM, or any JavaScript framework. Thus it\'s suited for websites, '+ - 'Node.js (http://nodejs.org) projects, or anywhere that JavaScript can run.') -deprecation=('The Jasmine packages for Python are deprecated. There will be no further\n' + - 'releases after the end of the Jasmine 3.x series. We recommend migrating to the\n' + - 'following options:\n' + - '\n' + - '* jasmine-browser-runner (,\n' + - ' `npm install jasmine-browser-runner`) to run specs in browsers, including\n' + - ' headless Chrome and Saucelabs. This is the most direct replacement for the\n' + - ' jasmine server` and `jasmine ci` commands provided by the `jasmine` Python\n' + - ' package.\n' + - '* The jasmine npm package (,\n' + - ' `npm install jasmine`) to run specs under Node.js.\n' + - '* The standalone distribution from the latest Jasmine release\n' + - ' to run specs in browsers with\n' + - ' no additional tools.\n' + - '* The jasmine-core npm package (`npm install jasmine-core`) if all you need is\n' + - ' the Jasmine assets. This is the direct equivalent of the jasmine-core Python\n' + - ' package.\n' + - '\n' + - 'Except for the standalone distribution, all of the above are distributed through\n' - 'npm.\n') -long_description = short_description + '\n\n' + deprecation - - -setup( - name="jasmine-core", - version=version, - url="http://jasmine.github.io", - author="Pivotal Labs", - author_email="jasmine-js@googlegroups.com", - description=short_description, - long_description=long_description, - long_description_content_type='text/plain', - license='MIT', - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Environment :: Console', - 'Environment :: Web Environment', - 'Framework :: Django', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.2', - 'Programming Language :: Python :: 3.3', - 'Programming Language :: Python :: Implementation :: PyPy', - 'Topic :: Internet :: WWW/HTTP', - 'Topic :: Software Development :: Libraries :: Python Modules', - 'Topic :: Software Development :: Build Tools', - 'Topic :: Software Development :: Quality Assurance', - 'Topic :: Software Development :: Testing', - ], - - packages=['jasmine_core', 'jasmine_core.images'], - package_dir={'jasmine_core': 'lib/jasmine-core', 'jasmine_core.images': 'images'}, - package_data={'jasmine_core': ['*.js', '*.css'], 'jasmine_core.images': ['*.png']}, - - include_package_data=True, - - install_requires=['glob2>=0.4.1', 'ordereddict==1.1'] -) diff --git a/spec/core/AsyncExpectationSpec.js b/spec/core/AsyncExpectationSpec.js index 338e0faf..60dc2f01 100644 --- a/spec/core/AsyncExpectationSpec.js +++ b/spec/core/AsyncExpectationSpec.js @@ -1,4 +1,3 @@ -/* eslint-disable compat/compat */ describe('AsyncExpectation', function() { beforeEach(function() { jasmineUnderTest.Expectation.addAsyncCoreMatchers( @@ -6,23 +5,8 @@ describe('AsyncExpectation', function() { ); }); - describe('Factory', function() { - it('throws an Error if promises are not available', function() { - var thenable = { then: function() {} }, - options = { global: {}, actual: thenable }; - function f() { - jasmineUnderTest.Expectation.asyncFactory(options); - } - expect(f).toThrowError( - 'expectAsync is unavailable because the environment does not support promises.' - ); - }); - }); - describe('#not', function() { it('converts a pass to a fail', function() { - jasmine.getEnv().requirePromises(); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.resolve(), pp = jasmineUnderTest.makePrettyPrinter(), @@ -44,8 +28,6 @@ describe('AsyncExpectation', function() { }); it('converts a fail to a pass', function() { - jasmine.getEnv().requirePromises(); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.reject(), expectation = jasmineUnderTest.Expectation.asyncFactory({ @@ -69,7 +51,6 @@ describe('AsyncExpectation', function() { }); it('propagates rejections from the comparison function', function() { - jasmine.getEnv().requirePromises(); var error = new Error('ExpectationSpec failure'); var addExpectationResult = jasmine.createSpy('addExpectationResult'), @@ -93,8 +74,6 @@ describe('AsyncExpectation', function() { describe('#withContext', function() { it('prepends the context to the generated failure message', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = { pp: function(val) { return val.toString(); @@ -122,8 +101,6 @@ describe('AsyncExpectation', function() { }); it('prepends the context to a custom failure message', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = { buildFailureMessage: function() { return 'failure message'; @@ -154,7 +131,6 @@ describe('AsyncExpectation', function() { it('prepends the context to a custom failure message from a function', function() { pending('should actually work, but no custom matchers for async yet'); - jasmine.getEnv().requirePromises(); var matchersUtil = { buildFailureMessage: function() { @@ -183,8 +159,6 @@ describe('AsyncExpectation', function() { }); it('works with #not', function() { - jasmine.getEnv().requirePromises(); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.resolve(), pp = jasmineUnderTest.makePrettyPrinter(), @@ -209,8 +183,6 @@ describe('AsyncExpectation', function() { }); it('works with #not and a custom message', function() { - jasmine.getEnv().requirePromises(); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.resolve('a'), expectation = jasmineUnderTest.Expectation.asyncFactory({ @@ -238,8 +210,6 @@ describe('AsyncExpectation', function() { describe('async matchers', function() { it('makes custom matchers available to this expectation', function() { - jasmine.getEnv().requirePromises(); - var asyncMatchers = { toFoo: function() {}, toBar: function() {} @@ -255,8 +225,6 @@ describe('AsyncExpectation', function() { }); it("wraps matchers's compare functions, passing in matcher dependencies", function() { - jasmine.getEnv().requirePromises(); - var fakeCompare = function() { return Promise.resolve({ pass: true }); }, @@ -285,8 +253,6 @@ describe('AsyncExpectation', function() { }); it("wraps matchers's compare functions, passing the actual and expected", function() { - jasmine.getEnv().requirePromises(); - var fakeCompare = jasmine .createSpy('fake-compare') .and.returnValue(Promise.resolve({ pass: true })), @@ -316,8 +282,6 @@ describe('AsyncExpectation', function() { }); it('reports a passing result to the spec when the comparison passes', function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { @@ -359,8 +323,6 @@ describe('AsyncExpectation', function() { }); it('reports a failing result to the spec when the comparison fails', function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { @@ -404,8 +366,6 @@ describe('AsyncExpectation', function() { }); it('reports a failing result and a custom fail message to the spec when the comparison fails', function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { @@ -446,8 +406,6 @@ describe('AsyncExpectation', function() { }); it('reports a failing result with a custom fail message function to the spec when the comparison fails', function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { @@ -490,8 +448,6 @@ describe('AsyncExpectation', function() { }); it('reports a passing result to the spec when the comparison fails for a negative expectation', function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { @@ -530,8 +486,6 @@ describe('AsyncExpectation', function() { }); it('reports a failing result to the spec when the comparison passes for a negative expectation', function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { @@ -576,8 +530,6 @@ describe('AsyncExpectation', function() { }); it('reports a failing result and a custom fail message to the spec when the comparison passes for a negative expectation', function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { @@ -619,8 +571,6 @@ describe('AsyncExpectation', function() { }); it("reports a passing result to the spec when the 'not' comparison passes, given a negativeCompare", function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { @@ -662,8 +612,6 @@ describe('AsyncExpectation', function() { }); it("reports a failing result and a custom fail message to the spec when the 'not' comparison fails, given a negativeCompare", function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { @@ -708,8 +656,6 @@ describe('AsyncExpectation', function() { }); it('reports errorWithStack when a custom error message is returned', function() { - jasmine.getEnv().requirePromises(); - var customError = new Error('I am a custom error'); var matchers = { toFoo: function() { @@ -752,8 +698,6 @@ describe('AsyncExpectation', function() { }); it("reports a custom message to the spec when a 'not' comparison fails", function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { @@ -794,8 +738,6 @@ describe('AsyncExpectation', function() { }); it("reports a custom message func to the spec when a 'not' comparison fails", function() { - jasmine.getEnv().requirePromises(); - var matchers = { toFoo: function() { return { diff --git a/spec/core/ClockSpec.js b/spec/core/ClockSpec.js index 126fe8ca..69c05fc4 100644 --- a/spec/core/ClockSpec.js +++ b/spec/core/ClockSpec.js @@ -950,7 +950,7 @@ describe('Clock (acceptance)', function() { expect(timeoutDate).toEqual(baseTime.getTime() + 150); }); - it('logs a deprecation when mockDate is called with a non-Date', function() { + it('throws mockDate is called with a non-Date', function() { var delayedFunctionScheduler = new jasmineUnderTest.DelayedFunctionScheduler(), global = { Date: Date }, mockDate = new jasmineUnderTest.MockDate(global), @@ -963,12 +963,9 @@ describe('Clock (acceptance)', function() { ), env = jasmineUnderTest.getEnv(); - spyOn(env, 'deprecated'); - clock.mockDate(12345); - expect(env.deprecated).toHaveBeenCalledWith( + expect(() => clock.mockDate(12345)).toThrowError( 'The argument to jasmine.clock().mockDate(), if specified, should be ' + - 'a Date instance. Passing anything other than a Date will be ' + - 'treated as an error in a future release.' + 'a Date instance.' ); }); diff --git a/spec/core/CompleteOnFirstErrorSkipPolicySpec.js b/spec/core/CompleteOnFirstErrorSkipPolicySpec.js new file mode 100644 index 00000000..babe4605 --- /dev/null +++ b/spec/core/CompleteOnFirstErrorSkipPolicySpec.js @@ -0,0 +1,131 @@ +describe('CompleteOnFirstErrorSkipPolicy', function() { + describe('#skipTo', function() { + describe('Before anything has errored', function() { + it('returns the next index', function() { + const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy( + arrayOfArbitraryFns(4), + 4 + ); + expect(policy.skipTo(1)).toEqual(2); + }); + }); + + describe('After something has errored', function() { + it('skips non cleanup fns', function() { + const fns = arrayOfArbitraryFns(4); + fns[2].type = arbitraryCleanupType(); + fns[3].type = arbitraryCleanupType(); + const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy(fns); + + policy.fnErrored(0); + expect(policy.skipTo(0)).toEqual(2); + expect(policy.skipTo(2)).toEqual(3); + expect(policy.skipTo(3)).toEqual(4); + }); + + for (const type of ['afterEach', 'specCleanup', 'afterAll']) { + it(`does not skip ${type} fns`, function() { + const fns = arrayOfArbitraryFns(2); + fns[1].type = type; + const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy( + fns + ); + + policy.fnErrored(0); + expect(policy.skipTo(0)).toEqual(1); + }); + } + + describe('When the error was in a beforeEach fn', function() { + it('runs cleanup fns defined by the current and containing suites', function() { + const parentSuite = { description: 'parentSuite' }; + const suite = { description: 'suite', parentSuite }; + const fns = [ + { + suite: suite + }, + { + fn: () => {} + }, + { + fn: () => {}, + suite: suite, + type: arbitraryCleanupType() + }, + { + fn: () => {}, + suite: parentSuite, + type: arbitraryCleanupType() + } + ]; + const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy( + fns + ); + + policy.fnErrored(0); + expect(policy.skipTo(0)).toEqual(2); + expect(policy.skipTo(2)).toEqual(3); + }); + + it('skips cleanup fns defined by nested suites', function() { + const parentSuite = { description: 'parentSuite' }; + const suite = { description: 'suite', parentSuite }; + const fns = [ + { + fn: () => {}, + type: 'beforeEach', + suite: parentSuite + }, + { + fn: () => {} + }, + { + fn: () => {}, + suite: suite, + type: arbitraryCleanupType() + }, + { + fn: () => {}, + suite: parentSuite, + type: arbitraryCleanupType() + } + ]; + const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy( + fns + ); + + policy.fnErrored(0); + expect(policy.skipTo(0)).toEqual(3); + }); + }); + + it('does not skip cleanup fns that have no suite, such as the spec complete fn', function() { + const fns = [ + { fn: () => {} }, + { + fn: () => {}, + type: arbitraryCleanupType() + } + ]; + const policy = new jasmineUnderTest.CompleteOnFirstErrorSkipPolicy(fns); + + policy.fnErrored(0); + expect(policy.skipTo(0)).toEqual(1); + }); + }); + }); + + function arrayOfArbitraryFns(n) { + const result = []; + + for (let i = 0; i < n; i++) { + result.push({ fn: () => {} }); + } + + return result; + } + + function arbitraryCleanupType() { + return 'specCleanup'; + } +}); diff --git a/spec/core/DelayedFunctionSchedulerSpec.js b/spec/core/DelayedFunctionSchedulerSpec.js index d06a66c1..caa585c6 100644 --- a/spec/core/DelayedFunctionSchedulerSpec.js +++ b/spec/core/DelayedFunctionSchedulerSpec.js @@ -278,4 +278,58 @@ describe('DelayedFunctionScheduler', function() { expect(tickDate).toHaveBeenCalledWith(0); expect(tickDate).toHaveBeenCalledWith(1); }); + + describe('ticking inside a scheduled function', function() { + let clock; + + // Runner function calls the callback until it returns false + function runWork(workCallback) { + while (workCallback()) {} + } + + // Make a worker that takes a little time and tracks when it finished + function mockWork(times) { + return () => { + clock.tick(1); + const now = new Date().getTime(); + expect(lastWork) + .withContext('Previous function calls should always be in the past') + .toBeLessThan(now); + lastWork = now; + times--; + return times > 0; + }; + } + let lastWork = 0; + + beforeEach(() => { + clock = jasmineUnderTest.getEnv().clock; + clock.install(); + clock.mockDate(new Date(1)); + }); + + afterEach(function() { + jasmineUnderTest.getEnv().clock.uninstall(); + }); + + it('preserves monotonically-increasing current time', () => { + const work1 = mockWork(3); + setTimeout(() => { + runWork(work1); + }, 1); + clock.tick(1); + expect(lastWork) + .withContext('tick should advance past last-scheduled function') + .toBeLessThanOrEqual(new Date().getTime()); + + const work2 = mockWork(3); + setTimeout(() => { + runWork(work2); + }, 1); + clock.tick(1); + expect(lastWork) + .withContext('tick should advance past last-scheduled function') + .toBeLessThanOrEqual(new Date().getTime()); + }); + }); }); diff --git a/spec/core/EnvSpec.js b/spec/core/EnvSpec.js index 5087d185..e51c3c20 100644 --- a/spec/core/EnvSpec.js +++ b/spec/core/EnvSpec.js @@ -39,19 +39,25 @@ describe('Env', function() { }); suite = env.topSuite(); + expect(suite).not.toBeInstanceOf(jasmineUnderTest.Suite); expect(suite.description).toEqual('Jasmine__TopLevel__Suite'); expect(suite.getFullName()).toEqual(''); expect(suite.children.length).toEqual(2); + expect(suite.children[0]).not.toBeInstanceOf(jasmineUnderTest.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].children).toBeFalsy(); + expect(suite.children[1]).not.toBeInstanceOf(jasmineUnderTest.Suite); expect(suite.children[1].description).toEqual('a suite'); expect(suite.children[1].getFullName()).toEqual('a suite'); expect(suite.children[1].parentSuite).toBe(suite); expect(suite.children[1].children.length).toEqual(2); + expect(suite.children[1].children[0]).not.toBeInstanceOf( + jasmineUnderTest.Spec + ); expect(suite.children[1].children[0].description).toEqual('a spec'); expect(suite.children[1].children[0].getFullName()).toEqual( 'a suite a spec' @@ -75,180 +81,6 @@ describe('Env', function() { ); expect(suite.children[1].children[1].children[0].children).toBeFalsy(); }); - - it('does not deprecate access to public Suite and Spec members', function() { - jasmine.getEnv().requireProxy(); - var suite; - spyOn(env, 'deprecated'); - - env.it('a top level spec'); - env.describe('a suite', function() { - env.it('a spec'); - }); - - suite = env.topSuite(); - suite.id; - suite.description; - suite.getFullName(); - suite.children; - suite.parentSuite; - suite.children[0].id; - suite.children[0].description; - suite.children[0].getFullName(); - suite.children[0].children; - - suite.children[1].id; - suite.children[1].description; - suite.children[1].getFullName(); - suite.children[1].parentSuite; - suite.children[1].children; - - expect(env.deprecated).not.toHaveBeenCalled(); - }); - - it('deprecates access to internal Spec members via it(), fit(), and xit()', function() { - jasmine.getEnv().requireProxy(); - spyOn(env, 'deprecated'); - - ['it', 'fit', 'xit'].forEach(function(method) { - var spec = env[method]('a spec', function() {}); - expect(env.deprecated).not.toHaveBeenCalled(); - - spec.pend(); - expect(env.deprecated) - .withContext('via ' + method) - .toHaveBeenCalledWith( - 'Access to private Spec members (in this case `pend`) is not ' + - 'supported and will break in a future release. See ' + - ' for correct usage.' - ); - env.deprecated.calls.reset(); - - spec.expectationFactory = {}; - expect(env.deprecated) - .withContext('via ' + method) - .toHaveBeenCalledWith( - 'Access to private Spec members (in this case `expectationFactory`) is not ' + - 'supported and will break in a future release. See ' + - ' for correct usage.' - ); - env.deprecated.calls.reset(); - - spec.expectationFactory = {}; - expect(env.deprecated) - .withContext('via ' + method) - .toHaveBeenCalledWith( - 'Access to private Spec members (in this case `expectationFactory`) is not ' + - 'supported and will break in a future release. See ' + - ' for correct usage.' - ); - env.deprecated.calls.reset(); - }); - }); - - it('deprecates access to internal Spec and Suite members via describe(), fdescribe(), and xdescribe()', function() { - jasmine.getEnv().requireProxy(); - spyOn(env, 'deprecated'); - - ['describe', 'fdescribe', 'xdescribe'].forEach(function(method) { - var suite = env[method]('a suite', function() { - env.it('a spec'); - }); - - suite.expectationFactory; - expect(env.deprecated) - .withContext('via ' + method) - .toHaveBeenCalledWith( - 'Access to private Suite ' + - 'members (in this case `expectationFactory`) is ' + - 'not supported and will break in a future release. See ' + - ' for correct usage.' - ); - env.deprecated.calls.reset(); - - suite.expectationFactory = {}; - expect(env.deprecated) - .withContext('via ' + method) - .toHaveBeenCalledWith( - 'Access to private Suite ' + - 'members (in this case `expectationFactory`) is ' + - 'not supported and will break in a future release. See ' + - ' for correct usage.' - ); - env.deprecated.calls.reset(); - - suite.status(); - expect(env.deprecated) - .withContext('via ' + method) - .toHaveBeenCalledWith( - 'Access to private Suite ' + - 'members (in this case `status`) is ' + - 'not supported and will break in a future release. See ' + - ' for correct usage.' - ); - env.deprecated.calls.reset(); - }); - }); - - it('deprecates access to internal Suite and Spec members via topSuite', function() { - jasmine.getEnv().requireProxy(); - var topSuite, expectationFactory, spec; - - env.it('a top level spec'); - spyOn(env, 'deprecated'); - topSuite = env.topSuite(); - - topSuite.expectationFactory; - expect(env.deprecated).toHaveBeenCalledWith( - 'Access to private Suite ' + - 'members (in this case `expectationFactory`) is ' + - 'not supported and will break in a future release. See ' + - ' for correct usage.' - ); - env.deprecated.calls.reset(); - - topSuite.expectationFactory = expectationFactory; - expect(env.deprecated).toHaveBeenCalledWith( - 'Access to private Suite ' + - 'members (in this case `expectationFactory`) is ' + - 'not supported and will break in a future release. See ' + - ' for correct usage.' - ); - - topSuite.status(); - expect(env.deprecated).toHaveBeenCalledWith( - 'Access to private Suite ' + - 'members (in this case `status`) is ' + - 'not supported and will break in a future release. See ' + - ' for correct usage.' - ); - - spec = topSuite.children[0]; - spec.pend(); - expect(env.deprecated).toHaveBeenCalledWith( - 'Access to private Spec ' + - 'members (in this case `pend`) ' + - 'is not supported and will break in a future release. See ' + - ' for correct usage.' - ); - - expectationFactory = spec.expectationFactory; - expect(env.deprecated).toHaveBeenCalledWith( - 'Access to private Spec ' + - 'members (in this case `expectationFactory`) ' + - 'is not supported and will break in a future release. See ' + - ' for correct usage.' - ); - env.deprecated.calls.reset(); - - spec.expectationFactory = expectationFactory; - expect(env.deprecated).toHaveBeenCalledWith( - 'Access to private Spec ' + - 'members (in this case `expectationFactory`) ' + - 'is not supported and will break in a future release. See ' + - ' for correct usage.' - ); - }); }); it('accepts its own current configureation', function() { @@ -258,7 +90,7 @@ describe('Env', function() { it('can configure specs to throw errors on expectation failures', function() { env.configure({ stopSpecOnExpectationFailure: true }); - spyOn(jasmineUnderTest, 'Spec'); + spyOn(jasmineUnderTest, 'Spec').and.callThrough(); env.it('foo', function() {}); expect(jasmineUnderTest.Spec).toHaveBeenCalledWith( jasmine.objectContaining({ @@ -284,9 +116,7 @@ describe('Env', function() { var initialConfig = { random: true, seed: '123', - failFast: true, failSpecWithNoExpectations: true, - oneFailurePerSpec: true, stopSpecOnExpectationFailure: true, stopOnSpecFailure: true, hideDisabled: true @@ -296,9 +126,7 @@ describe('Env', function() { env.configure({ random: undefined, seed: undefined, - failFast: undefined, failSpecWithNoExpectations: undefined, - oneFailurePerSpec: undefined, stopSpecOnExpectationFailure: undefined, stopOnSpecFailure: undefined, hideDisabled: undefined @@ -309,122 +137,8 @@ describe('Env', function() { ); }); - it('sets stopOnSpecFailure when failFast is set, and vice versa', function() { - spyOn(env, 'deprecated'); - env.configure({ failFast: true }); - expect(env.configuration()).toEqual( - jasmine.objectContaining({ - failFast: true, - stopOnSpecFailure: true - }) - ); - - env.configure({ stopOnSpecFailure: false }); - expect(env.configuration()).toEqual( - jasmine.objectContaining({ - failFast: false, - stopOnSpecFailure: false - }) - ); - }); - - it('rejects a single call that sets stopOnSpecFailure and failFast to different values', function() { - spyOn(env, 'deprecated'); - expect(function() { - env.configure({ failFast: true, stopOnSpecFailure: false }); - }).toThrowError( - 'stopOnSpecFailure and failFast are aliases for each ' + - "other. Don't set failFast if you also set stopOnSpecFailure." - ); - }); - - it('deprecates the failFast config property', function() { - spyOn(env, 'deprecated'); - env.configure({ failFast: true }); - expect(env.deprecated).toHaveBeenCalledWith( - 'The `failFast` config property is deprecated and will be removed in a ' + - 'future version of Jasmine. Please use `stopOnSpecFailure` instead.', - { ignoreRunnable: true } - ); - }); - - it('sets stopSpecOnExpectationFailure when oneFailurePerSpec is set, and vice versa', function() { - spyOn(env, 'deprecated'); - env.configure({ oneFailurePerSpec: true }); - expect(env.configuration()).toEqual( - jasmine.objectContaining({ - oneFailurePerSpec: true, - stopSpecOnExpectationFailure: true - }) - ); - - env.configure({ stopSpecOnExpectationFailure: false }); - expect(env.configuration()).toEqual( - jasmine.objectContaining({ - oneFailurePerSpec: false, - stopSpecOnExpectationFailure: false - }) - ); - }); - - it('rejects a single call that sets stopSpecOnExpectationFailure and oneFailurePerSpec to different values', function() { - spyOn(env, 'deprecated'); - expect(function() { - env.configure({ - oneFailurePerSpec: true, - stopSpecOnExpectationFailure: false - }); - }).toThrowError( - 'stopSpecOnExpectationFailure and oneFailurePerSpec are ' + - "aliases for each other. Don't set oneFailurePerSpec if you also set " + - 'stopSpecOnExpectationFailure.' - ); - }); - - it('deprecates the oneFailurePerSpec config property', function() { - spyOn(env, 'deprecated'); - env.configure({ oneFailurePerSpec: true }); - expect(env.deprecated).toHaveBeenCalledWith( - 'The `oneFailurePerSpec` config property is deprecated and will be ' + - 'removed in a future version of Jasmine. Please use ' + - '`stopSpecOnExpectationFailure` instead.', - { ignoreRunnable: true } - ); - }); - - describe('promise library', function() { - it('can be configured without a custom library', function() { - env.configure({}); - env.configure({ Promise: undefined }); - }); - - it('can be configured with a custom library', function() { - spyOn(env, 'deprecated'); - var myLibrary = { - resolve: jasmine.createSpy(), - reject: jasmine.createSpy() - }; - env.configure({ Promise: myLibrary }); - expect(env.deprecated).toHaveBeenCalledWith( - 'The `Promise` config property is deprecated. Future versions of ' + - 'Jasmine will create native promises even if the `Promise` config ' + - 'property is set. Please remove it.' - ); - }); - - it('cannot be configured with an invalid promise library', function() { - var myLibrary = {}; - - expect(function() { - env.configure({ Promise: myLibrary }); - }).toThrowError( - 'Custom promise library missing `resolve`/`reject` functions' - ); - }); - }); - it('defaults to multiple failures for specs', function() { - spyOn(jasmineUnderTest, 'Spec'); + spyOn(jasmineUnderTest, 'Spec').and.callThrough(); env.it('bar', function() {}); expect(jasmineUnderTest.Spec).toHaveBeenCalledWith( jasmine.objectContaining({ @@ -443,7 +157,40 @@ describe('Env', function() { ); }); + function behavesLikeDescribe(methodName) { + it('returns a suite metadata object', function() { + let innerSuite; + let spec; + const suite = env.describe('outer suite', function() { + innerSuite = env.describe('inner suite', function() { + spec = env.it('a spec'); + }); + }); + + expect(suite.parentSuite).toEqual( + jasmine.objectContaining({ + description: 'Jasmine__TopLevel__Suite' + }) + ); + expect(suite.parentSuite.pend).toBeUndefined(); + expect(suite.pend).toBeUndefined(); + expect(suite.description).toEqual('outer suite'); + expect(suite.getFullName()).toEqual('outer suite'); + expect(suite.id).toBeInstanceOf(String); + expect(suite.id).not.toEqual(''); + expect(suite.children.length).toEqual(1); + expect(suite.children[0]).toBe(innerSuite); + expect(innerSuite.children.length).toEqual(1); + expect(innerSuite.children[0]).toBe(spec); + expect(innerSuite.getFullName()).toEqual('outer suite inner suite'); + expect(innerSuite.parentSuite).toBe(suite); + expect(spec.getFullName()).toEqual('outer suite inner suite a spec'); + }); + } + describe('#describe', function() { + behavesLikeDescribe('describe'); + it('throws an error when given arguments', function() { expect(function() { env.describe('done method', function(done) {}); @@ -487,19 +234,48 @@ describe('Env', function() { ); }); - it('logs a deprecation when it has no children', function() { - spyOn(env, 'deprecated'); - env.describe('no children', function() {}); - expect(env.deprecated).toHaveBeenCalledWith( - 'describe with no children' + - ' (describe() or it()) is deprecated and will be removed in a future ' + - 'version of Jasmine. Please either remove the describe or add ' + - 'children to it.' - ); + it('throws an error when it has no children', function() { + expect(function() { + env.describe('done method', function() {}); + }).toThrowError('describe with no children (describe() or it())'); }); }); + describe('#fdescribe', function() { + behavesLikeDescribe('fdescribe'); + }); + + describe('xdescribe', function() { + behavesLikeDescribe('xdescribe'); + }); + + function behavesLikeIt(methodName) { + it('returns a spec metadata object', function() { + let spec; + + env.describe('a suite', function() { + spec = env[methodName]('a spec', function() {}); + }); + + expect(spec.description) + .withContext('description') + .toEqual('a spec'); + expect(spec.getFullName()) + .withContext('getFullName') + .toEqual('a suite a spec'); + expect(spec.id) + .withContext('id') + .toBeInstanceOf(String); + expect(spec.id) + .withContext('id') + .not.toEqual(''); + expect(spec.pend).toBeFalsy(); + }); + } + describe('#it', function() { + behavesLikeIt('it'); + it('throws an error when it receives a non-fn argument', function() { expect(function() { env.it('undefined arg', null); @@ -515,9 +291,8 @@ describe('Env', function() { }); it('accepts an async function', function() { - jasmine.getEnv().requireAsyncAwait(); expect(function() { - env.it('async', jasmine.getEnv().makeAsyncAwaitFunction()); + env.it('async', async function() {}); }).not.toThrow(); }); @@ -529,6 +304,8 @@ describe('Env', function() { }); describe('#xit', function() { + behavesLikeIt('xit'); + it('calls spec.exclude with "Temporarily disabled with xit"', function() { var excludeSpy = jasmine.createSpy(); spyOn(env, 'it_').and.returnValue({ @@ -565,14 +342,15 @@ describe('Env', function() { }); it('accepts an async function', function() { - jasmine.getEnv().requireAsyncAwait(); expect(function() { - env.xit('async', jasmine.getEnv().makeAsyncAwaitFunction()); + env.xit('async', async function() {}); }).not.toThrow(); }); }); describe('#fit', function() { + behavesLikeIt('fit'); + it('throws an error when it receives a non-fn argument', function() { expect(function() { env.fit('undefined arg', undefined); @@ -598,9 +376,8 @@ describe('Env', function() { }); it('accepts an async function', function() { - jasmine.getEnv().requireAsyncAwait(); expect(function() { - env.beforeEach(jasmine.getEnv().makeAsyncAwaitFunction()); + env.beforeEach(async function() {}); }).not.toThrow(); }); @@ -621,9 +398,8 @@ describe('Env', function() { }); it('accepts an async function', function() { - jasmine.getEnv().requireAsyncAwait(); expect(function() { - env.beforeAll(jasmine.getEnv().makeAsyncAwaitFunction()); + env.beforeAll(async function() {}); }).not.toThrow(); }); @@ -644,9 +420,8 @@ describe('Env', function() { }); it('accepts an async function', function() { - jasmine.getEnv().requireAsyncAwait(); expect(function() { - env.afterEach(jasmine.getEnv().makeAsyncAwaitFunction()); + env.afterEach(async function() {}); }).not.toThrow(); }); @@ -667,9 +442,8 @@ describe('Env', function() { }); it('accepts an async function', function() { - jasmine.getEnv().requireAsyncAwait(); expect(function() { - env.afterAll(jasmine.getEnv().makeAsyncAwaitFunction()); + env.afterAll(async function() {}); }).not.toThrow(); }); @@ -778,40 +552,7 @@ describe('Env', function() { }); }); - it("deprecates access to 'this' in describes", function() { - jasmine.getEnv().requireProxy(); - var msg = - "Access to 'this' in describe functions (and in arrow " + - 'functions inside describe functions) is deprecated.', - ran = false; - spyOn(env, 'deprecated'); - - env.describe('a suite', function() { - expect(this.description).toEqual('a suite'); - expect(env.deprecated).toHaveBeenCalledWith(msg); - env.deprecated.calls.reset(); - - this.foo = 1; - expect(env.deprecated).toHaveBeenCalledWith(msg); - expect(this.foo).toEqual(1); - env.deprecated.calls.reset(); - - expect(this.getFullName()).toEqual('a suite'); - expect(env.deprecated).toHaveBeenCalledWith(msg); - env.deprecated.calls.reset(); - - env.it('has a spec'); - ran = true; - }); - - expect(ran).toBeTrue(); - }); - - // TODO: Remove this in the next major version. Suites were never meant to be - // exposed via describe 'this' in >= 2.0, and user code should not rely on it. - // This spec is just here to make sure we don't break user code that *does* - // rely on it in older browsers (without Proxy) while deprecating it. - it("sets 'this' to the Suite in describes", function() { + it("does not expose the suite as 'this'", function() { var suiteThis; spyOn(env, 'deprecated'); @@ -820,32 +561,15 @@ describe('Env', function() { env.it('has a spec'); }); - expect(suiteThis).toBeInstanceOf(jasmineUnderTest.Suite); + expect(suiteThis).not.toBeInstanceOf(jasmineUnderTest.Suite); }); describe('#execute', function() { - it('returns a promise when the environment supports promises', function() { - jasmine.getEnv().requirePromises(); + it('returns a promise', function() { expect(env.execute()).toBeInstanceOf(Promise); }); - it('returns a promise when a custom promise constructor is provided', function() { - function CustomPromise() {} - CustomPromise.resolve = function() {}; - CustomPromise.reject = function() {}; - - spyOn(env, 'deprecated'); - env.configure({ Promise: CustomPromise }); - expect(env.execute()).toBeInstanceOf(CustomPromise); - }); - - it('returns undefined when promises are unavailable', function() { - jasmine.getEnv().requireNoPromises(); - expect(env.execute()).toBeUndefined(); - }); - it('should reset the topSuite when run twice', function() { - jasmine.getEnv().requirePromises(); spyOn(jasmineUnderTest.Suite.prototype, 'reset'); return env .execute() // 1 diff --git a/spec/core/ExceptionFormatterSpec.js b/spec/core/ExceptionFormatterSpec.js index 1c4a1c62..f4f15700 100644 --- a/spec/core/ExceptionFormatterSpec.js +++ b/spec/core/ExceptionFormatterSpec.js @@ -225,5 +225,61 @@ describe('ExceptionFormatter', function() { expect(result).toMatch(/error properties:.*someProperty.*hello there/); }); + + describe('When omitMessage is true', function() { + it('filters the message from V8-style stack traces', function() { + const error = { + message: 'nope', + stack: + 'Error: nope\n' + + ' at fn1 (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n' + + ' at fn2 (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' + }; + const subject = new jasmineUnderTest.ExceptionFormatter({ + jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js' + }); + const result = subject.stack(error, { omitMessage: true }); + expect(result).toEqual( + ' at fn1 (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n' + + ' at \n' + + ' at fn4 (http://localhost:8888/__spec__/core/UtilSpec.js:110:19)' + ); + }); + + it('handles Webkit style traces that do not include a message', function() { + const error = { + stack: + 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28\n' + + 'fn1@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' + }; + const subject = new jasmineUnderTest.ExceptionFormatter({ + jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js' + }); + const result = subject.stack(error, { omitMessage: true }); + expect(result).toEqual( + 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28\n' + + '\n' + + 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28' + ); + }); + + it('ensures that stack traces do not include the message in this environment', function() { + let error; + try { + throw new Error('an error'); + } catch (e) { + error = e; + } + const subject = new jasmineUnderTest.ExceptionFormatter({ + jasmineFile: jasmine.util.jasmineFile() + }); + const result = subject.stack(error, { omitMessage: true }); + expect(result).not.toContain('an error'); + }); + }); }); }); diff --git a/spec/core/ExpectationResultSpec.js b/spec/core/ExpectationResultSpec.js index b28818aa..d68b1655 100644 --- a/spec/core/ExpectationResultSpec.js +++ b/spec/core/ExpectationResultSpec.js @@ -50,7 +50,9 @@ describe('buildExpectationResult', function() { stackFormatter: stackFormatter }); - expect(stackFormatter).toHaveBeenCalledWith(fakeError); + expect(stackFormatter).toHaveBeenCalledWith(fakeError, { + omitMessage: true + }); expect(result.stack).toEqual('foo'); }); @@ -66,7 +68,9 @@ describe('buildExpectationResult', function() { stackFormatter: stackFormatter }); - expect(stackFormatter).toHaveBeenCalledWith(fakeError); + expect(stackFormatter).toHaveBeenCalledWith(fakeError, { + omitMessage: true + }); expect(result.stack).toEqual('foo'); }); diff --git a/spec/core/ExpectationSpec.js b/spec/core/ExpectationSpec.js index f0cdfded..ce2b9ae9 100644 --- a/spec/core/ExpectationSpec.js +++ b/spec/core/ExpectationSpec.js @@ -55,43 +55,6 @@ describe('Expectation', function() { expect(matcherFactory).toHaveBeenCalledWith(matchersUtil); }); - // TODO: remove this in the next major release - it('passes custom equality testers when the matcher factory takes two arguments', function() { - var fakeCompare = function() { - return { pass: true }; - }, - matcherFactory = function(matchersUtil, customTesters) { - return { compare: fakeCompare }; - }, - matcherFactorySpy = jasmine - .createSpy('matcher', matcherFactory) - .and.callThrough(), - matchers = { - toFoo: matcherFactorySpy - }, - matchersUtil = { - buildFailureMessage: jasmine.createSpy('buildFailureMessage') - }, - customEqualityTesters = ['a'], - addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation; - - expectation = jasmineUnderTest.Expectation.factory({ - matchersUtil: matchersUtil, - customMatchers: matchers, - customEqualityTesters: customEqualityTesters, - actual: 'an actual', - addExpectationResult: addExpectationResult - }); - - expectation.toFoo('hello'); - - expect(matcherFactorySpy).toHaveBeenCalledWith( - matchersUtil, - customEqualityTesters - ); - }); - it("wraps matchers's compare functions, passing the actual and expected", function() { var fakeCompare = jasmine .createSpy('fake-compare') diff --git a/spec/core/JsApiReporterSpec.js b/spec/core/JsApiReporterSpec.js index d0985a31..ea3e67b7 100644 --- a/spec/core/JsApiReporterSpec.js +++ b/spec/core/JsApiReporterSpec.js @@ -99,7 +99,7 @@ describe('JsApiReporter', function() { }); describe('#suiteResults', function() { - var reporter, suiteResult1, suiteResult2; + var reporter, suiteStarted1, suiteResult1, suiteResult2; beforeEach(function() { reporter = new jasmineUnderTest.JsApiReporter({}); suiteStarted1 = { diff --git a/spec/core/MockDateSpec.js b/spec/core/MockDateSpec.js index 6f6f88df..aaeece54 100644 --- a/spec/core/MockDateSpec.js +++ b/spec/core/MockDateSpec.js @@ -96,24 +96,6 @@ describe('FakeDate', function() { expect(fakeGlobal.Date.now()).toEqual(1000); }); - it("does not stub Date.now() if it doesn't already exist", function() { - var globalDate = jasmine.createSpy('global Date').and.callFake(function() { - return { - getTime: function() { - return 1000; - } - }; - }), - fakeGlobal = { Date: globalDate }, - mockDate = new jasmineUnderTest.MockDate(fakeGlobal); - - mockDate.install(); - - expect(fakeGlobal.Date.now).toThrowError( - 'Browser does not support Date.now()' - ); - }); - it('makes time passes using tick', function() { var globalDate = jasmine.createSpy('global Date').and.callFake(function() { return { diff --git a/spec/core/PrettyPrintSpec.js b/spec/core/PrettyPrintSpec.js index de6a11d6..ed239191 100644 --- a/spec/core/PrettyPrintSpec.js +++ b/spec/core/PrettyPrintSpec.js @@ -18,8 +18,7 @@ describe('PrettyPrinter', function() { describe('stringify sets', function() { it('should stringify sets properly', function() { - jasmine.getEnv().requireFunctioningSets(); - var set = new Set(); // eslint-disable-line compat/compat + var set = new Set(); set.add(1); set.add(2); var pp = jasmineUnderTest.makePrettyPrinter(); @@ -27,12 +26,11 @@ describe('PrettyPrinter', function() { }); it('should truncate sets with more elements than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() { - jasmine.getEnv().requireFunctioningSets(); var originalMaxSize = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; try { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2; - var set = new Set(); // eslint-disable-line compat/compat + var set = new Set(); set.add('a'); set.add('b'); set.add('c'); @@ -46,20 +44,18 @@ describe('PrettyPrinter', function() { describe('stringify maps', function() { it('should stringify maps properly', function() { - jasmine.getEnv().requireFunctioningMaps(); - var map = new Map(); // eslint-disable-line compat/compat + var map = new Map(); map.set(1, 2); var pp = jasmineUnderTest.makePrettyPrinter(); expect(pp(map)).toEqual('Map( [ 1, 2 ] )'); }); it('should truncate maps with more elements than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() { - jasmine.getEnv().requireFunctioningMaps(); var originalMaxSize = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; try { jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2; - var map = new Map(); // eslint-disable-line compat/compat + var map = new Map(); map.set('a', 1); map.set('b', 2); map.set('c', 3); @@ -272,15 +268,13 @@ describe('PrettyPrinter', function() { }); it('should stringify immutable circular objects', function() { - if (Object.freeze) { - var pp = jasmineUnderTest.makePrettyPrinter(); - var frozenObject = { foo: { bar: 'baz' } }; - frozenObject.circular = frozenObject; - frozenObject = Object.freeze(frozenObject); - expect(pp(frozenObject)).toEqual( - "Object({ foo: Object({ bar: 'baz' }), circular: })" - ); - } + var pp = jasmineUnderTest.makePrettyPrinter(); + var frozenObject = { foo: { bar: 'baz' } }; + frozenObject.circular = frozenObject; + frozenObject = Object.freeze(frozenObject); + expect(pp(frozenObject)).toEqual( + "Object({ foo: Object({ bar: 'baz' }), circular: })" + ); }); it('should stringify RegExp objects properly', function() { @@ -299,20 +293,15 @@ describe('PrettyPrinter', function() { it('should indicate getters on objects as such', function() { var pp = jasmineUnderTest.makePrettyPrinter(); - var sampleValue = { id: 1 }; - if (sampleValue.__defineGetter__) { - //not supported in IE! - sampleValue.__defineGetter__('calculatedValue', function() { + var sampleValue = { + id: 1, + get calculatedValue() { throw new Error("don't call me!"); - }); - } - if (sampleValue.__defineGetter__) { - expect(pp(sampleValue)).toEqual( - 'Object({ id: 1, calculatedValue: })' - ); - } else { - expect(pp(sampleValue)).toEqual('Object({ id: 1 })'); - } + } + }; + expect(pp(sampleValue)).toEqual( + 'Object({ id: 1, calculatedValue: })' + ); }); it('should not do HTML escaping of strings', function() { diff --git a/spec/core/QueueRunnerSpec.js b/spec/core/QueueRunnerSpec.js index 302e535e..5adf6ea7 100644 --- a/spec/core/QueueRunnerSpec.js +++ b/spec/core/QueueRunnerSpec.js @@ -18,26 +18,6 @@ describe('QueueRunner', function() { expect(calls).toEqual(['fn1', 'fn2']); }); - it('runs cleanup functions after the others', function() { - var calls = [], - queueableFn1 = { fn: jasmine.createSpy('fn1') }, - queueableFn2 = { fn: jasmine.createSpy('fn2') }, - queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn1], - cleanupFns: [queueableFn2] - }); - queueableFn1.fn.and.callFake(function() { - calls.push('fn1'); - }); - queueableFn2.fn.and.callFake(function() { - calls.push('fn2'); - }); - - queueRunner.execute(); - - expect(calls).toEqual(['fn1', 'fn2']); - }); - it("calls each function with a consistent 'this'-- an empty object", function() { var queueableFn1 = { fn: jasmine.createSpy('fn1') }, queueableFn2 = { fn: jasmine.createSpy('fn2') }, @@ -150,109 +130,31 @@ describe('QueueRunner', function() { }); describe('When next is called with an argument', function() { - describe('that is an Error', function() { - it('explicitly fails and moves to the next function', function() { - var err = new Error('foo'), - queueableFn1 = { - fn: function(done) { - setTimeout(function() { - done(err); - }, 100); - } - }, - queueableFn2 = { fn: jasmine.createSpy('fn2') }, - failFn = jasmine.createSpy('fail'), - queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn1, queueableFn2], - fail: failFn - }); + it('explicitly fails and moves to the next function', function() { + var err = 'anything except undefined', + queueableFn1 = { + fn: function(done) { + setTimeout(function() { + done(err); + }, 100); + } + }, + queueableFn2 = { fn: jasmine.createSpy('fn2') }, + failFn = jasmine.createSpy('fail'), + queueRunner = new jasmineUnderTest.QueueRunner({ + queueableFns: [queueableFn1, queueableFn2], + fail: failFn + }); - queueRunner.execute(); + queueRunner.execute(); - expect(failFn).not.toHaveBeenCalled(); - expect(queueableFn2.fn).not.toHaveBeenCalled(); + expect(failFn).not.toHaveBeenCalled(); + expect(queueableFn2.fn).not.toHaveBeenCalled(); - jasmine.clock().tick(100); + jasmine.clock().tick(100); - expect(failFn).toHaveBeenCalledWith(err); - expect(queueableFn2.fn).toHaveBeenCalled(); - }); - - it('does not log a deprecation', function() { - var err = new Error('foo'), - queueableFn1 = { - fn: function(done) { - setTimeout(function() { - done(err); - }, 100); - } - }, - deprecated = jasmine.createSpy('deprecated'), - queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn1], - deprecated: deprecated - }); - - queueRunner.execute(); - - jasmine.clock().tick(100); - - expect(deprecated).not.toHaveBeenCalled(); - }); - }); - - describe('that is not an Error', function() { - it('logs a deprecation', function() { - var queueableFn1 = { - fn: function(done) { - setTimeout(function() { - done('not an Error'); - }, 100); - } - }, - deprecated = jasmine.createSpy('deprecated'), - queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn1], - deprecated: deprecated - }); - - queueRunner.execute(); - - jasmine.clock().tick(100); - - expect(deprecated).toHaveBeenCalledWith( - 'Any argument passed to a done callback will be treated as an ' + - 'error in a future release. Call the done callback without ' + - "arguments if you don't want to trigger a spec failure." - ); - }); - - it('moves to the next function without failing', function() { - var queueableFn1 = { - fn: function(done) { - setTimeout(function() { - done('not an Error'); - }, 100); - } - }, - queueableFn2 = { fn: jasmine.createSpy('fn2') }, - failFn = jasmine.createSpy('fail'), - queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn1, queueableFn2], - fail: failFn, - deprecated: function() {} - }); - - queueRunner.execute(); - - expect(failFn).not.toHaveBeenCalled(); - expect(queueableFn2.fn).not.toHaveBeenCalled(); - - jasmine.clock().tick(100); - - expect(failFn).not.toHaveBeenCalled(); - expect(queueableFn2.fn).toHaveBeenCalled(); - }); + expect(failFn).toHaveBeenCalledWith(err); + expect(queueableFn2.fn).toHaveBeenCalled(); }); }); @@ -569,20 +471,20 @@ describe('QueueRunner', function() { }, 100); return p1; } - }; - (queueableFn2 = { - fn: function() { - fnCallback(); - setTimeout(function() { - p2.resolveHandler(); - }, 100); - return p2; - } - }), - (queueRunner = new jasmineUnderTest.QueueRunner({ + }, + queueableFn2 = { + fn: function() { + fnCallback(); + setTimeout(function() { + p2.resolveHandler(); + }, 100); + return p2; + } + }, + queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn1, queueableFn2], onComplete: onComplete - })); + }); queueRunner.execute(); expect(fnCallback).not.toHaveBeenCalled(); @@ -626,48 +528,44 @@ describe('QueueRunner', function() { expect(queueableFn2.fn).toHaveBeenCalled(); }); - it('issues a deprecation if the function also takes a parameter', function() { + it('issues an error if the function also takes a parameter', function() { var queueableFn = { fn: function(done) { return new StubPromise(); } }, - deprecated = jasmine.createSpy('deprecated'), + onException = jasmine.createSpy('onException'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [queueableFn], - deprecated: deprecated + onException: onException }); queueRunner.execute(); - expect(deprecated).toHaveBeenCalledWith( + expect(onException).toHaveBeenCalledWith( 'An asynchronous ' + 'before/it/after function took a done callback but also returned a ' + - 'promise. This is not supported and will stop working in the future. ' + + 'promise. ' + 'Either remove the done callback (recommended) or change the function ' + - 'to not return a promise.', - { omitStackTrace: true } + 'to not return a promise.' ); }); - it('issues a more specific deprecation if the function is `async`', function() { - jasmine.getEnv().requireAsyncAwait(); + it('issues a more specific error if the function is `async`', function() { eval('var fn = async function(done){};'); - var deprecated = jasmine.createSpy('deprecated'), + var onException = jasmine.createSpy('onException'), queueRunner = new jasmineUnderTest.QueueRunner({ queueableFns: [{ fn: fn }], - deprecated: deprecated + onException: onException }); queueRunner.execute(); - expect(deprecated).toHaveBeenCalledWith( + expect(onException).toHaveBeenCalledWith( 'An asynchronous ' + 'before/it/after function was defined with the async keyword but ' + - 'also took a done callback. This is not supported and will stop ' + - 'working in the future. Either remove the done callback ' + - '(recommended) or remove the async keyword.', - { omitStackTrace: true } + 'also took a done callback. Either remove the done callback ' + + '(recommended) or remove the async keyword.' ); }); }); @@ -731,6 +629,67 @@ describe('QueueRunner', function() { expect(nextQueueableFn.fn).toHaveBeenCalled(); }); + describe('When configured with a skip policy', function() { + it('instantiates the skip policy', function() { + const SkipPolicy = jasmine.createSpy('SkipPolicy ctor'); + const queueableFns = [{ fn: () => {} }, { fn: () => {} }]; + + new jasmineUnderTest.QueueRunner({ + queueableFns, + SkipPolicy + }); + + expect(SkipPolicy).toHaveBeenCalledWith(queueableFns); + }); + + it('uses the skip policy to determine which fn to run next', function() { + const queueableFns = [ + { fn: jasmine.createSpy('fn0') }, + { fn: jasmine.createSpy('fn1') }, + { fn: jasmine.createSpy('fn2').and.throwError(new Error('nope')) }, + { fn: jasmine.createSpy('fn3') } + ]; + const skipPolicy = jasmine.createSpyObj('skipPolicy', [ + 'skipTo', + 'fnErrored' + ]); + skipPolicy.skipTo.and.callFake(function(lastRanIx) { + return lastRanIx === 0 ? 2 : lastRanIx + 1; + }); + const queueRunner = new jasmineUnderTest.QueueRunner({ + queueableFns, + SkipPolicy: function() { + return skipPolicy; + } + }); + + queueRunner.execute(); + + expect(skipPolicy.skipTo).toHaveBeenCalledWith(0); + expect(skipPolicy.skipTo).toHaveBeenCalledWith(2); + expect(skipPolicy.fnErrored).toHaveBeenCalledWith(2); + expect(queueableFns[0].fn).toHaveBeenCalled(); + expect(queueableFns[1].fn).not.toHaveBeenCalled(); + expect(queueableFns[2].fn).toHaveBeenCalled(); + expect(queueableFns[3].fn).toHaveBeenCalled(); + }); + + it('throws if the skip policy returns the current fn', function() { + const skipPolicy = { skipTo: i => i }; + const queueableFns = [{ fn: () => {} }]; + const queueRunner = new jasmineUnderTest.QueueRunner({ + queueableFns, + SkipPolicy: function() { + return skipPolicy; + } + }); + + expect(function() { + queueRunner.execute(); + }).toThrowError("Can't skip to the same queueable fn that just finished"); + }); + }); + describe('When configured to complete on first error', function() { it('skips to cleanup functions on the first exception', function() { var queueableFn = { @@ -739,13 +698,15 @@ describe('QueueRunner', function() { } }, nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, - cleanupFn = { fn: jasmine.createSpy('cleanup') }, + cleanupFn = { + fn: jasmine.createSpy('cleanup'), + type: 'specCleanup' + }, onComplete = jasmine.createSpy('onComplete'), queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn, nextQueueableFn], - cleanupFns: [cleanupFn], + queueableFns: [queueableFn, nextQueueableFn, cleanupFn], onComplete: onComplete, - completeOnFirstError: true + SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy }); queueRunner.execute(); @@ -761,13 +722,16 @@ describe('QueueRunner', function() { cleanupFn1 = { fn: function() { throw new Error('error'); - } + }, + type: 'afterEach' + }, + cleanupFn2 = { + fn: jasmine.createSpy('cleanupFn2'), + type: 'afterEach' }, - cleanupFn2 = { fn: jasmine.createSpy('cleanupFn2') }, queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn], - cleanupFns: [cleanupFn1, cleanupFn2], - completeOnFirstError: true + queueableFns: [queueableFn, cleanupFn1, cleanupFn2], + SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy }); queueRunner.execute(); @@ -791,7 +755,7 @@ describe('QueueRunner', function() { } }, nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, - cleanupFn = { fn: jasmine.createSpy('cleanup') }, + cleanupFn = { fn: jasmine.createSpy('cleanup'), type: 'specCleanup' }, queueRunner = new jasmineUnderTest.QueueRunner({ globalErrors: { pushListener: function(f) { @@ -801,9 +765,8 @@ describe('QueueRunner', function() { errorListeners.pop(); } }, - queueableFns: [queueableFn, nextQueueableFn], - cleanupFns: [cleanupFn], - completeOnFirstError: true + queueableFns: [queueableFn, nextQueueableFn, cleanupFn], + SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy }), queueableFnDone; @@ -822,11 +785,10 @@ describe('QueueRunner', function() { } }, nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, - cleanupFn = { fn: jasmine.createSpy('cleanup') }, + cleanupFn = { fn: jasmine.createSpy('cleanup'), type: 'specCleanup' }, queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn, nextQueueableFn], - cleanupFns: [cleanupFn], - completeOnFirstError: true + queueableFns: [queueableFn, nextQueueableFn, cleanupFn], + SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy }); queueRunner.execute(); @@ -842,11 +804,13 @@ describe('QueueRunner', function() { } }, nextQueueableFn = { fn: jasmine.createSpy('nextFunction') }, - cleanupFn = { fn: jasmine.createSpy('cleanup') }, + cleanupFn = { + fn: jasmine.createSpy('cleanup'), + type: 'specCleanup' + }, queueRunner = new jasmineUnderTest.QueueRunner({ - queueableFns: [queueableFn, nextQueueableFn], - cleanupFns: [cleanupFn], - completeOnFirstError: true + queueableFns: [queueableFn, nextQueueableFn, cleanupFn], + SkipPolicy: jasmineUnderTest.CompleteOnFirstErrorSkipPolicy }); queueRunner.execute(); diff --git a/spec/core/SkipAfterBeforeAllErrorPolicySpec.js b/spec/core/SkipAfterBeforeAllErrorPolicySpec.js new file mode 100644 index 00000000..455f4381 --- /dev/null +++ b/spec/core/SkipAfterBeforeAllErrorPolicySpec.js @@ -0,0 +1,84 @@ +describe('SkipAfterBeforeAllErrorPolicy', function() { + describe('#skipTo', function() { + describe('When nothing has errored', function() { + it('does not skip anything', function() { + const policy = new jasmineUnderTest.SkipAfterBeforeAllErrorPolicy( + arrayOfArbitraryFns(4) + ); + + expect(policy.skipTo(0)).toEqual(1); + expect(policy.skipTo(1)).toEqual(2); + expect(policy.skipTo(2)).toEqual(3); + expect(policy.skipTo(3)).toEqual(4); + }); + }); + + describe('When anything but a beforeAll has errored', function() { + it('does not skip anything', function() { + const policy = new jasmineUnderTest.SkipAfterBeforeAllErrorPolicy( + arrayOfArbitraryFns(4) + ); + + policy.fnErrored(0); + expect(policy.skipTo(0)).toEqual(1); + policy.fnErrored(1); + expect(policy.skipTo(1)).toEqual(2); + policy.fnErrored(2); + expect(policy.skipTo(2)).toEqual(3); + policy.fnErrored(3); + expect(policy.skipTo(3)).toEqual(4); + }); + }); + + describe('When a beforeAll has errored', function() { + it('skips subsequent functions other than afterAll', function() { + const suite = {}; + const fns = [ + { type: 'beforeAll', fn: () => {}, suite }, + { fn: () => {} }, + { fn: () => {} }, + { type: 'afterAll', fn: () => {} }, + { type: 'afterAll', fn: () => {} } + ]; + const policy = new jasmineUnderTest.SkipAfterBeforeAllErrorPolicy(fns); + + policy.fnErrored(0); + expect(policy.skipTo(0)).toEqual(3); + expect(policy.skipTo(3)).toEqual(4); + }); + }); + }); + + describe('#fnErrored', function() { + describe('When the fn is a beforeAll', function() { + it("sets the suite's hadBeforeAllFailure property to true", function() { + const suite = {}; + const fns = [{ type: 'beforeAll', fn: () => {}, suite }]; + const policy = new jasmineUnderTest.SkipAfterBeforeAllErrorPolicy(fns); + + policy.fnErrored(0); + + expect(suite.hadBeforeAllFailure).toBeTrue(); + }); + }); + + describe('When the fn is not a beforeAll', function() { + it('does not try to access the suite, which is probably not there', function() { + const fns = [{ fn: () => {} /* no suite */ }]; + const policy = new jasmineUnderTest.SkipAfterBeforeAllErrorPolicy(fns); + + expect(() => policy.fnErrored(0)).not.toThrow(); + }); + }); + }); +}); + +function arrayOfArbitraryFns(n) { + const result = []; + + for (let i = 0; i < n; i++) { + result.push({ fn: () => {} }); + } + + return result; +} diff --git a/spec/core/SpecSpec.js b/spec/core/SpecSpec.js index b4dc5742..9efebbdf 100644 --- a/spec/core/SpecSpec.js +++ b/spec/core/SpecSpec.js @@ -61,10 +61,6 @@ describe('Spec', function() { spec.execute(); fakeQueueRunner.calls.mostRecent().args[0].queueableFns[0].fn(); - // TODO: due to some issue with the Pretty Printer, this line fails, but the other two pass. - // This means toHaveBeenCalledWith on IE8 will always be broken. - - // expect(startCallback).toHaveBeenCalledWith(spec); expect(startCallback).toHaveBeenCalled(); expect(startCallback.calls.first().object).toEqual(spec); }); @@ -120,9 +116,13 @@ describe('Spec', function() { expect(options.queueableFns).toEqual([ { fn: jasmine.any(Function) }, before, - queueableFn + queueableFn, + after, + { + fn: jasmine.any(Function), + type: 'specCleanup' + } ]); - expect(options.cleanupFns).toEqual([after, { fn: jasmine.any(Function) }]); }); it("tells the queue runner that it's a leaf node", function() { @@ -175,8 +175,13 @@ describe('Spec', function() { expect(fakeQueueRunner).toHaveBeenCalledWith( jasmine.objectContaining({ onComplete: jasmine.any(Function), - queueableFns: [{ fn: jasmine.any(Function) }], - cleanupFns: [{ fn: jasmine.any(Function) }] + queueableFns: [ + { fn: jasmine.any(Function) }, + { + fn: jasmine.any(Function), + type: 'specCleanup' + } + ] }) ); expect(specBody).not.toHaveBeenCalled(); @@ -184,7 +189,7 @@ describe('Spec', function() { var args = fakeQueueRunner.calls.mostRecent().args[0]; args.queueableFns[0].fn(); expect(startCallback).toHaveBeenCalled(); - args.cleanupFns[0].fn(); + args.queueableFns[args.queueableFns.length - 1].fn(); expect(resultCallback).toHaveBeenCalled(); expect(spec.result.status).toBe('excluded'); @@ -216,7 +221,7 @@ describe('Spec', function() { var args = fakeQueueRunner.calls.mostRecent().args[0]; args.queueableFns[0].fn(); expect(startCallback).toHaveBeenCalled(); - args.cleanupFns[0].fn('things'); + args.queueableFns[1].fn('things'); expect(resultCallback).toHaveBeenCalledWith( { id: spec.id, @@ -228,7 +233,8 @@ describe('Spec', function() { deprecationWarnings: [], pendingReason: '', duration: jasmine.any(Number), - properties: null + properties: null, + debugLogs: null }, 'things' ); @@ -287,9 +293,6 @@ describe('Spec', function() { config.queueableFns.forEach(function(qf) { qf.fn(); }); - config.cleanupFns.forEach(function(qf) { - qf.fn(); - }); config.onComplete(); }, timer: timer @@ -357,7 +360,9 @@ describe('Spec', function() { spec.execute(); - fakeQueueRunner.calls.mostRecent().args[0].cleanupFns[0].fn(); + const fns = fakeQueueRunner.calls.mostRecent().args[0].queueableFns; + fns[fns.length - 1].fn(); + expect(resultCallback.calls.first().args[0].passedExpectations).toEqual([ 'expectation1' ]); @@ -386,7 +391,8 @@ describe('Spec', function() { spec.execute(); - fakeQueueRunner.calls.mostRecent().args[0].cleanupFns[0].fn(); + const fns = fakeQueueRunner.calls.mostRecent().args[0].queueableFns; + fns[fns.length - 1].fn(); expect(resultCallback.calls.first().args[0].passedExpectations).toEqual([ 'passed' ]); @@ -485,7 +491,7 @@ describe('Spec', function() { spec.execute(); var args = fakeQueueRunner.calls.mostRecent().args[0]; - args.cleanupFns[0].fn(); + args.queueableFns[args.queueableFns.length - 1].fn(); expect(resultCallback.calls.first().args[0].failedExpectations).toEqual([ { error: 'foo', @@ -513,15 +519,15 @@ describe('Spec', function() { spec.execute(); var args = fakeQueueRunner.calls.mostRecent().args[0]; - args.cleanupFns[0].fn(); + args.queueableFns[args.queueableFns.length - 1].fn(); expect(resultCallback.calls.first().args[0].failedExpectations).toEqual([]); }); - it('passes an onMultipleDone that logs a deprecation', function() { + it('treats multiple done calls as late errors', function() { var queueRunnerFactory = jasmine.createSpy('queueRunnerFactory'), - deprecated = jasmine.createSpy('depredated'), + onLateError = jasmine.createSpy('onLateError'), spec = new jasmineUnderTest.Spec({ - deprecated: deprecated, + onLateError: onLateError, queueableFn: { fn: function() {} }, queueRunnerFactory: queueRunnerFactory, getSpecName: function() { @@ -534,15 +540,119 @@ describe('Spec', function() { expect(queueRunnerFactory).toHaveBeenCalled(); queueRunnerFactory.calls.argsFor(0)[0].onMultipleDone(); - expect(deprecated).toHaveBeenCalledWith( - "An asynchronous function called its 'done' " + - 'callback more than once. This is a bug in the spec, beforeAll, ' + - 'beforeEach, afterAll, or afterEach function in question. This will ' + - 'be treated as an error in a future version. See' + - ' ' + - 'for more information.\n' + - '(in spec: a spec)', - { ignoreRunnable: true } + expect(onLateError).toHaveBeenCalledTimes(1); + expect(onLateError.calls.argsFor(0)[0]).toBeInstanceOf(Error); + expect(onLateError.calls.argsFor(0)[0].message).toEqual( + 'An asynchronous spec, beforeEach, or afterEach function called its ' + + "'done' callback more than once.\n(in spec: a spec)" ); }); + + describe('#trace', function() { + it('adds the messages to the result', function() { + var timer = jasmine.createSpyObj('timer', ['start', 'elapsed']), + spec = new jasmineUnderTest.Spec({ + queueableFn: { + fn: function() {} + }, + queueRunnerFactory: function() {}, + timer: timer + }), + t1 = 123, + t2 = 456; + + spec.execute(); + expect(spec.result.debugLogs).toBeNull(); + timer.elapsed.and.returnValue(t1); + spec.debugLog('msg 1'); + expect(spec.result.debugLogs).toEqual([ + { message: 'msg 1', timestamp: t1 } + ]); + timer.elapsed.and.returnValue(t2); + spec.debugLog('msg 2'); + expect(spec.result.debugLogs).toEqual([ + { message: 'msg 1', timestamp: t1 }, + { message: 'msg 2', timestamp: t2 } + ]); + }); + + describe('When the spec passes', function() { + it('omits the messages from the reported result', function() { + var resultCallback = jasmine.createSpy('resultCallback'), + spec = new jasmineUnderTest.Spec({ + queueableFn: { + fn: function() {} + }, + resultCallback: resultCallback, + queueRunnerFactory: function(config) { + spec.debugLog('msg'); + for (const fn of config.queueableFns) { + fn.fn(); + } + config.onComplete(false); + } + }); + + spec.execute(function() {}); + expect(resultCallback).toHaveBeenCalledWith( + jasmine.objectContaining({ debugLogs: null }), + undefined + ); + }); + + it('removes the messages to save memory', function() { + var resultCallback = jasmine.createSpy('resultCallback'), + spec = new jasmineUnderTest.Spec({ + queueableFn: { + fn: function() {} + }, + resultCallback: resultCallback, + queueRunnerFactory: function(config) { + spec.debugLog('msg'); + for (const fn of config.queueableFns) { + fn.fn(); + } + config.onComplete(false); + } + }); + + spec.execute(function() {}); + expect(resultCallback).toHaveBeenCalled(); + expect(spec.result.debugLogs).toBeNull(); + }); + }); + + describe('When the spec fails', function() { + it('includes the messages in the reported result', function() { + var resultCallback = jasmine.createSpy('resultCallback'), + timer = jasmine.createSpyObj('timer', ['start', 'elapsed']), + spec = new jasmineUnderTest.Spec({ + queueableFn: { + fn: function() {} + }, + resultCallback: resultCallback, + queueRunnerFactory: function(config) { + spec.debugLog('msg'); + spec.onException(new Error('nope')); + for (const fn of config.queueableFns) { + fn.fn(); + } + config.onComplete(true); + }, + timer: timer + }), + timestamp = 12345; + + timer.elapsed.and.returnValue(timestamp); + + spec.execute(function() {}); + expect(resultCallback).toHaveBeenCalledWith( + jasmine.objectContaining({ + debugLogs: [{ message: 'msg', timestamp: timestamp }] + }), + undefined + ); + }); + }); + }); }); diff --git a/spec/core/SpySpec.js b/spec/core/SpySpec.js index bbe86a66..bfc08e98 100644 --- a/spec/core/SpySpec.js +++ b/spec/core/SpySpec.js @@ -31,12 +31,7 @@ describe('Spies', function() { var fn = function test() {}; var spy = env.createSpy(fn); - // IE doesn't do `.name` - if (fn.name === 'test') { - expect(spy.and.identity).toEqual('test'); - } else { - expect(spy.and.identity).toEqual('unknown'); - } + expect(spy.and.identity).toEqual('test'); }); it('warns the user that we intend to overwrite an existing property', function() { @@ -236,7 +231,7 @@ describe('Spies', function() { expect(spy('baz', 'grault', 'waldo')).toEqual(42); }); - it('uses custom equality testers when selecting a strategy', function() { + it('uses asymmetric equality testers when selecting a strategy', function() { var spy = env.createSpy('foo'); spy.and.returnValue(42); spy.withArgs(jasmineUnderTest.any(String)).and.returnValue(-1); @@ -245,6 +240,23 @@ describe('Spies', function() { expect(spy({})).toEqual(42); }); + it('uses the provided matchersUtil selecting a strategy', function() { + const matchersUtil = new jasmineUnderTest.MatchersUtil({ + customTesters: [ + function(a, b) { + if ((a === 'bar' && b === 'baz') || (a === 'baz' && b === 'bar')) { + return true; + } + } + ] + }); + const spy = new jasmineUnderTest.Spy('aSpy', matchersUtil); + spy.and.returnValue('default strategy return value'); + spy.withArgs('bar').and.returnValue('custom strategy return value'); + expect(spy('foo')).toEqual('default strategy return value'); + expect(spy('baz')).toEqual('custom strategy return value'); + }); + it('can reconfigure an argument-specific strategy', function() { var spy = env.createSpy('foo'); spy.withArgs('foo').and.returnValue(42); @@ -253,9 +265,7 @@ describe('Spies', function() { }); describe('any promise-based strategy', function() { - it('works with global Promise library when available', function(done) { - jasmine.getEnv().requirePromises(); - + it('works with global Promise library', function(done) { var spy = env.createSpy('foo').and.resolveTo(42); spy() .then(function(result) { @@ -264,20 +274,6 @@ describe('Spies', function() { }) .catch(done.fail); }); - - it('works with a custom Promise library', function() { - var customPromise = { - resolve: jasmine.createSpy(), - reject: jasmine.createSpy() - }; - customPromise.resolve.and.returnValue('resolved'); - spyOn(env, 'deprecated'); - env.configure({ Promise: customPromise }); - - var spy = env.createSpy('foo').and.resolveTo(42); - expect(spy()).toEqual('resolved'); - expect(customPromise.resolve).toHaveBeenCalledWith(42); - }); }); describe('when withArgs is used without a base strategy', function() { diff --git a/spec/core/SpyStrategySpec.js b/spec/core/SpyStrategySpec.js index b4beabc1..f8f96920 100644 --- a/spec/core/SpyStrategySpec.js +++ b/spec/core/SpyStrategySpec.js @@ -108,7 +108,6 @@ describe('SpyStrategy', function() { }); it('allows a fake async function to be called instead', function(done) { - jasmine.getEnv().requireAsyncAwait(); var originalFn = jasmine.createSpy('original'), fakeFn = jasmine .createSpy('fake') @@ -131,15 +130,9 @@ describe('SpyStrategy', function() { describe('#resolveTo', function() { it('allows a resolved promise to be returned', function(done) { - jasmine.getEnv().requirePromises(); - var originalFn = jasmine.createSpy('original'), - getPromise = function() { - return Promise; - }, spyStrategy = new jasmineUnderTest.SpyStrategy({ - fn: originalFn, - getPromise: getPromise + fn: originalFn }); spyStrategy.resolveTo(37); @@ -153,15 +146,9 @@ describe('SpyStrategy', function() { }); it('allows an empty resolved promise to be returned', function(done) { - jasmine.getEnv().requirePromises(); - var originalFn = jasmine.createSpy('original'), - getPromise = function() { - return Promise; - }, spyStrategy = new jasmineUnderTest.SpyStrategy({ - fn: originalFn, - getPromise: getPromise + fn: originalFn }); spyStrategy.resolveTo(); @@ -173,30 +160,13 @@ describe('SpyStrategy', function() { }) .catch(done.fail); }); - - it('fails if promises are not available', function() { - var originalFn = jasmine.createSpy('original'), - spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); - - expect(function() { - spyStrategy.resolveTo(37); - }).toThrowError( - 'resolveTo requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`' - ); - }); }); describe('#rejectWith', function() { it('allows a rejected promise to be returned', function(done) { - jasmine.getEnv().requirePromises(); - var originalFn = jasmine.createSpy('original'), - getPromise = function() { - return Promise; - }, spyStrategy = new jasmineUnderTest.SpyStrategy({ - fn: originalFn, - getPromise: getPromise + fn: originalFn }); spyStrategy.rejectWith(new Error('oops')); @@ -211,15 +181,9 @@ describe('SpyStrategy', function() { }); it('allows an empty rejected promise to be returned', function(done) { - jasmine.getEnv().requirePromises(); - var originalFn = jasmine.createSpy('original'), - getPromise = function() { - return Promise; - }, spyStrategy = new jasmineUnderTest.SpyStrategy({ - fn: originalFn, - getPromise: getPromise + fn: originalFn }); spyStrategy.rejectWith(); @@ -234,15 +198,9 @@ describe('SpyStrategy', function() { }); it('allows a non-Error to be rejected', function(done) { - jasmine.getEnv().requirePromises(); - var originalFn = jasmine.createSpy('original'), - getPromise = function() { - return Promise; - }, spyStrategy = new jasmineUnderTest.SpyStrategy({ - fn: originalFn, - getPromise: getPromise + fn: originalFn }); spyStrategy.rejectWith('oops'); @@ -255,17 +213,6 @@ describe('SpyStrategy', function() { }) .catch(done.fail); }); - - it('fails if promises are not available', function() { - var originalFn = jasmine.createSpy('original'), - spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }); - - expect(function() { - spyStrategy.rejectWith(new Error('oops')); - }).toThrowError( - 'rejectWith requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`' - ); - }); }); it('allows a custom strategy to be used', function() { @@ -335,9 +282,9 @@ describe('SpyStrategy', function() { }); it('allows generator functions to be passed to callFake strategy', function() { - jasmine.getEnv().requireGeneratorFunctions(); - - var generator = jasmine.getEnv().makeGeneratorFunction('yield "ok";'), + var generator = function*() { + yield 'ok'; + }, spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: function() {} }); spyStrategy.callFake(generator); diff --git a/spec/core/StackTraceSpec.js b/spec/core/StackTraceSpec.js index d041c8e7..32ccc090 100644 --- a/spec/core/StackTraceSpec.js +++ b/spec/core/StackTraceSpec.js @@ -1,5 +1,5 @@ describe('StackTrace', function() { - it('understands Chrome/IE/Edge style traces', function() { + it('understands Chrome/Edge style traces', function() { var error = { message: 'nope', stack: @@ -30,7 +30,7 @@ describe('StackTrace', function() { ]); }); - it('understands Chrome/IE/Edge style traces with multiline messages', function() { + it('understands Chrome/Edge style traces with multiline messages', function() { var error = { message: 'line 1\nline 2', stack: @@ -95,7 +95,7 @@ describe('StackTrace', function() { ]); }); - it('understands Safari/Firefox/Phantom-OS X style traces', function() { + it('understands Safari <=14/Firefox/Phantom-OS X style traces', function() { var error = { message: 'nope', stack: @@ -122,6 +122,33 @@ describe('StackTrace', function() { ]); }); + it('understands Safari 15 style traces', function() { + var error = { + message: 'nope', + stack: + '@http://localhost:8888/__spec__/core/FooSpec.js:164:24\n' + + 'attempt@http://localhost:8888/__jasmine__/jasmine.js:8074:44\n' + }; + var result = new jasmineUnderTest.StackTrace(error); + + expect(result.message).toBeFalsy(); + expect(result.style).toEqual('webkit'); + expect(result.frames).toEqual([ + { + raw: '@http://localhost:8888/__spec__/core/FooSpec.js:164:24', + func: undefined, + file: 'http://localhost:8888/__spec__/core/FooSpec.js', + line: 164 + }, + { + raw: 'attempt@http://localhost:8888/__jasmine__/jasmine.js:8074:44', + func: 'attempt', + file: 'http://localhost:8888/__jasmine__/jasmine.js', + line: 8074 + } + ]); + }); + it('does not mistake gibberish for Safari/Firefox/Phantom-OS X style traces', function() { var error = { message: 'nope', diff --git a/spec/core/SuiteSpec.js b/spec/core/SuiteSpec.js index d57ae8dd..37317161 100644 --- a/spec/core/SuiteSpec.js +++ b/spec/core/SuiteSpec.js @@ -43,32 +43,83 @@ describe('Suite', function() { expect(suite.getFullName()).toEqual('I am a parent suite I am a suite'); }); - it('adds before functions in order of needed execution', function() { + it('adds beforeEach functions in order of needed execution', function() { var suite = new jasmineUnderTest.Suite({ env: env, description: 'I am a suite' }), - outerBefore = jasmine.createSpy('outerBeforeEach'), - innerBefore = jasmine.createSpy('insideBeforeEach'); + outerBefore = { fn: 'outerBeforeEach' }, + innerBefore = { fn: 'insideBeforeEach' }; suite.beforeEach(outerBefore); suite.beforeEach(innerBefore); - expect(suite.beforeFns).toEqual([innerBefore, outerBefore]); + expect(suite.beforeFns).toEqual([ + { fn: innerBefore.fn, suite }, + { fn: outerBefore.fn, suite } + ]); }); - it('adds after functions in order of needed execution', function() { + it('adds beforeAll functions in order of needed execution', function() { var suite = new jasmineUnderTest.Suite({ env: env, description: 'I am a suite' }), - outerAfter = jasmine.createSpy('outerAfterEach'), - innerAfter = jasmine.createSpy('insideAfterEach'); + outerBefore = { fn: 'outerBeforeAll' }, + innerBefore = { fn: 'insideBeforeAll' }; + + suite.beforeAll(outerBefore); + suite.beforeAll(innerBefore); + + function sameInstance(expected) { + return { + asymmetricMatch: function(actual) { + return actual === expected; + }, + jasmineToString: function() { + return ``; + } + }; + } + + expect(suite.beforeAllFns).toEqual([ + { fn: outerBefore.fn, type: 'beforeAll', suite: sameInstance(suite) }, + { fn: innerBefore.fn, type: 'beforeAll', suite: sameInstance(suite) } + ]); + }); + + it('adds afterEach functions in order of needed execution', function() { + var suite = new jasmineUnderTest.Suite({ + env: env, + description: 'I am a suite' + }), + outerAfter = { fn: 'outerAfterEach' }, + innerAfter = { fn: 'insideAfterEach' }; suite.afterEach(outerAfter); suite.afterEach(innerAfter); - expect(suite.afterFns).toEqual([innerAfter, outerAfter]); + expect(suite.afterFns).toEqual([ + { fn: innerAfter.fn, suite, type: 'afterEach' }, + { fn: outerAfter.fn, suite, type: 'afterEach' } + ]); + }); + + it('adds afterAll functions in order of needed execution', function() { + const suite = new jasmineUnderTest.Suite({ + env: env, + description: 'I am a suite' + }), + outerAfter = { fn: 'outerAfterAll' }, + innerAfter = { fn: 'insideAfterAl' }; + + suite.afterAll(outerAfter); + suite.afterAll(innerAfter); + + expect(suite.afterAllFns).toEqual([ + { fn: innerAfter.fn, type: 'afterAll' }, + { fn: outerAfter.fn, type: 'afterAll' } + ]); }); it('has a status of failed if any expectations have failed', function() { @@ -226,27 +277,27 @@ describe('Suite', function() { }); describe('#onMultipleDone', function() { - it('logs a special deprecation when it is the top suite', function() { - var env = jasmine.createSpyObj('env', ['deprecated']); - var suite = new jasmineUnderTest.Suite({ env: env, parentSuite: null }); + it('reports a special error when it is the top suite', function() { + const onLateError = jasmine.createSpy('onLateError'); + const suite = new jasmineUnderTest.Suite({ + onLateError, + parentSuite: null + }); suite.onMultipleDone(); - expect(env.deprecated).toHaveBeenCalledWith( + expect(onLateError).toHaveBeenCalledTimes(1); + expect(onLateError.calls.argsFor(0)[0]).toBeInstanceOf(Error); + expect(onLateError.calls.argsFor(0)[0].message).toEqual( 'A top-level beforeAll or afterAll function called its ' + - "'done' callback more than once. This is a bug in the beforeAll " + - 'or afterAll function in question. This will be treated as an ' + - 'error in a future version. See' + - ' ' + - 'for more information.', - { ignoreRunnable: true } + "'done' callback more than once." ); }); - it('logs a deprecation including the suite name when it is a normal suite', function() { - var env = jasmine.createSpyObj('env', ['deprecated']); + it('reports an error including the suite name when it is a normal suite', function() { + const onLateError = jasmine.createSpy('onLateError'); var suite = new jasmineUnderTest.Suite({ - env: env, + onLateError, description: 'the suite', parentSuite: { description: 'the parent suite', @@ -256,15 +307,11 @@ describe('Suite', function() { suite.onMultipleDone(); - expect(env.deprecated).toHaveBeenCalledWith( - "An asynchronous function called its 'done' callback more than " + - 'once. This is a bug in the spec, beforeAll, beforeEach, afterAll, ' + - 'or afterEach function in question. This will be treated as an error ' + - 'in a future version. See' + - ' ' + - 'for more information.\n' + - '(in suite: the parent suite the suite)', - { ignoreRunnable: true } + expect(onLateError).toHaveBeenCalledTimes(1); + expect(onLateError.calls.argsFor(0)[0]).toBeInstanceOf(Error); + expect(onLateError.calls.argsFor(0)[0].message).toEqual( + "An asynchronous beforeAll or afterAll function called its 'done' " + + 'callback more than once.\n(in suite: the parent suite the suite)' ); }); }); diff --git a/spec/core/TimerSpec.js b/spec/core/TimerSpec.js index f733f0d9..39d74dc6 100644 --- a/spec/core/TimerSpec.js +++ b/spec/core/TimerSpec.js @@ -14,10 +14,12 @@ describe('Timer', function() { describe('when date is stubbed, perhaps by other testing helpers', function() { var origDate = Date; beforeEach(function() { + // eslint-disable-next-line no-implicit-globals Date = jasmine.createSpy('date spy'); }); afterEach(function() { + // eslint-disable-next-line no-implicit-globals Date = origDate; }); diff --git a/spec/core/TreeProcessorSpec.js b/spec/core/TreeProcessorSpec.js index b494d1ac..c33a0000 100644 --- a/spec/core/TreeProcessorSpec.js +++ b/spec/core/TreeProcessorSpec.js @@ -482,7 +482,10 @@ describe('TreeProcessor', function() { var leaf = new Leaf(), node = new Node({ children: [leaf], - beforeAllFns: ['beforeAll1', 'beforeAll2'] + beforeAllFns: [ + { fn: 'beforeAll1', timeout: 1 }, + { fn: 'beforeAll2', timeout: 2 } + ] }), root = new Node({ children: [node] }), queueRunner = jasmine.createSpy('queueRunner'), @@ -502,17 +505,18 @@ describe('TreeProcessor', function() { expect(queueableFns).toEqual([ { fn: jasmine.any(Function) }, - 'beforeAll1', - 'beforeAll2', + { fn: 'beforeAll1', timeout: 1 }, + { fn: 'beforeAll2', timeout: 2 }, { fn: jasmine.any(Function) } ]); }); it('runs afterAlls for a node with children', function() { var leaf = new Leaf(), + afterAllFns = [{ fn: 'afterAll1' }, { fn: 'afterAll2' }], node = new Node({ children: [leaf], - afterAllFns: ['afterAll1', 'afterAll2'] + afterAllFns }), root = new Node({ children: [node] }), queueRunner = jasmine.createSpy('queueRunner'), @@ -533,15 +537,15 @@ describe('TreeProcessor', function() { expect(queueableFns).toEqual([ { fn: jasmine.any(Function) }, { fn: jasmine.any(Function) }, - 'afterAll1', - 'afterAll2' + afterAllFns[0], + afterAllFns[1] ]); }); it('does not run beforeAlls or afterAlls for a node with no children', function() { var node = new Node({ - beforeAllFns: ['before'], - afterAllFns: ['after'] + beforeAllFns: [{ fn: 'before' }], + afterAllFns: [{ fn: 'after' }] }), root = new Node({ children: [node] }), queueRunner = jasmine.createSpy('queueRunner'), @@ -566,8 +570,8 @@ describe('TreeProcessor', function() { var leaf = new Leaf({ markedPending: true }), node = new Node({ children: [leaf], - beforeAllFns: ['before'], - afterAllFns: ['after'], + beforeAllFns: [{ fn: 'before' }], + afterAllFns: [{ fn: 'after' }], markedPending: false }), root = new Node({ children: [node] }), diff --git a/spec/core/UtilSpec.js b/spec/core/UtilSpec.js index 8e05c6ab..f95d92fc 100644 --- a/spec/core/UtilSpec.js +++ b/spec/core/UtilSpec.js @@ -39,8 +39,7 @@ describe('jasmineUnderTest.util', function() { }; beforeEach(function() { - jasmine.getEnv().requirePromises(); - mockNativePromise = new Promise(function(res, rej) {}); // eslint-disable-line compat/compat + mockNativePromise = new Promise(function(res, rej) {}); mockPromiseLikeObject = new mockPromiseLike(); }); diff --git a/spec/core/asymmetricEqualityTesterArgCompatShimSpec.js b/spec/core/asymmetricEqualityTesterArgCompatShimSpec.js deleted file mode 100644 index 45275f38..00000000 --- a/spec/core/asymmetricEqualityTesterArgCompatShimSpec.js +++ /dev/null @@ -1,197 +0,0 @@ -describe('asymmetricEqualityTesterArgCompatShim', function() { - it('provides all the properties of the MatchersUtil', function() { - var matchersUtil = { - foo: function() {}, - bar: function() {} - }, - shim = jasmineUnderTest.asymmetricEqualityTesterArgCompatShim( - matchersUtil, - [] - ); - - expect(shim.foo).toBe(matchersUtil.foo); - expect(shim.bar).toBe(matchersUtil.bar); - }); - - it('provides and deprecates all the properties of the customEqualityTesters', function() { - var customEqualityTesters = [function() {}, function() {}], - shim = jasmineUnderTest.asymmetricEqualityTesterArgCompatShim( - {}, - customEqualityTesters - ), - deprecated = spyOn(jasmineUnderTest.getEnv(), 'deprecated'), - expectedMessage = - 'The second argument to asymmetricMatch is now a MatchersUtil. ' + - 'Using it as an array of custom equality testers is deprecated and will stop ' + - 'working in a future release. ' + - 'See for details.'; - - expect(shim.length).toBe(2); - expect(deprecated).toHaveBeenCalledWith(expectedMessage); - deprecated.calls.reset(); - - expect(shim[0]).toBe(customEqualityTesters[0]); - expect(deprecated).toHaveBeenCalledWith(expectedMessage); - deprecated.calls.reset(); - - expect(shim[1]).toBe(customEqualityTesters[1]); - expect(deprecated).toHaveBeenCalledWith(expectedMessage); - }); - - it('provides and deprecates all the properties of Array.prototype', function() { - var shim = jasmineUnderTest.asymmetricEqualityTesterArgCompatShim({}, []), - deprecated = spyOn(jasmineUnderTest.getEnv(), 'deprecated'), - expectedMessage = - 'The second argument to asymmetricMatch is now a MatchersUtil. ' + - 'Using it as an array of custom equality testers is deprecated and will stop ' + - 'working in a future release. ' + - 'See for details.'; - - expect(shim.filter).toBe(Array.prototype.filter); - expect(deprecated).toHaveBeenCalledWith(expectedMessage); - deprecated.calls.reset(); - - expect(shim.forEach).toBe(Array.prototype.forEach); - expect(deprecated).toHaveBeenCalledWith(expectedMessage); - deprecated.calls.reset(); - - expect(shim.map).toBe(Array.prototype.map); - expect(deprecated).toHaveBeenCalledWith(expectedMessage); - deprecated.calls.reset(); - }); - - it('provides and deprecates properties of Array.prototype', function() { - var keys = [ - 'concat', - 'every', - 'filter', - 'forEach', - 'indexOf', - 'join', - 'lastIndexOf', - 'length', - 'map', - 'pop', - 'push', - 'reduce', - 'reduceRight', - 'reverse', - 'shift', - 'slice', - 'some', - 'sort', - 'splice', - 'unshift' - ], - optionalKeys = [ - 'copyWithin', - 'entries', - 'fill', - 'find', - 'findIndex', - 'flat', - 'flatMap', - 'includes', - 'keys', - 'values' - ], - shim = jasmineUnderTest.asymmetricEqualityTesterArgCompatShim({}, []), - deprecated = spyOn(jasmineUnderTest.getEnv(), 'deprecated'), - i, - k; - - // Properties that are present on all supported runtimes - for (i = 0; i < keys.length; i++) { - k = keys[i]; - expect(shim[k]) - .withContext(k) - .not.toBeUndefined(); - expect(shim[k]) - .withContext(k) - .toBe(Array.prototype[k]); - expect(deprecated).toHaveBeenCalled(); - deprecated.calls.reset(); - } - - // Properties that are present on only some supported runtimes - for (i = 0; i < optionalKeys.length; i++) { - k = optionalKeys[i]; - - if (shim[k] !== undefined) { - expect(shim[k]) - .withContext(k) - .toBe(Array.prototype[k]); - expect(deprecated) - .withContext(k) - .toHaveBeenCalled(); - deprecated.calls.reset(); - } - } - }); - - it('does not deprecate properties of Object.prototype', function() { - var shim = jasmineUnderTest.asymmetricEqualityTesterArgCompatShim({}, []), - deprecated = spyOn(jasmineUnderTest.getEnv(), 'deprecated'); - - expect(shim.hasOwnProperty).toBe(Object.prototype.hasOwnProperty); - expect(shim.isPrototypeOf).toBe(Object.prototype.isPrototypeOf); - - expect(deprecated).not.toHaveBeenCalled(); - }); - - describe('When Array.prototype additions collide with MatchersUtil methods', function() { - function keys() { - return [ - 'contains', - 'buildFailureMessage', - 'asymmetricDiff_', - 'asymmetricMatch_', - 'equals', - 'eq_' - ]; - } - - beforeEach(function() { - keys().forEach(function(k) { - expect(Array.prototype[k]) - .withContext('Array.prototype already had ' + k) - .toBeUndefined(); - Array.prototype[k] = function() {}; - }); - }); - - afterEach(function() { - keys().forEach(function(k) { - delete Array.prototype[k]; - }); - }); - - it('uses the MatchersUtil methods', function() { - var matchersUtil = new jasmineUnderTest.MatchersUtil({}), - shim = jasmineUnderTest.asymmetricEqualityTesterArgCompatShim( - matchersUtil, - [] - ); - - keys().forEach(function(k) { - expect(shim[k]) - .withContext(k + ' was overwritten') - .toBe(jasmineUnderTest.MatchersUtil.prototype[k]); - }); - }); - }); - - describe('When the matchersUtil is already an asymmetricEqualityTesterArgCompatShim', function() { - it('does not trigger any deprecations', function() { - var shim1 = jasmineUnderTest.asymmetricEqualityTesterArgCompatShim( - {}, - [] - ); - spyOn(jasmineUnderTest.getEnv(), 'deprecated'); - - jasmineUnderTest.asymmetricEqualityTesterArgCompatShim(shim1, []); - - expect(jasmineUnderTest.getEnv().deprecated).not.toHaveBeenCalled(); - }); - }); -}); diff --git a/spec/core/asymmetric_equality/AnySpec.js b/spec/core/asymmetric_equality/AnySpec.js index 4db56f3b..7979dd7c 100644 --- a/spec/core/asymmetric_equality/AnySpec.js +++ b/spec/core/asymmetric_equality/AnySpec.js @@ -30,33 +30,27 @@ describe('Any', function() { }); it('matches a Map', function() { - jasmine.getEnv().requireFunctioningMaps(); - var any = new jasmineUnderTest.Any(Map); - expect(any.asymmetricMatch(new Map())).toBe(true); // eslint-disable-line compat/compat + expect(any.asymmetricMatch(new Map())).toBe(true); }); it('matches a Set', function() { - jasmine.getEnv().requireFunctioningSets(); - var any = new jasmineUnderTest.Any(Set); - expect(any.asymmetricMatch(new Set())).toBe(true); // eslint-disable-line compat/compat + expect(any.asymmetricMatch(new Set())).toBe(true); }); it('matches a TypedArray', function() { var any = new jasmineUnderTest.Any(Uint32Array); - expect(any.asymmetricMatch(new Uint32Array([]))).toBe(true); // eslint-disable-line compat/compat + expect(any.asymmetricMatch(new Uint32Array([]))).toBe(true); }); it('matches a Symbol', function() { - jasmine.getEnv().requireFunctioningSymbols(); + var any = new jasmineUnderTest.Any(Symbol); - var any = new jasmineUnderTest.Any(Symbol); // eslint-disable-line compat/compat - - expect(any.asymmetricMatch(Symbol())).toBe(true); // eslint-disable-line compat/compat + expect(any.asymmetricMatch(Symbol())).toBe(true); }); it('matches another constructed object', function() { diff --git a/spec/core/asymmetric_equality/AnythingSpec.js b/spec/core/asymmetric_equality/AnythingSpec.js index 1463c1a8..e4a3df5f 100644 --- a/spec/core/asymmetric_equality/AnythingSpec.js +++ b/spec/core/asymmetric_equality/AnythingSpec.js @@ -24,33 +24,27 @@ describe('Anything', function() { }); it('matches a Map', function() { - jasmine.getEnv().requireFunctioningMaps(); - var anything = new jasmineUnderTest.Anything(); - expect(anything.asymmetricMatch(new Map())).toBe(true); // eslint-disable-line compat/compat + expect(anything.asymmetricMatch(new Map())).toBe(true); }); it('matches a Set', function() { - jasmine.getEnv().requireFunctioningSets(); - var anything = new jasmineUnderTest.Anything(); - expect(anything.asymmetricMatch(new Set())).toBe(true); // eslint-disable-line compat/compat + expect(anything.asymmetricMatch(new Set())).toBe(true); }); it('matches a TypedArray', function() { var anything = new jasmineUnderTest.Anything(); - expect(anything.asymmetricMatch(new Uint32Array([]))).toBe(true); // eslint-disable-line compat/compat + expect(anything.asymmetricMatch(new Uint32Array([]))).toBe(true); }); it('matches a Symbol', function() { - jasmine.getEnv().requireFunctioningSymbols(); - var anything = new jasmineUnderTest.Anything(); - expect(anything.asymmetricMatch(Symbol())).toBe(true); // eslint-disable-line compat/compat + expect(anything.asymmetricMatch(Symbol())).toBe(true); }); it("doesn't match undefined", function() { diff --git a/spec/core/asymmetric_equality/EmptySpec.js b/spec/core/asymmetric_equality/EmptySpec.js index 03d822be..a99f0458 100644 --- a/spec/core/asymmetric_equality/EmptySpec.js +++ b/spec/core/asymmetric_equality/EmptySpec.js @@ -22,29 +22,27 @@ describe('Empty', function() { }); it('matches an empty map', function() { - jasmine.getEnv().requireFunctioningMaps(); var empty = new jasmineUnderTest.Empty(); - var fullMap = new Map(); // eslint-disable-line compat/compat + var fullMap = new Map(); fullMap.set('thing', 2); - expect(empty.asymmetricMatch(new Map())).toBe(true); // eslint-disable-line compat/compat + expect(empty.asymmetricMatch(new Map())).toBe(true); expect(empty.asymmetricMatch(fullMap)).toBe(false); }); it('matches an empty set', function() { - jasmine.getEnv().requireFunctioningSets(); var empty = new jasmineUnderTest.Empty(); - var fullSet = new Set(); // eslint-disable-line compat/compat + var fullSet = new Set(); fullSet.add(3); - expect(empty.asymmetricMatch(new Set())).toBe(true); // eslint-disable-line compat/compat + expect(empty.asymmetricMatch(new Set())).toBe(true); expect(empty.asymmetricMatch(fullSet)).toBe(false); }); it('matches an empty typed array', function() { var empty = new jasmineUnderTest.Empty(); - expect(empty.asymmetricMatch(new Int16Array())).toBe(true); // eslint-disable-line compat/compat - expect(empty.asymmetricMatch(new Int16Array([1, 2]))).toBe(false); // eslint-disable-line compat/compat + expect(empty.asymmetricMatch(new Int16Array())).toBe(true); + expect(empty.asymmetricMatch(new Int16Array([1, 2]))).toBe(false); }); }); diff --git a/spec/core/asymmetric_equality/MapContainingSpec.js b/spec/core/asymmetric_equality/MapContainingSpec.js index d55c450b..dbee6bf5 100644 --- a/spec/core/asymmetric_equality/MapContainingSpec.js +++ b/spec/core/asymmetric_equality/MapContainingSpec.js @@ -1,33 +1,19 @@ -/* eslint-disable compat/compat */ describe('MapContaining', function() { - function MapI(iterable) { - // for IE11 - var map = new Map(); - iterable.forEach(function(kv) { - map.set(kv[0], kv[1]); - }); - return map; - } - - beforeEach(function() { - jasmine.getEnv().requireFunctioningMaps(); - }); - it('matches any actual map to an empty map', function() { - var actualMap = new MapI([['foo', 'bar']]); + var actualMap = new Map([['foo', 'bar']]); var containing = new jasmineUnderTest.MapContaining(new Map()); expect(containing.asymmetricMatch(actualMap)).toBe(true); }); it('matches when all the key/value pairs in sample have matches in actual', function() { - var actualMap = new MapI([ + var actualMap = new Map([ ['foo', [1, 2, 3]], [{ foo: 'bar' }, 'baz'], ['other', 'any'] ]); - var containingMap = new MapI([[{ foo: 'bar' }, 'baz'], ['foo', [1, 2, 3]]]); + var containingMap = new Map([[{ foo: 'bar' }, 'baz'], ['foo', [1, 2, 3]]]); var containing = new jasmineUnderTest.MapContaining(containingMap); var matchersUtil = new jasmineUnderTest.MatchersUtil(); @@ -35,12 +21,12 @@ describe('MapContaining', function() { }); it('does not match when a key is not in actual', function() { - var actualMap = new MapI([ + var actualMap = new Map([ ['foo', [1, 2, 3]], [{ foo: 'not a bar' }, 'baz'] ]); - var containingMap = new MapI([[{ foo: 'bar' }, 'baz'], ['foo', [1, 2, 3]]]); + var containingMap = new Map([[{ foo: 'bar' }, 'baz'], ['foo', [1, 2, 3]]]); var containing = new jasmineUnderTest.MapContaining(containingMap); var matchersUtil = new jasmineUnderTest.MatchersUtil(); @@ -48,9 +34,9 @@ describe('MapContaining', function() { }); it('does not match when a value is not in actual', function() { - var actualMap = new MapI([['foo', [1, 2, 3]], [{ foo: 'bar' }, 'baz']]); + var actualMap = new Map([['foo', [1, 2, 3]], [{ foo: 'bar' }, 'baz']]); - var containingMap = new MapI([[{ foo: 'bar' }, 'baz'], ['foo', [1, 2]]]); + var containingMap = new Map([[{ foo: 'bar' }, 'baz'], ['foo', [1, 2]]]); var containing = new jasmineUnderTest.MapContaining(containingMap); var matchersUtil = new jasmineUnderTest.MatchersUtil(); @@ -58,13 +44,13 @@ describe('MapContaining', function() { }); it('matches when all the key/value pairs in sample have asymmetric matches in actual', function() { - var actualMap = new MapI([ + var actualMap = new Map([ ['foo1', 'not a bar'], ['foo2', 'bar'], ['baz', [1, 2, 3, 4]] ]); - var containingMap = new MapI([ + var containingMap = new Map([ [jasmineUnderTest.stringMatching(/^foo\d/), 'bar'], ['baz', jasmineUnderTest.arrayContaining([2, 3])] ]); @@ -75,9 +61,9 @@ describe('MapContaining', function() { }); it('does not match when a key in sample has no asymmetric matches in actual', function() { - var actualMap = new MapI([['a-foo1', 'bar'], ['baz', [1, 2, 3, 4]]]); + var actualMap = new Map([['a-foo1', 'bar'], ['baz', [1, 2, 3, 4]]]); - var containingMap = new MapI([ + var containingMap = new Map([ [jasmineUnderTest.stringMatching(/^foo\d/), 'bar'], ['baz', jasmineUnderTest.arrayContaining([2, 3])] ]); @@ -88,9 +74,9 @@ describe('MapContaining', function() { }); it('does not match when a value in sample has no asymmetric matches in actual', function() { - var actualMap = new MapI([['foo1', 'bar'], ['baz', [1, 2, 3, 4]]]); + var actualMap = new Map([['foo1', 'bar'], ['baz', [1, 2, 3, 4]]]); - var containingMap = new MapI([ + var containingMap = new Map([ [jasmineUnderTest.stringMatching(/^foo\d/), 'bar'], ['baz', jasmineUnderTest.arrayContaining([4, 5])] ]); @@ -101,15 +87,15 @@ describe('MapContaining', function() { }); it('matches recursively', function() { - var actualMap = new MapI([ - ['foo', new MapI([['foo1', 1], ['foo2', 2]])], - [new MapI([[1, 'bar1'], [2, 'bar2']]), 'bar'], + var actualMap = new Map([ + ['foo', new Map([['foo1', 1], ['foo2', 2]])], + [new Map([[1, 'bar1'], [2, 'bar2']]), 'bar'], ['other', 'any'] ]); - var containingMap = new MapI([ - ['foo', new jasmineUnderTest.MapContaining(new MapI([['foo1', 1]]))], - [new jasmineUnderTest.MapContaining(new MapI([[2, 'bar2']])), 'bar'] + var containingMap = new Map([ + ['foo', new jasmineUnderTest.MapContaining(new Map([['foo1', 1]]))], + [new jasmineUnderTest.MapContaining(new Map([[2, 'bar2']])), 'bar'] ]); var containing = new jasmineUnderTest.MapContaining(containingMap); var matchersUtil = new jasmineUnderTest.MatchersUtil(); @@ -124,10 +110,8 @@ describe('MapContaining', function() { ? a < 0 && b < 0 : a === b; } - var actualMap = new MapI([['foo', -1]]); - var containing = new jasmineUnderTest.MapContaining( - new MapI([['foo', -2]]) - ); + var actualMap = new Map([['foo', -1]]); + var containing = new jasmineUnderTest.MapContaining(new Map([['foo', -2]])); var matchersUtil = new jasmineUnderTest.MatchersUtil({ customTesters: [tester] }); @@ -136,7 +120,7 @@ describe('MapContaining', function() { }); it('does not match when actual is not a map', function() { - var containingMap = new MapI([['foo', 'bar']]); + var containingMap = new Map([['foo', 'bar']]); expect( new jasmineUnderTest.MapContaining(containingMap).asymmetricMatch('foo') ).toBe(false); diff --git a/spec/core/asymmetric_equality/NotEmptySpec.js b/spec/core/asymmetric_equality/NotEmptySpec.js index 82bcf014..52c4b692 100644 --- a/spec/core/asymmetric_equality/NotEmptySpec.js +++ b/spec/core/asymmetric_equality/NotEmptySpec.js @@ -22,22 +22,20 @@ describe('NotEmpty', function() { }); it('matches a non empty map', function() { - jasmine.getEnv().requireFunctioningMaps(); var notEmpty = new jasmineUnderTest.NotEmpty(); - var fullMap = new Map(); // eslint-disable-line compat/compat + var fullMap = new Map(); fullMap.set('one', 1); - var emptyMap = new Map(); // eslint-disable-line compat/compat + var emptyMap = new Map(); expect(notEmpty.asymmetricMatch(fullMap)).toBe(true); expect(notEmpty.asymmetricMatch(emptyMap)).toBe(false); }); it('matches a non empty set', function() { - jasmine.getEnv().requireFunctioningSets(); var notEmpty = new jasmineUnderTest.NotEmpty(); - var filledSet = new Set(); // eslint-disable-line compat/compat + var filledSet = new Set(); filledSet.add(1); - var emptySet = new Set(); // eslint-disable-line compat/compat + var emptySet = new Set(); expect(notEmpty.asymmetricMatch(filledSet)).toBe(true); expect(notEmpty.asymmetricMatch(emptySet)).toBe(false); @@ -46,7 +44,7 @@ describe('NotEmpty', function() { it('matches a non empty typed array', function() { var notEmpty = new jasmineUnderTest.NotEmpty(); - expect(notEmpty.asymmetricMatch(new Int16Array([1, 2, 3]))).toBe(true); // eslint-disable-line compat/compat - expect(notEmpty.asymmetricMatch(new Int16Array())).toBe(false); // eslint-disable-line compat/compat + expect(notEmpty.asymmetricMatch(new Int16Array([1, 2, 3]))).toBe(true); + expect(notEmpty.asymmetricMatch(new Int16Array())).toBe(false); }); }); diff --git a/spec/core/asymmetric_equality/ObjectContainingSpec.js b/spec/core/asymmetric_equality/ObjectContainingSpec.js index 07b86148..07772047 100644 --- a/spec/core/asymmetric_equality/ObjectContainingSpec.js +++ b/spec/core/asymmetric_equality/ObjectContainingSpec.js @@ -110,16 +110,7 @@ describe('ObjectContaining', function() { var matchersUtil = new jasmineUnderTest.MatchersUtil(); var prototypeObject = { foo: 'fooVal' }; - var obj; - - if (Object.create) { - obj = Object.create(prototypeObject); - } else { - function Foo() {} - Foo.prototype = prototypeObject; - Foo.prototype.constructor = Foo; - obj = new Foo(); - } + var obj = Object.create(prototypeObject); expect(containing.asymmetricMatch(obj, matchersUtil)).toBe(true); }); diff --git a/spec/core/asymmetric_equality/SetContainingSpec.js b/spec/core/asymmetric_equality/SetContainingSpec.js index 37925c46..6c2efc2b 100644 --- a/spec/core/asymmetric_equality/SetContainingSpec.js +++ b/spec/core/asymmetric_equality/SetContainingSpec.js @@ -1,29 +1,15 @@ -/* eslint-disable compat/compat */ describe('SetContaining', function() { - function SetI(iterable) { - // for IE11 - var set = new Set(); - iterable.forEach(function(v) { - set.add(v); - }); - return set; - } - - beforeEach(function() { - jasmine.getEnv().requireFunctioningSets(); - }); - it('matches any actual set to an empty set', function() { - var actualSet = new SetI(['foo', 'bar']); + var actualSet = new Set(['foo', 'bar']); var containing = new jasmineUnderTest.SetContaining(new Set()); expect(containing.asymmetricMatch(actualSet)).toBe(true); }); it('matches when all the values in sample have matches in actual', function() { - var actualSet = new SetI([{ foo: 'bar' }, 'baz', [1, 2, 3]]); + var actualSet = new Set([{ foo: 'bar' }, 'baz', [1, 2, 3]]); - var containingSet = new SetI([[1, 2, 3], { foo: 'bar' }]); + var containingSet = new Set([[1, 2, 3], { foo: 'bar' }]); var containing = new jasmineUnderTest.SetContaining(containingSet); var matchersUtil = new jasmineUnderTest.MatchersUtil(); @@ -31,9 +17,9 @@ describe('SetContaining', function() { }); it('does not match when a value is not in actual', function() { - var actualSet = new SetI([{ foo: 'bar' }, 'baz', [1, 2, 3]]); + var actualSet = new Set([{ foo: 'bar' }, 'baz', [1, 2, 3]]); - var containingSet = new SetI([[1, 2], { foo: 'bar' }]); + var containingSet = new Set([[1, 2], { foo: 'bar' }]); var containing = new jasmineUnderTest.SetContaining(containingSet); var matchersUtil = new jasmineUnderTest.MatchersUtil(); @@ -41,9 +27,9 @@ describe('SetContaining', function() { }); it('matches when all the values in sample have asymmetric matches in actual', function() { - var actualSet = new SetI([[1, 2, 3, 4], 'other', 'foo1']); + var actualSet = new Set([[1, 2, 3, 4], 'other', 'foo1']); - var containingSet = new SetI([ + var containingSet = new Set([ jasmineUnderTest.stringMatching(/^foo\d/), jasmineUnderTest.arrayContaining([2, 3]) ]); @@ -54,9 +40,9 @@ describe('SetContaining', function() { }); it('does not match when a value in sample has no asymmetric matches in actual', function() { - var actualSet = new SetI(['a-foo1', [1, 2, 3, 4], 'other']); + var actualSet = new Set(['a-foo1', [1, 2, 3, 4], 'other']); - var containingSet = new SetI([ + var containingSet = new Set([ jasmine.stringMatching(/^foo\d/), jasmine.arrayContaining([2, 3]) ]); @@ -67,10 +53,10 @@ describe('SetContaining', function() { }); it('matches recursively', function() { - var actualSet = new SetI(['foo', new SetI([1, 'bar', 2]), 'other']); + var actualSet = new Set(['foo', new Set([1, 'bar', 2]), 'other']); - var containingSet = new SetI([ - new jasmineUnderTest.SetContaining(new SetI(['bar'])), + var containingSet = new Set([ + new jasmineUnderTest.SetContaining(new Set(['bar'])), 'foo' ]); var containing = new jasmineUnderTest.SetContaining(containingSet); @@ -86,8 +72,8 @@ describe('SetContaining', function() { ? a < 0 && b < 0 : a === b; } - var actualSet = new SetI(['foo', -1]); - var containing = new jasmineUnderTest.SetContaining(new SetI([-2, 'foo'])); + var actualSet = new Set(['foo', -1]); + var containing = new jasmineUnderTest.SetContaining(new Set([-2, 'foo'])); var matchersUtil = new jasmineUnderTest.MatchersUtil({ customTesters: [tester] }); @@ -96,7 +82,7 @@ describe('SetContaining', function() { }); it('does not match when actual is not a set', function() { - var containingSet = new SetI(['foo']); + var containingSet = new Set(['foo']); expect( new jasmineUnderTest.SetContaining(containingSet).asymmetricMatch('foo') ).toBe(false); diff --git a/spec/core/baseSpec.js b/spec/core/baseSpec.js index 0c6ef23a..703a4f50 100644 --- a/spec/core/baseSpec.js +++ b/spec/core/baseSpec.js @@ -91,8 +91,7 @@ describe('base helpers', function() { describe('isSet', function() { it('returns true when the object is a Set', function() { - jasmine.getEnv().requireFunctioningSets(); - expect(jasmineUnderTest.isSet(new Set())).toBe(true); // eslint-disable-line compat/compat + expect(jasmineUnderTest.isSet(new Set())).toBe(true); }); it('returns false when the object is not a Set', function() { @@ -102,21 +101,38 @@ describe('base helpers', function() { describe('isURL', function() { it('returns true when the object is a URL', function() { - jasmine.getEnv().requireUrls(); - // eslint-disable-next-line compat/compat expect(jasmineUnderTest.isURL(new URL('http://localhost/'))).toBe(true); }); it('returns false when the object is not a URL', function() { - jasmine.getEnv().requireUrls(); expect(jasmineUnderTest.isURL({})).toBe(false); }); }); + describe('isIterable_', function() { + it('returns true when the object is an Array', function() { + expect(jasmineUnderTest.isIterable_([])).toBe(true); + }); + + it('returns true when the object is a Set', function() { + expect(jasmineUnderTest.isIterable_(new Set())).toBe(true); + }); + it('returns true when the object is a Map', function() { + expect(jasmineUnderTest.isIterable_(new Map())).toBe(true); + }); + + it('returns true when the object implements @@iterator', function() { + const myIterable = { [Symbol.iterator]: function() {} }; + expect(jasmineUnderTest.isIterable_(myIterable)).toBe(true); + }); + + it('returns false when the object does not implement @@iterator', function() { + expect(jasmineUnderTest.isIterable_({})).toBe(false); + }); + }); + describe('isPending_', function() { it('returns a promise that resolves to true when the promise is pending', function() { - jasmine.getEnv().requirePromises(); - // eslint-disable-next-line compat/compat var promise = new Promise(function() {}); return expectAsync(jasmineUnderTest.isPending_(promise)).toBeResolvedTo( true @@ -124,8 +140,6 @@ describe('base helpers', function() { }); it('returns a promise that resolves to false when the promise is resolved', function() { - jasmine.getEnv().requirePromises(); - // eslint-disable-next-line compat/compat var promise = Promise.resolve(); return expectAsync(jasmineUnderTest.isPending_(promise)).toBeResolvedTo( false @@ -133,8 +147,6 @@ describe('base helpers', function() { }); it('returns a promise that resolves to false when the promise is rejected', function() { - jasmine.getEnv().requirePromises(); - // eslint-disable-next-line compat/compat var promise = Promise.reject(); return expectAsync(jasmineUnderTest.isPending_(promise)).toBeResolvedTo( false @@ -186,4 +198,14 @@ describe('base helpers', function() { }); }); }); + + describe('debugLog', function() { + it("forwards to the current env's debugLog function", function() { + spyOn(jasmineUnderTest.getEnv(), 'debugLog'); + jasmineUnderTest.debugLog('a message'); + expect(jasmineUnderTest.getEnv().debugLog).toHaveBeenCalledWith( + 'a message' + ); + }); + }); }); diff --git a/spec/core/integration/AsymmetricEqualityTestersSpec.js b/spec/core/integration/AsymmetricEqualityTestersSpec.js index 7ab1c77f..cf71329c 100644 --- a/spec/core/integration/AsymmetricEqualityTestersSpec.js +++ b/spec/core/integration/AsymmetricEqualityTestersSpec.js @@ -122,40 +122,24 @@ describe('Asymmetric equality testers (Integration)', function() { }); describe('mapContaining', function() { - if (jasmine.getEnv().hasFunctioningMaps()) { - verifyPasses(function(env) { - var actual = new Map(); - actual.set('a', '2'); - var expected = new Map(); - expected.set('a', 2); + verifyPasses(function(env) { + var actual = new Map(); + actual.set('a', '2'); + var expected = new Map(); + expected.set('a', 2); - env.addCustomEqualityTester(function(a, b) { - return a.toString() === b.toString(); - }); + env.addCustomEqualityTester(function(a, b) { + return a.toString() === b.toString(); + }); - env.expect(actual).toEqual(jasmineUnderTest.mapContaining(expected)); - }); - } else { - it('passes', function() { - jasmine - .getEnv() - .pending('Browser has incomplete or missing support for Maps'); - }); - } + env.expect(actual).toEqual(jasmineUnderTest.mapContaining(expected)); + }); - if (jasmine.getEnv().hasFunctioningMaps()) { - verifyFails(function(env) { - env - .expect('something') - .toEqual(jasmineUnderTest.mapContaining(new Map())); - }); - } else { - it('fails', function() { - jasmine - .getEnv() - .pending('Browser has incomplete or missing support for Maps'); - }); - } + verifyFails(function(env) { + env + .expect('something') + .toEqual(jasmineUnderTest.mapContaining(new Map())); + }); }); describe('notEmpty', function() { @@ -185,40 +169,24 @@ describe('Asymmetric equality testers (Integration)', function() { }); describe('setContaining', function() { - if (jasmine.getEnv().hasFunctioningSets()) { - verifyPasses(function(env) { - var actual = new Set(); - actual.add('1'); - var expected = new Set(); - actual.add(1); + verifyPasses(function(env) { + var actual = new Set(); + actual.add('1'); + var expected = new Set(); + actual.add(1); - env.addCustomEqualityTester(function(a, b) { - return a.toString() === b.toString(); - }); + env.addCustomEqualityTester(function(a, b) { + return a.toString() === b.toString(); + }); - env.expect(actual).toEqual(jasmineUnderTest.setContaining(expected)); - }); - } else { - it('pases', function() { - jasmine - .getEnv() - .pending('Browser has incomplete or missing support for Sets'); - }); - } + env.expect(actual).toEqual(jasmineUnderTest.setContaining(expected)); + }); - if (jasmine.getEnv().hasFunctioningSets()) { - verifyFails(function(env) { - env - .expect('something') - .toEqual(jasmineUnderTest.setContaining(new Set())); - }); - } else { - it('fails', function() { - jasmine - .getEnv() - .pending('Browser has incomplete or missing support for Sets'); - }); - } + verifyFails(function(env) { + env + .expect('something') + .toEqual(jasmineUnderTest.setContaining(new Set())); + }); }); describe('stringMatching', function() { diff --git a/spec/core/integration/CustomAsyncMatchersSpec.js b/spec/core/integration/CustomAsyncMatchersSpec.js index 92eeaa35..36fe3fde 100644 --- a/spec/core/integration/CustomAsyncMatchersSpec.js +++ b/spec/core/integration/CustomAsyncMatchersSpec.js @@ -1,4 +1,3 @@ -/* eslint-disable compat/compat */ describe('Custom Async Matchers (Integration)', function() { var env; @@ -12,8 +11,6 @@ describe('Custom Async Matchers (Integration)', function() { }); it('passes the spec if the custom async matcher passes', function(done) { - jasmine.getEnv().requirePromises(); - env.it('spec using custom async matcher', function() { env.addAsyncMatchers({ toBeReal: function() { @@ -37,8 +34,6 @@ describe('Custom Async Matchers (Integration)', function() { }); it('uses the negative compare function for a negative comparison, if provided', function(done) { - jasmine.getEnv().requirePromises(); - env.it('spec with custom negative comparison matcher', function() { env.addAsyncMatchers({ toBeReal: function() { @@ -65,8 +60,6 @@ describe('Custom Async Matchers (Integration)', function() { }); it('generates messages with the same rules as built in matchers absent a custom message', function(done) { - jasmine.getEnv().requirePromises(); - env.it('spec with an expectation', function() { env.addAsyncMatchers({ toBeReal: function() { @@ -92,8 +85,6 @@ describe('Custom Async Matchers (Integration)', function() { }); it('passes the jasmine utility to the matcher factory', function(done) { - jasmine.getEnv().requirePromises(); - var matcherFactory = function(util) { return { compare: function() { @@ -124,56 +115,7 @@ describe('Custom Async Matchers (Integration)', function() { env.execute(null, done); }); - // TODO: remove this in the next major release. - describe('When a matcher factory takes at least two arguments', function() { - it('passes the jasmine utility and current equality testers to the matcher factory', function(done) { - jasmine.getEnv().requirePromises(); - - var matcherFactory = function(util, customTesters) { - return { - compare: function() { - return Promise.resolve({ pass: true }); - } - }; - }, - matcherFactorySpy = jasmine.createSpy( - 'matcherFactorySpy', - matcherFactory - ), - customEqualityFn = function() { - return true; - }; - - env.it('spec with expectation', function() { - env.addCustomEqualityTester(customEqualityFn); - env.addAsyncMatchers({ - toBeReal: matcherFactorySpy - }); - - return env.expectAsync(true).toBeReal(); - }); - - var specExpectations = function() { - expect(matcherFactorySpy).toHaveBeenCalledWith( - jasmine.any(jasmineUnderTest.MatchersUtil), - [customEqualityFn] - ); - }; - - spyOn(env, 'deprecated'); - env.addReporter({ - specDone: specExpectations, - jasmineDone: function() { - done(); - } - }); - env.execute(); - }); - }); - it('provides custom equality testers to the matcher factory via matchersUtil', function(done) { - jasmine.getEnv().requirePromises(); - var matcherFactory = function(matchersUtil) { return { compare: function(actual, expected) { @@ -206,41 +148,4 @@ describe('Custom Async Matchers (Integration)', function() { env.addReporter({ specDone: specExpectations }); env.execute(null, done); }); - - it('logs a distinct deprecation for each matcher if the matcher factory takes two arguments', function(done) { - var matcherFactory = function(matchersUtil, customEqualityTesters) { - return { compare: function() {} }; - }; - - spyOn(env, 'deprecated'); - - env.beforeEach(function() { - env.addAsyncMatchers({ toBeFoo: matcherFactory }); - env.addAsyncMatchers({ toBeBar: matcherFactory }); - }); - - env.it('a spec', function() {}); - env.it('another spec', function() {}); - - function jasmineDone() { - expect(env.deprecated).toHaveBeenCalledWith( - jasmine.stringMatching( - 'The matcher factory for "toBeFoo" accepts custom equality testers, ' + - 'but this parameter will no longer be passed in a future release. ' + - 'See for details.' - ) - ); - expect(env.deprecated).toHaveBeenCalledWith( - jasmine.stringMatching( - 'The matcher factory for "toBeBar" accepts custom equality testers, ' + - 'but this parameter will no longer be passed in a future release. ' + - 'See for details.' - ) - ); - done(); - } - - env.addReporter({ jasmineDone: jasmineDone }); - env.execute(); - }); }); diff --git a/spec/core/integration/CustomMatchersSpec.js b/spec/core/integration/CustomMatchersSpec.js index 66048a19..5bd990f8 100644 --- a/spec/core/integration/CustomMatchersSpec.js +++ b/spec/core/integration/CustomMatchersSpec.js @@ -108,44 +108,7 @@ describe('Custom Matchers (Integration)', function() { env.execute(null, done); }); - it('supports asymmetric equality testers that take a list of custom equality testers', function(done) { - // TODO: remove this in the next major release. - spyOn(jasmineUnderTest, 'getEnv').and.returnValue(env); - spyOn(env, 'deprecated'); // suppress warnings - - env.it('spec using custom asymmetric equality tester', function() { - var customEqualityFn = function(a, b) { - if (a === 2 && b === 'two') { - return true; - } - }; - var arrayWithFirstElement = function(sample) { - return { - asymmetricMatch: function(actual, customEqualityTesters) { - return jasmineUnderTest.matchersUtil.equals( - sample, - actual[0], - customEqualityTesters - ); - } - }; - }; - - env.addCustomEqualityTester(customEqualityFn); - env.expect(['two']).toEqual(arrayWithFirstElement(2)); - }); - - var specExpectations = function(result) { - expect(result.status).toEqual('passed'); - }; - - env.addReporter({ specDone: specExpectations }); - env.execute(null, done); - }); - it('displays an appropriate failure message if a custom equality matcher fails', function(done) { - spyOn(env, 'deprecated'); - env.it('spec using custom equality matcher', function() { var customEqualityFn = function(a, b) { // "foo" is not equal to anything @@ -277,52 +240,6 @@ describe('Custom Matchers (Integration)', function() { env.execute(null, done); }); - // TODO: remove this in the next major release. - describe('When a matcher factory takes at least two arguments', function() { - it('passes the jasmine utility and current equality testers to the matcher factory', function(done) { - spyOn(env, 'deprecated'); - - var matcherFactory = function(util, customTesters) { - return { - compare: function() { - return { pass: true }; - } - }; - }, - matcherFactorySpy = jasmine.createSpy( - 'matcherFactorySpy', - matcherFactory - ), - customEqualityFn = function() { - return true; - }; - - env.it('spec with expectation', function() { - env.addCustomEqualityTester(customEqualityFn); - env.addMatchers({ - toBeReal: matcherFactorySpy - }); - - env.expect(true).toBeReal(); - }); - - var specExpectations = function() { - expect(matcherFactorySpy).toHaveBeenCalledWith( - jasmine.any(jasmineUnderTest.MatchersUtil), - [customEqualityFn] - ); - }; - - env.addReporter({ - specDone: specExpectations, - jasmineDone: function() { - done(); - } - }); - env.execute(); - }); - }); - it('provides custom equality testers to the matcher factory via matchersUtil', function(done) { var matcherFactory = function(matchersUtil) { return { @@ -354,41 +271,4 @@ describe('Custom Matchers (Integration)', function() { env.addReporter({ specDone: specExpectations }); env.execute(null, done); }); - - it('logs a distinct deprecation per matcher if the matcher factory takes two arguments', function(done) { - var matcherFactory = function(matchersUtil, customEqualityTesters) { - return { compare: function() {} }; - }; - - spyOn(env, 'deprecated'); - - env.beforeEach(function() { - env.addMatchers({ toBeFoo: matcherFactory }); - env.addMatchers({ toBeBar: matcherFactory }); - }); - - env.it('a spec', function() {}); - env.it('another spec', function() {}); - - function jasmineDone() { - expect(env.deprecated).toHaveBeenCalledWith( - jasmine.stringMatching( - 'The matcher factory for "toBeFoo" accepts custom equality testers, ' + - 'but this parameter will no longer be passed in a future release. ' + - 'See for details.' - ) - ); - expect(env.deprecated).toHaveBeenCalledWith( - jasmine.stringMatching( - 'The matcher factory for "toBeBar" accepts custom equality testers, ' + - 'but this parameter will no longer be passed in a future release. ' + - 'See for details.' - ) - ); - done(); - } - - env.addReporter({ jasmineDone: jasmineDone }); - env.execute(); - }); }); diff --git a/spec/core/integration/CustomSpyStrategiesSpec.js b/spec/core/integration/CustomSpyStrategiesSpec.js index 92372c3f..676b00a7 100644 --- a/spec/core/integration/CustomSpyStrategiesSpec.js +++ b/spec/core/integration/CustomSpyStrategiesSpec.js @@ -10,13 +10,12 @@ describe('Custom Spy Strategies (Integration)', function() { env.cleanup_(); }); - it('allows adding more strategies local to a suite', function(done) { + it('allows adding more strategies local to a suite', async function() { var plan = jasmine.createSpy('custom strategy plan').and.returnValue(42); var strategy = jasmine.createSpy('custom strategy').and.returnValue(plan); - var jasmineDone = jasmine.createSpy('jasmineDone'); env.describe('suite defining a custom spy strategy', function() { - env.beforeEach(function() { + env.beforeAll(function() { env.addSpyStrategy('frobnicate', strategy); }); @@ -32,20 +31,13 @@ describe('Custom Spy Strategies (Integration)', function() { expect(env.createSpy('something').and.frobnicate).toBeUndefined(); }); - function expectations() { - var result = jasmineDone.calls.argsFor(0)[0]; - expect(result.overallStatus).toEqual('passed'); - done(); - } - - env.addReporter({ jasmineDone: jasmineDone }); - env.execute(null, expectations); + const result = await env.execute(); + expect(result.overallStatus).toEqual('passed'); }); - it('allows adding more strategies local to a spec', function(done) { + it('allows adding more strategies local to a spec', async function() { var plan = jasmine.createSpy('custom strategy plan').and.returnValue(42); var strategy = jasmine.createSpy('custom strategy').and.returnValue(plan); - var jasmineDone = jasmine.createSpy('jasmineDone'); env.it('spec defining a custom spy strategy', function() { env.addSpyStrategy('frobnicate', strategy); @@ -59,20 +51,13 @@ describe('Custom Spy Strategies (Integration)', function() { expect(env.createSpy('something').and.frobnicate).toBeUndefined(); }); - function expectations() { - var result = jasmineDone.calls.argsFor(0)[0]; - expect(result.overallStatus).toEqual('passed'); - done(); - } - - env.addReporter({ jasmineDone: jasmineDone }); - env.execute(null, expectations); + const result = await env.execute(); + expect(result.overallStatus).toEqual('passed'); }); - it('allows using custom strategies on a per-argument basis', function(done) { + it('allows using custom strategies on a per-argument basis', async function() { var plan = jasmine.createSpy('custom strategy plan').and.returnValue(42); var strategy = jasmine.createSpy('custom strategy').and.returnValue(plan); - var jasmineDone = jasmine.createSpy('jasmineDone'); env.it('spec defining a custom spy strategy', function() { env.addSpyStrategy('frobnicate', strategy); @@ -92,23 +77,16 @@ describe('Custom Spy Strategies (Integration)', function() { expect(env.createSpy('something').and.frobnicate).toBeUndefined(); }); - function expectations() { - var result = jasmineDone.calls.argsFor(0)[0]; - expect(result.overallStatus).toEqual('passed'); - done(); - } - - env.addReporter({ jasmineDone: jasmineDone }); - env.execute(null, expectations); + const result = await env.execute(); + expect(result.overallStatus).toEqual('passed'); }); - it('allows multiple custom strategies to be used', function(done) { + it('allows multiple custom strategies to be used', async function() { var plan1 = jasmine.createSpy('plan 1').and.returnValue(42), strategy1 = jasmine.createSpy('strat 1').and.returnValue(plan1), plan2 = jasmine.createSpy('plan 2').and.returnValue(24), strategy2 = jasmine.createSpy('strat 2').and.returnValue(plan2), - specDone = jasmine.createSpy('specDone'), - jasmineDone = jasmine.createSpy('jasmineDone'); + specDone = jasmine.createSpy('specDone'); env.beforeEach(function() { env.addSpyStrategy('frobnicate', strategy1); @@ -133,14 +111,9 @@ describe('Custom Spy Strategies (Integration)', function() { expect(plan2).toHaveBeenCalled(); }); - function expectations() { - var result = jasmineDone.calls.argsFor(0)[0]; - expect(result.overallStatus).toEqual('passed'); - expect(specDone.calls.count()).toBe(2); - done(); - } - - env.addReporter({ jasmineDone: jasmineDone, specDone: specDone }); - env.execute(null, expectations); + env.addReporter({ specDone: specDone }); + const result = await env.execute(); + expect(result.overallStatus).toEqual('passed'); + expect(specDone.calls.count()).toBe(2); }); }); diff --git a/spec/core/integration/DefaultSpyStrategySpec.js b/spec/core/integration/DefaultSpyStrategySpec.js index 3f17a1d4..87325817 100644 --- a/spec/core/integration/DefaultSpyStrategySpec.js +++ b/spec/core/integration/DefaultSpyStrategySpec.js @@ -10,7 +10,7 @@ describe('Default Spy Strategy (Integration)', function() { env.cleanup_(); }); - it('allows defining a default spy strategy', function(done) { + it('allows defining a default spy strategy', async function() { env.describe('suite with default strategy', function() { env.beforeEach(function() { env.setDefaultSpyStrategy(function(and) { @@ -29,18 +29,11 @@ describe('Default Spy Strategy (Integration)', function() { expect(spy()).toBeUndefined(); }); - function expectations() { - var result = jasmineDone.calls.argsFor(0)[0]; - expect(result.overallStatus).toEqual('passed'); - done(); - } - - var jasmineDone = jasmine.createSpy('jasmineDone'); - env.addReporter({ jasmineDone: jasmineDone }); - env.execute(null, expectations); + const result = await env.execute(); + expect(result.overallStatus).toEqual('passed'); }); - it('uses the default spy strategy defined when the spy is created', function(done) { + it('uses the default spy strategy defined when the spy is created', async function() { env.it('spec', function() { var a = env.createSpy('a'); env.setDefaultSpyStrategy(function(and) { @@ -67,14 +60,7 @@ describe('Default Spy Strategy (Integration)', function() { expect(d.and.isConfigured()).toBe(false); }); - function expectations() { - var result = jasmineDone.calls.argsFor(0)[0]; - expect(result.overallStatus).toEqual('passed'); - done(); - } - - var jasmineDone = jasmine.createSpy('jasmineDone'); - env.addReporter({ jasmineDone: jasmineDone }); - env.execute(null, expectations); + const result = await env.execute(); + expect(result.overallStatus).toEqual('passed'); }); }); diff --git a/spec/core/integration/EnvSpec.js b/spec/core/integration/EnvSpec.js index 83002c5b..14d9e759 100644 --- a/spec/core/integration/EnvSpec.js +++ b/spec/core/integration/EnvSpec.js @@ -156,10 +156,6 @@ describe('Env integration', function() { message: 'Failed: error message', stack: { asymmetricMatch: function(other) { - if (!other) { - // IE doesn't give us a stacktrace so just ignore it. - return true; - } var split = other.split('\n'), firstLine = split[0]; if (firstLine.indexOf('error message') >= 0) { @@ -513,19 +509,13 @@ describe('Env integration', function() { env.execute(null, assertions); }); - it('deprecates multiple calls to done in the top suite', function(done) { + it('reports multiple calls to done in the top suite as errors', function(done) { var reporter = jasmine.createSpyObj('fakeReporter', ['jasmineDone']); var message = 'A top-level beforeAll or afterAll function called its ' + - "'done' callback more than once. This is a bug in the beforeAll " + - 'or afterAll function in question. This will be treated as an ' + - 'error in a future version. See' + - ' ' + - 'for more information.'; + "'done' callback more than once."; - spyOn(console, 'error'); env.addReporter(reporter); - env.configure({ verboseDeprecations: true }); env.beforeAll(function(innerDone) { innerDone(); innerDone(); @@ -537,33 +527,29 @@ describe('Env integration', function() { }); env.execute(null, function() { - var warnings; expect(reporter.jasmineDone).toHaveBeenCalled(); - warnings = reporter.jasmineDone.calls.argsFor(0)[0].deprecationWarnings; - expect(warnings.length).toEqual(2); - expect(warnings[0]) + const errors = reporter.jasmineDone.calls.argsFor(0)[0] + .failedExpectations; + expect(errors.length).toEqual(2); + expect(errors[0].message) .withContext('top beforeAll') - .toEqual(jasmine.objectContaining({ message: message })); - expect(warnings[1]) + .toContain(message); + expect(errors[0].globalErrorType).toEqual('lateError'); + expect(errors[1].message) .withContext('top afterAll') - .toEqual(jasmine.objectContaining({ message: message })); + .toContain(message); + expect(errors[1].globalErrorType).toEqual('lateError'); done(); }); }); - it('deprecates multiple calls to done in a non-top suite', function(done) { + it('reports multiple calls to done in a non-top suite as errors', function(done) { var reporter = jasmine.createSpyObj('fakeReporter', ['jasmineDone']); var message = - "An asynchronous function called its 'done' " + - 'callback more than once. This is a bug in the spec, beforeAll, ' + - 'beforeEach, afterAll, or afterEach function in question. This will ' + - 'be treated as an error in a future version. See' + - ' ' + - 'for more information.'; + "An asynchronous beforeAll or afterAll function called its 'done' " + + 'callback more than once.\n(in suite: a suite)'; - spyOn(console, 'error'); env.addReporter(reporter); - env.configure({ verboseDeprecations: true }); env.describe('a suite', function() { env.beforeAll(function(innerDone) { innerDone(); @@ -577,42 +563,29 @@ describe('Env integration', function() { }); env.execute(null, function() { - var warnings; expect(reporter.jasmineDone).toHaveBeenCalled(); - warnings = reporter.jasmineDone.calls.argsFor(0)[0].deprecationWarnings; - expect(warnings.length).toEqual(2); - expect(warnings[0]) + const errors = reporter.jasmineDone.calls.argsFor(0)[0] + .failedExpectations; + expect(errors.length).toEqual(2); + expect(errors[0].message) .withContext('suite beforeAll') - .toEqual( - jasmine.objectContaining({ - message: message + '\n(in suite: a suite)' - }) - ); - expect(warnings[1]) + .toContain(message); + expect(errors[0].globalErrorType).toEqual('lateError'); + expect(errors[1].message) .withContext('suite afterAll') - .toEqual( - jasmine.objectContaining({ - message: message + '\n(in suite: a suite)' - }) - ); + .toContain(message); + expect(errors[1].globalErrorType).toEqual('lateError'); done(); }); }); - it('deprecates multiple calls to done in a spec', function(done) { + it('reports multiple calls to done in a spec as errors', function(done) { var reporter = jasmine.createSpyObj('fakeReporter', ['jasmineDone']); var message = - "An asynchronous function called its 'done' " + - 'callback more than once. This is a bug in the spec, beforeAll, ' + - 'beforeEach, afterAll, or afterEach function in question. This will ' + - 'be treated as an error in a future version. See' + - ' ' + - 'for more information.\n' + - '(in spec: a suite a spec)'; + 'An asynchronous spec, beforeEach, or afterEach function called its ' + + "'done' callback more than once.\n(in spec: a suite a spec)"; - spyOn(console, 'error'); env.addReporter(reporter); - env.configure({ verboseDeprecations: true }); env.describe('a suite', function() { env.beforeEach(function(innerDone) { innerDone(); @@ -629,33 +602,30 @@ describe('Env integration', function() { }); env.execute(null, function() { - var warnings; expect(reporter.jasmineDone).toHaveBeenCalled(); - warnings = reporter.jasmineDone.calls.argsFor(0)[0].deprecationWarnings; - expect(warnings.length).toEqual(3); - expect(warnings[0]) - .withContext('warning caused by beforeEach') - .toEqual(jasmine.objectContaining({ message: message })); - expect(warnings[1]) - .withContext('warning caused by it') - .toEqual(jasmine.objectContaining({ message: message })); - expect(warnings[2]) - .withContext('warning caused by afterEach') - .toEqual(jasmine.objectContaining({ message: message })); + const errors = reporter.jasmineDone.calls.argsFor(0)[0] + .failedExpectations; + expect(errors.length).toEqual(3); + expect(errors[0].message) + .withContext('error caused by beforeEach') + .toContain(message); + expect(errors[0].globalErrorType).toEqual('lateError'); + expect(errors[1].message) + .withContext('error caused by it') + .toContain(message); + expect(errors[1].globalErrorType).toEqual('lateError'); + expect(errors[2].message) + .withContext('error caused by afterEach') + .toContain(message); + expect(errors[2].globalErrorType).toEqual('lateError'); done(); }); }); - it('deprecates multiple calls to done in reporters', function(done) { + it('reports multiple calls to done in reporters as errors', function(done) { var message = "An asynchronous reporter callback called its 'done' callback more " + - 'than once. This is a bug in the reporter callback in question. This ' + - 'will be treated as an error in a future version. See' + - ' ' + - 'for more information.\nNote: This message ' + - 'will be shown only once. Set the verboseDeprecations config property ' + - 'to true to see every occurrence.'; - + 'than once.'; var reporter = jasmine.createSpyObj('fakeReport', ['jasmineDone']); reporter.specDone = function(result, done) { done(); @@ -665,19 +635,18 @@ describe('Env integration', function() { env.it('a spec', function() {}); - spyOn(console, 'error'); env.execute(null, function() { expect(reporter.jasmineDone).toHaveBeenCalled(); - warnings = reporter.jasmineDone.calls.argsFor(0)[0].deprecationWarnings; - expect(warnings.length).toEqual(1); - expect(warnings[0]).toEqual( - jasmine.objectContaining({ message: message }) - ); + const errors = reporter.jasmineDone.calls.argsFor(0)[0] + .failedExpectations; + expect(errors.length).toEqual(1); + expect(errors[0].message).toContain(message); + expect(errors[0].globalErrorType).toEqual('lateError'); done(); }); }); - it('does not deprecate a call to done that comes after a timeout', function(done) { + it('does not report an error for a call to done that comes after a timeout', function(done) { var reporter = jasmine.createSpyObj('fakeReporter', ['jasmineDone']), firstSpecDone; @@ -700,7 +669,7 @@ describe('Env integration', function() { env.execute(null, function() { expect(reporter.jasmineDone).toHaveBeenCalledWith( jasmine.objectContaining({ - deprecationWarnings: [] + failedExpectations: [] }) ); done(); @@ -1259,42 +1228,6 @@ describe('Env integration', function() { }); }); - it('logs a deprecation warning when the mock clock is ticked reentrantly', function(done) { - var ticked = false, - env = jasmineUnderTest.getEnv(); - spyOn(env, 'deprecated'); - - env.beforeEach(function() { - env.clock.install(); - }); - - env.afterEach(function() { - env.clock.uninstall(); - }); - - env.it('ticks inside tick', function() { - setTimeout(function() { - ticked = true; - env.clock.tick(); - }, 1); - - env.clock.tick(1); - }); - - env.execute(null, function() { - expect(ticked).toBeTrue(); - expect(env.deprecated).toHaveBeenCalledWith( - 'The behavior of reentrant calls to jasmine.clock().tick() will ' + - 'change in a future version. Either modify the affected spec to ' + - 'not call tick() from within a setTimeout or setInterval handler, ' + - 'or be aware that it may behave differently in the future. See ' + - ' ' + - 'for details.' - ); - done(); - }); - }); - it('should run async specs in order, waiting for them to complete', function(done) { var mutatedVar; @@ -2282,6 +2215,7 @@ describe('Env integration', function() { } catch (e) { exception = e; } + env.it('has a test', function() {}); }); env.execute(null, function() { @@ -2905,7 +2839,7 @@ describe('Env integration', function() { expect(result.deprecationWarnings).toEqual([ jasmine.objectContaining({ message: topLevelError.message, - stack: exceptionFormatter.stack(topLevelError) + stack: exceptionFormatter.stack(topLevelError, { omitMessage: true }) }) ]); @@ -2915,7 +2849,9 @@ describe('Env integration', function() { deprecationWarnings: [ jasmine.objectContaining({ message: suiteLevelError.message, - stack: exceptionFormatter.stack(suiteLevelError) + stack: exceptionFormatter.stack(suiteLevelError, { + omitMessage: true + }) }) ] }) @@ -2927,7 +2863,9 @@ describe('Env integration', function() { deprecationWarnings: [ jasmine.objectContaining({ message: specLevelError.message, - stack: exceptionFormatter.stack(specLevelError) + stack: exceptionFormatter.stack(specLevelError, { + omitMessage: true + }) }) ] }) @@ -2938,8 +2876,6 @@ describe('Env integration', function() { }); it('supports async matchers', function(done) { - jasmine.getEnv().requirePromises(); - var specDone = jasmine.createSpy('specDone'), suiteDone = jasmine.createSpy('suiteDone'), jasmineDone = jasmine.createSpy('jasmineDone'); @@ -2952,7 +2888,6 @@ describe('Env integration', function() { function fail(innerDone) { var resolve; - // eslint-disable-next-line compat/compat var p = new Promise(function(res, rej) { resolve = res; }); @@ -3004,7 +2939,9 @@ describe('Env integration', function() { }); it('provides custom equality testers to async matchers', function(done) { - jasmine.getEnv().requirePromises(); + if (jasmine.getEnv().skipBrowserFlake) { + jasmine.getEnv().skipBrowserFlake(); + } var specDone = jasmine.createSpy('specDone'); @@ -3014,7 +2951,7 @@ describe('Env integration', function() { env.addCustomEqualityTester(function() { return true; }); - var p = Promise.resolve('something'); // eslint-disable-line compat/compat + var p = Promise.resolve('something'); return env.expectAsync(p).toBeResolvedTo('something else'); }); @@ -3030,8 +2967,6 @@ describe('Env integration', function() { }); it('includes useful stack frames in async matcher failures', function(done) { - jasmine.getEnv().requirePromises(); - var specDone = jasmine.createSpy('specDone'); env.addReporter({ specDone: specDone }); @@ -3040,7 +2975,7 @@ describe('Env integration', function() { env.addCustomEqualityTester(function() { return true; }); - var p = Promise.resolve(); // eslint-disable-line compat/compat + var p = Promise.resolve(); return env.expectAsync(p).toBeRejected(); }); @@ -3059,11 +2994,8 @@ describe('Env integration', function() { }); it('reports an error when an async expectation occurs after the spec finishes', function(done) { - jasmine.getEnv().requirePromises(); - var resolve, jasmineDone = jasmine.createSpy('jasmineDone'), - // eslint-disable-next-line compat/compat promise = new Promise(function(res) { resolve = res; }); @@ -3126,11 +3058,8 @@ describe('Env integration', function() { }); it('reports an error when an async expectation occurs after the suite finishes', function(done) { - jasmine.getEnv().requirePromises(); - var resolve, jasmineDone = jasmine.createSpy('jasmineDone'), - // eslint-disable-next-line compat/compat promise = new Promise(function(res) { resolve = res; }); @@ -3219,7 +3148,6 @@ describe('Env integration', function() { }); it('is resolved after reporter events are dispatched', function() { - jasmine.getEnv().requirePromises(); var reporter = jasmine.createSpyObj('reporter', [ 'specDone', 'suiteDone', @@ -3239,7 +3167,6 @@ describe('Env integration', function() { }); it('is resolved after the stack is cleared', function(done) { - jasmine.getEnv().requirePromises(); var realClearStack = jasmineUnderTest.getClearStack( jasmineUnderTest.getGlobal() ), @@ -3267,7 +3194,6 @@ describe('Env integration', function() { }); it('is resolved after QueueRunner timeouts are cleared', function() { - jasmine.getEnv().requirePromises(); var setTimeoutSpy = spyOn( jasmineUnderTest.getGlobal(), 'setTimeout' @@ -3303,15 +3229,21 @@ describe('Env integration', function() { }); }); - it('is resolved even if specs fail', function() { - jasmine.getEnv().requirePromises(); + it('is resolved to the value of the jasmineDone event', async function() { env.describe('suite', function() { env.it('spec', function() { env.expect(true).toBe(false); }); }); - return expectAsync(env.execute(null)).toBeResolved(); + let event; + env.addReporter({ + jasmineDone: e => (event = e) + }); + const result = await env.execute(); + + expect(event.overallStatus).toEqual('failed'); + expect(result).toEqual(event); }); }); @@ -3409,4 +3341,139 @@ describe('Env integration', function() { }); }); }); + + it('sends debug logs to the reporter when the spec fails', function(done) { + var reporter = jasmine.createSpyObj('reporter', ['specDone']), + startTime, + endTime; + + env.addReporter(reporter); + env.configure({ random: false }); + + env.it('fails', function() { + startTime = new Date().getTime(); + env.debugLog('message 1'); + env.debugLog('message 2'); + env.expect(1).toBe(2); + endTime = new Date().getTime(); + }); + + env.it('passes', function() { + env.debugLog('message that should not be reported'); + }); + + env.execute(null, function() { + function numberInRange(min, max) { + return { + asymmetricMatch: function(compareTo) { + return compareTo >= min && compareTo <= max; + }, + jasmineToString: function(pp) { + return ''; + } + }; + } + + var duration; + + expect(reporter.specDone).toHaveBeenCalledTimes(2); + duration = reporter.specDone.calls.argsFor(0)[0].duration; + expect(reporter.specDone.calls.argsFor(0)[0]).toEqual( + jasmine.objectContaining({ + debugLogs: [ + { + timestamp: numberInRange(0, duration), + message: 'message 1' + }, + { + timestamp: numberInRange(0, duration), + message: 'message 2' + } + ] + }) + ); + expect(reporter.specDone.calls.argsFor(1)[0].debugLogs).toBeFalsy(); + done(); + }); + }); + + it('reports an error when debugLog is used when a spec is not running', function(done) { + var reporter = jasmine.createSpyObj('reporter', ['suiteDone']); + + env.describe('a suite', function() { + env.beforeAll(function() { + env.debugLog('a message'); + }); + + env.it('a spec', function() {}); + }); + + env.addReporter(reporter); + env.execute(null, function() { + expect(reporter.suiteDone).toHaveBeenCalledWith( + jasmine.objectContaining({ + failedExpectations: [ + jasmine.objectContaining({ + message: jasmine.stringContaining( + "'debugLog' was called when there was no current spec" + ) + }) + ] + }) + ); + done(); + }); + }); + + it('uses custom equality testers in Spy#withArgs', async function() { + env.it('a spec', function() { + const createSpySpy = env.createSpy('via createSpy'); + const spiedOn = { foo: function() {} }; + env.spyOn(spiedOn, 'foo'); + const spyObj = env.createSpyObj('spyObj', ['foo']); + const spiedOnAllFuncs = { foo: function() {} }; + env.spyOnAllFunctions(spiedOnAllFuncs); + + for (const spy of [ + createSpySpy, + spiedOn.foo, + spyObj.foo, + spiedOnAllFuncs.foo + ]) { + spy.and.returnValue('default strategy'); + spy.withArgs(42).and.returnValue('custom strategy'); + } + + env.addCustomEqualityTester(function(a, b) { + if ((a === 'x' && b === 42) || (a === 42 && b === 'x')) { + return true; + } + }); + + env + .expect(createSpySpy('x')) + .withContext('createSpy') + .toEqual('custom strategy'); + env + .expect(spiedOn.foo('x')) + .withContext('spyOn') + .toEqual('custom strategy'); + env + .expect(spyObj.foo('x')) + .withContext('createSpyObj') + .toEqual('custom strategy'); + env + .expect(spiedOnAllFuncs.foo('x')) + .withContext('spyOnAllFunctions') + .toEqual('custom strategy'); + }); + + let failedExpectations; + env.addReporter({ + specDone: r => (failedExpectations = r.failedExpectations) + }); + + await env.execute(); + expect(failedExpectations).toEqual([]); + }); }); diff --git a/spec/core/integration/MatchersSpec.js b/spec/core/integration/MatchersSpec.js index 86fe77c4..9e3f7f6c 100644 --- a/spec/core/integration/MatchersSpec.js +++ b/spec/core/integration/MatchersSpec.js @@ -90,8 +90,6 @@ describe('Matchers (Integration)', function() { function verifyPassesAsync(expectations) { it('passes', function(done) { - jasmine.getEnv().requirePromises(); - env.it('a spec', function() { return expectations(env); }); @@ -118,8 +116,6 @@ describe('Matchers (Integration)', function() { function verifyFailsAsync(expectations) { it('fails', function(done) { - jasmine.getEnv().requirePromises(); - env.it('a spec', function() { return expectations(env); }); @@ -147,7 +143,6 @@ describe('Matchers (Integration)', function() { function verifyFailsWithCustomObjectFormattersAsync(config) { it('uses custom object formatters', function(done) { var env = new jasmineUnderTest.Env(); - jasmine.getEnv().requirePromises(); env.it('a spec', function() { env.addCustomObjectFormatter(config.formatter); return config.expectations(env); @@ -348,12 +343,10 @@ describe('Matchers (Integration)', function() { describe('toBeResolved', function() { verifyPassesAsync(function(env) { - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.resolve()).toBeResolved(); }); verifyFailsAsync(function(env) { - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.reject()).toBeResolved(); }); }); @@ -363,12 +356,10 @@ describe('Matchers (Integration)', function() { env.addCustomEqualityTester(function(a, b) { return a.toString() === b.toString(); }); - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.resolve('5')).toBeResolvedTo(5); }); verifyFailsAsync(function(env) { - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.resolve('foo')).toBeResolvedTo('bar'); }); @@ -377,7 +368,6 @@ describe('Matchers (Integration)', function() { return '|' + val + '|'; }, expectations: function(env) { - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.resolve('x')).toBeResolvedTo('y'); }, expectedMessage: @@ -388,12 +378,10 @@ describe('Matchers (Integration)', function() { describe('toBeRejected', function() { verifyPassesAsync(function(env) { - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.reject('nope')).toBeRejected(); }); verifyFailsAsync(function(env) { - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.resolve()).toBeRejected(); }); }); @@ -403,12 +391,10 @@ describe('Matchers (Integration)', function() { env.addCustomEqualityTester(function(a, b) { return a.toString() === b.toString(); }); - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.reject('5')).toBeRejectedWith(5); }); verifyFailsAsync(function(env) { - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.resolve()).toBeRejectedWith('nope'); }); @@ -417,7 +403,6 @@ describe('Matchers (Integration)', function() { return '|' + val + '|'; }, expectations: function(env) { - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.reject('x')).toBeRejectedWith('y'); }, expectedMessage: @@ -428,16 +413,12 @@ describe('Matchers (Integration)', function() { describe('toBeRejectedWithError', function() { verifyPassesAsync(function(env) { - return ( - env - // eslint-disable-next-line compat/compat - .expectAsync(Promise.reject(new Error())) - .toBeRejectedWithError(Error) - ); + return env + .expectAsync(Promise.reject(new Error())) + .toBeRejectedWithError(Error); }); verifyFailsAsync(function(env) { - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.resolve()).toBeRejectedWithError(Error); }); @@ -446,12 +427,9 @@ describe('Matchers (Integration)', function() { return '|' + val + '|'; }, expectations: function(env) { - return ( - env - // eslint-disable-next-line compat/compat - .expectAsync(Promise.reject('foo')) - .toBeRejectedWithError('foo') - ); + return env + .expectAsync(Promise.reject('foo')) + .toBeRejectedWithError('foo'); }, expectedMessage: 'Expected a promise to be rejected with Error: |foo| ' + @@ -757,10 +735,7 @@ describe('Matchers (Integration)', function() { describe('When an async matcher is used with .already()', function() { it('propagates the matcher result when the promise is resolved', function(done) { - jasmine.getEnv().requirePromises(); - env.it('a spec', function() { - // eslint-disable-next-line compat/compat return env.expectAsync(Promise.resolve()).already.toBeRejected(); }); @@ -782,15 +757,10 @@ describe('Matchers (Integration)', function() { }); it('propagates the matcher result when the promise is rejected', function(done) { - jasmine.getEnv().requirePromises(); - env.it('a spec', function() { - return ( - env - // eslint-disable-next-line compat/compat - .expectAsync(Promise.reject(new Error('nope'))) - .already.toBeResolved() - ); + return env + .expectAsync(Promise.reject(new Error('nope'))) + .already.toBeResolved(); }); var specExpectations = function(result) { @@ -812,9 +782,6 @@ describe('Matchers (Integration)', function() { }); it('fails when the promise is pending', function(done) { - jasmine.getEnv().requirePromises(); - - // eslint-disable-next-line compat/compat var promise = new Promise(function() {}); env.it('a spec', function() { diff --git a/spec/core/integration/SpecRunningSpec.js b/spec/core/integration/SpecRunningSpec.js index f15a7e14..2ce28901 100644 --- a/spec/core/integration/SpecRunningSpec.js +++ b/spec/core/integration/SpecRunningSpec.js @@ -792,9 +792,9 @@ describe('spec running', function() { }); }); - describe('When stopSpecOnExpectationFailure is set', function() { - it('skips to cleanup functions after an error', function(done) { - var actions = []; + function hasStandardErrorHandlingBehavior() { + it('skips to cleanup functions after a thrown error', async function() { + const actions = []; env.describe('Something', function() { env.beforeEach(function() { @@ -821,79 +821,18 @@ describe('spec running', function() { }); }); - env.configure({ stopSpecOnExpectationFailure: true }); + await env.execute(); - env.execute(null, function() { - expect(actions).toEqual([ - 'outer beforeEach', - 'inner afterEach', - 'outer afterEach' - ]); - done(); - }); + expect(actions).toEqual(['outer beforeEach', 'outer afterEach']); }); - it('skips to cleanup functions after done.fail is called', function(done) { - var actions = []; - - env.describe('Something', function() { - env.beforeEach(function(done) { - actions.push('beforeEach'); - done.fail('error'); - actions.push('after done.fail'); - }); - - env.afterEach(function() { - actions.push('afterEach'); - }); - - env.it('does it', function() { - actions.push('it'); - }); - }); - - env.configure({ stopSpecOnExpectationFailure: true }); - - env.execute(null, function() { - expect(actions).toEqual(['beforeEach', 'afterEach']); - done(); - }); - }); - - it('skips to cleanup functions when an async function times out', function(done) { - var actions = []; - - env.describe('Something', function() { - env.beforeEach(function(innerDone) { - actions.push('beforeEach'); - }, 1); - - env.afterEach(function() { - actions.push('afterEach'); - }); - - env.it('does it', function() { - actions.push('it'); - }); - }); - - env.configure({ stopSpecOnExpectationFailure: true }); - - env.execute(null, function() { - expect(actions).toEqual(['beforeEach', 'afterEach']); - done(); - }); - }); - - it('skips to cleanup functions after an error with deprecations', function(done) { - var actions = []; - - spyOn(env, 'deprecated'); + it('skips to cleanup functions after a rejected promise', async function() { + const actions = []; env.describe('Something', function() { env.beforeEach(function() { actions.push('outer beforeEach'); - throw new Error('error'); + return Promise.reject(new Error('error')); }); env.afterEach(function() { @@ -915,29 +854,18 @@ describe('spec running', function() { }); }); - env.throwOnExpectationFailure(true); + await env.execute(); - env.execute(null, function() { - expect(actions).toEqual([ - 'outer beforeEach', - 'inner afterEach', - 'outer afterEach' - ]); - expect(env.deprecated).toHaveBeenCalled(); - done(); - }); + expect(actions).toEqual(['outer beforeEach', 'outer afterEach']); }); - it('skips to cleanup functions after done.fail is called with deprecations', function(done) { - var actions = []; - - spyOn(env, 'deprecated'); + it('skips to cleanup functions after done.fail is called', async function() { + const actions = []; env.describe('Something', function() { env.beforeEach(function(done) { actions.push('beforeEach'); done.fail('error'); - actions.push('after done.fail'); }); env.afterEach(function() { @@ -949,19 +877,13 @@ describe('spec running', function() { }); }); - env.throwOnExpectationFailure(true); + await env.execute(); - env.execute(null, function() { - expect(actions).toEqual(['beforeEach', 'afterEach']); - expect(env.deprecated).toHaveBeenCalled(); - done(); - }); + expect(actions).toEqual(['beforeEach', 'afterEach']); }); - it('skips to cleanup functions when an async function times out with deprecations', function(done) { - var actions = []; - - spyOn(env, 'deprecated'); + it('skips to cleanup functions when an async function times out', async function() { + const actions = []; env.describe('Something', function() { env.beforeEach(function(innerDone) { @@ -977,17 +899,405 @@ describe('spec running', function() { }); }); - env.throwOnExpectationFailure(true); + await env.execute(); - env.execute(null, function() { - expect(actions).toEqual(['beforeEach', 'afterEach']); - expect(env.deprecated).toHaveBeenCalled(); - done(); + expect(actions).toEqual(['beforeEach', 'afterEach']); + }); + + it('skips to cleanup functions after pending() is called', async function() { + const actions = []; + + env.describe('Something', function() { + env.beforeEach(function() { + actions.push('outer beforeEach'); + pending(); + }); + + env.afterEach(function() { + actions.push('outer afterEach'); + }); + + env.describe('Inner', function() { + env.beforeEach(function() { + actions.push('inner beforeEach'); + }); + + env.afterEach(function() { + actions.push('inner afterEach'); + }); + + env.it('does it', function() { + actions.push('inner it'); + }); + }); }); + + await env.execute(); + + expect(actions).toEqual(['outer beforeEach', 'outer afterEach']); + }); + + it('runs all reporter callbacks even if one fails', async function() { + const laterReporter = jasmine.createSpyObj('laterReporter', ['specDone']); + + env.it('a spec', function() {}); + env.addReporter({ + specDone: function() { + throw new Error('nope'); + } + }); + env.addReporter(laterReporter); + + await env.execute(); + + expect(laterReporter.specDone).toHaveBeenCalled(); + }); + + it('skips cleanup functions that are defined in child suites when a beforeEach errors', async function() { + const parentAfterEachFn = jasmine.createSpy('parentAfterEachFn'); + const childAfterEachFn = jasmine.createSpy('childAfterEachFn'); + + env.describe('parent suite', function() { + env.beforeEach(function() { + throw new Error('nope'); + }); + + env.afterEach(parentAfterEachFn); + + env.describe('child suite', function() { + env.it('a spec', function() {}); + env.afterEach(childAfterEachFn); + }); + }); + + await env.execute(); + + expect(parentAfterEachFn).toHaveBeenCalled(); + expect(childAfterEachFn).not.toHaveBeenCalled(); + }); + } + + describe('When stopSpecOnExpectationFailure is true', function() { + beforeEach(function() { + env.configure({ stopSpecOnExpectationFailure: true }); + }); + + hasStandardErrorHandlingBehavior(); + + it('skips to cleanup functions after an expectation failure', async function() { + var actions = []; + + env.describe('Something', function() { + env.beforeEach(function() { + actions.push('outer beforeEach'); + env.expect(1).toBe(2); + }); + + env.afterEach(function() { + actions.push('outer afterEach'); + }); + + env.describe('Inner', function() { + env.beforeEach(function() { + actions.push('inner beforeEach'); + }); + + env.afterEach(function() { + actions.push('inner afterEach'); + }); + + env.it('does it', function() { + actions.push('inner it'); + }); + }); + }); + + await env.execute(); + + expect(actions).toEqual(['outer beforeEach', 'outer afterEach']); }); }); - function behavesLikeStopOnSpecFailureIsOn(configureFn) { + describe('When stopSpecOnExpectationFailure is false', function() { + beforeEach(function() { + env.configure({ stopSpecOnExpectationFailure: false }); + }); + + hasStandardErrorHandlingBehavior(); + + it('does not skip anything after an expectation failure', async function() { + var actions = []; + + env.describe('Something', function() { + env.beforeEach(function() { + actions.push('outer beforeEach'); + env.expect(1).toBe(2); + }); + + env.afterEach(function() { + actions.push('outer afterEach'); + }); + + env.describe('Inner', function() { + env.beforeEach(function() { + actions.push('inner beforeEach'); + }); + + env.afterEach(function() { + actions.push('inner afterEach'); + }); + + env.it('does it', function() { + actions.push('inner it'); + }); + }); + }); + + await env.execute(); + + expect(actions).toEqual([ + 'outer beforeEach', + 'inner beforeEach', + 'inner it', + 'inner afterEach', + 'outer afterEach' + ]); + }); + }); + + describe('When a top-level beforeAll function fails', function() { + it('skips and reports contained specs', async function() { + const outerBeforeEach = jasmine.createSpy('outerBeforeEach'); + const nestedBeforeEach = jasmine.createSpy('nestedBeforeEach'); + const outerAfterEach = jasmine.createSpy('outerAfterEach'); + const nestedAfterEach = jasmine.createSpy('nestedAfterEach'); + const outerIt = jasmine.createSpy('outerIt'); + const nestedIt = jasmine.createSpy('nestedIt'); + const nestedBeforeAll = jasmine.createSpy('nestedBeforeAll'); + + env.beforeAll(function() { + throw new Error('nope'); + }); + + env.beforeEach(outerBeforeEach); + env.it('a spec', outerIt); + env.describe('a nested suite', function() { + env.beforeAll(nestedBeforeAll); + env.beforeEach(nestedBeforeEach); + env.it('a nested spec', nestedIt); + env.afterEach(nestedAfterEach); + }); + env.afterEach(outerAfterEach); + + const reporter = jasmine.createSpyObj('reporter', [ + 'suiteStarted', + 'suiteDone', + 'specStarted', + 'specDone' + ]); + env.addReporter(reporter); + + await env.execute(); + + expect(outerBeforeEach).not.toHaveBeenCalled(); + expect(outerIt).not.toHaveBeenCalled(); + expect(nestedBeforeAll).not.toHaveBeenCalled(); + expect(nestedBeforeEach).not.toHaveBeenCalled(); + expect(nestedIt).not.toHaveBeenCalled(); + expect(nestedAfterEach).not.toHaveBeenCalled(); + expect(outerAfterEach).not.toHaveBeenCalled(); + + expect(reporter.suiteStarted).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a nested suite' + }) + ); + + // The child suite should be reported as passed, for consistency with + // suites that contain failing specs but no suite-level errors. + expect(reporter.suiteDone).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a nested suite', + status: 'passed', + failedExpectations: [] + }) + ); + + expect(reporter.specStarted).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a spec' + }) + ); + expect(reporter.specDone).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a spec', + status: 'failed', + failedExpectations: [ + jasmine.objectContaining({ + passed: false, + message: + 'Not run because a beforeAll function failed. The ' + + 'beforeAll failure will be reported on the suite that ' + + 'caused it.' + }) + ] + }) + ); + + expect(reporter.specStarted).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a nested suite a nested spec' + }) + ); + expect(reporter.specDone).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a nested suite a nested spec', + status: 'failed', + failedExpectations: [ + jasmine.objectContaining({ + passed: false, + message: + 'Not run because a beforeAll function failed. The ' + + 'beforeAll failure will be reported on the suite that ' + + 'caused it.' + }) + ] + }) + ); + }); + }); + + describe('When a suite beforeAll function fails', function() { + it('skips and reports contained specs', async function() { + const outerBeforeEach = jasmine.createSpy('outerBeforeEach'); + const nestedBeforeEach = jasmine.createSpy('nestedBeforeEach'); + const outerAfterEach = jasmine.createSpy('outerAfterEach'); + const nestedAfterEach = jasmine.createSpy('nestedAfterEach'); + const outerIt = jasmine.createSpy('outerIt'); + const nestedIt = jasmine.createSpy('nestedIt'); + const nestedBeforeAll = jasmine.createSpy('nestedBeforeAll'); + + env.describe('a suite', function() { + env.beforeAll(function() { + throw new Error('nope'); + }); + + env.beforeEach(outerBeforeEach); + env.it('a spec', outerIt); + env.describe('a nested suite', function() { + env.beforeAll(nestedBeforeAll); + env.beforeEach(nestedBeforeEach); + env.it('a nested spec', nestedIt); + env.afterEach(nestedAfterEach); + }); + env.afterEach(outerAfterEach); + }); + + const reporter = jasmine.createSpyObj('reporter', [ + 'suiteStarted', + 'suiteDone', + 'specStarted', + 'specDone' + ]); + env.addReporter(reporter); + + await env.execute(); + + expect(outerBeforeEach).not.toHaveBeenCalled(); + expect(outerIt).not.toHaveBeenCalled(); + expect(nestedBeforeAll).not.toHaveBeenCalled(); + expect(nestedBeforeEach).not.toHaveBeenCalled(); + expect(nestedIt).not.toHaveBeenCalled(); + expect(nestedAfterEach).not.toHaveBeenCalled(); + expect(outerAfterEach).not.toHaveBeenCalled(); + + expect(reporter.suiteStarted).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a suite a nested suite' + }) + ); + + // The child suite should be reported as passed, for consistency with + // suites that contain failing specs but no suite-level errors. + expect(reporter.suiteDone).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a suite a nested suite', + status: 'passed', + failedExpectations: [] + }) + ); + + expect(reporter.specStarted).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a suite a spec' + }) + ); + expect(reporter.specDone).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a suite a spec', + status: 'failed', + failedExpectations: [ + jasmine.objectContaining({ + passed: false, + message: + 'Not run because a beforeAll function failed. The ' + + 'beforeAll failure will be reported on the suite that ' + + 'caused it.' + }) + ] + }) + ); + + expect(reporter.specStarted).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a suite a nested suite a nested spec' + }) + ); + expect(reporter.specDone).toHaveBeenCalledWith( + jasmine.objectContaining({ + fullName: 'a suite a nested suite a nested spec', + status: 'failed', + failedExpectations: [ + jasmine.objectContaining({ + passed: false, + message: + 'Not run because a beforeAll function failed. The ' + + 'beforeAll failure will be reported on the suite that ' + + 'caused it.' + }) + ] + }) + ); + }); + + it('runs afterAll functions in the current suite and outer scopes', async function() { + const outerAfterAll = jasmine.createSpy('outerAfterAll'); + const nestedAfterAll = jasmine.createSpy('nestedAfterAll'); + const secondNestedAfterAll = jasmine.createSpy('secondNestedAfterAll'); + + env.describe('a nested suite', function() { + env.beforeAll(function() { + throw new Error('nope'); + }); + + env.describe('more nesting', function() { + env.it('a nested spec', function() {}); + env.afterAll(secondNestedAfterAll); + }); + + env.afterAll(nestedAfterAll); + }); + env.afterAll(outerAfterAll); + + await env.execute(); + + expect(secondNestedAfterAll).not.toHaveBeenCalled(); + expect(nestedAfterAll).toHaveBeenCalled(); + expect(outerAfterAll).toHaveBeenCalled(); + }); + }); + + describe('when stopOnSpecFailure is on', function() { it('does not run further specs when one fails', function(done) { var actions = [], config; @@ -1006,32 +1316,47 @@ describe('spec running', function() { }); env.configure({ random: false }); - configureFn(env); + env.configure({ stopOnSpecFailure: true }); env.execute(null, function() { expect(actions).toEqual(['fails']); done(); }); }); - } - describe('when failFast is on', function() { - behavesLikeStopOnSpecFailureIsOn(function(env) { - spyOn(env, 'deprecated'); - env.configure({ failFast: true }); - }); - }); + it('runs afterAll functions', async function() { + const actions = []; + + env.describe('outer suite', function() { + env.describe('inner suite', function() { + env.it('fails', function() { + actions.push('fails'); + env.expect(1).toBe(2); + }); + + env.afterAll(function() { + actions.push('inner afterAll'); + }); + }); + + env.afterAll(function() { + actions.push('outer afterAll'); + }); + }); + + env.afterAll(function() { + actions.push('top afterAll'); + }); - describe('when stopOnSpecFailure is on', function() { - behavesLikeStopOnSpecFailureIsOn(function(env) { env.configure({ stopOnSpecFailure: true }); - }); - }); + await env.execute(); - describe('when stopOnSpecFailure is enabled via the deprecated method', function() { - behavesLikeStopOnSpecFailureIsOn(function(env) { - spyOn(env, 'deprecated'); - env.stopOnSpecFailure(true); + expect(actions).toEqual([ + 'fails', + 'inner afterAll', + 'outer afterAll', + 'top afterAll' + ]); }); }); diff --git a/spec/core/matchers/DiffBuilderSpec.js b/spec/core/matchers/DiffBuilderSpec.js index d1a3d884..840eff68 100644 --- a/spec/core/matchers/DiffBuilderSpec.js +++ b/spec/core/matchers/DiffBuilderSpec.js @@ -112,7 +112,7 @@ describe('DiffBuilder', function() { return '[number:' + x + ']'; } }; - prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]); + const prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]); var diffBuilder = new jasmineUnderTest.DiffBuilder({ prettyPrinter: prettyPrinter }); @@ -131,7 +131,7 @@ describe('DiffBuilder', function() { return '[thing with a=' + x.a + ', b=' + JSON.stringify(x.b) + ']'; } }; - prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]); + const prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]); var diffBuilder = new jasmineUnderTest.DiffBuilder({ prettyPrinter: prettyPrinter }); diff --git a/spec/core/matchers/async/toBePendingSpec.js b/spec/core/matchers/async/toBePendingSpec.js index 0b78d8cd..385a08be 100644 --- a/spec/core/matchers/async/toBePendingSpec.js +++ b/spec/core/matchers/async/toBePendingSpec.js @@ -1,8 +1,5 @@ -/* eslint-disable compat/compat */ describe('toBePending', function() { it('passes if the actual promise is pending', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(), matcher = jasmineUnderTest.asyncMatchers.toBePending(matchersUtil), actual = new Promise(function() {}); @@ -13,8 +10,6 @@ describe('toBePending', function() { }); it('fails if the actual promise is resolved', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(), matcher = jasmineUnderTest.asyncMatchers.toBePending(matchersUtil), actual = Promise.resolve(); @@ -25,8 +20,6 @@ describe('toBePending', function() { }); it('fails if the actual promise is rejected', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(), matcher = jasmineUnderTest.asyncMatchers.toBePending(matchersUtil), actual = Promise.reject(new Error('promise was rejected')); diff --git a/spec/core/matchers/async/toBeRejectedSpec.js b/spec/core/matchers/async/toBeRejectedSpec.js index c1ea377b..e69f0044 100644 --- a/spec/core/matchers/async/toBeRejectedSpec.js +++ b/spec/core/matchers/async/toBeRejectedSpec.js @@ -1,8 +1,5 @@ -/* eslint-disable compat/compat */ describe('toBeRejected', function() { it('passes if the actual is rejected', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(), matcher = jasmineUnderTest.asyncMatchers.toBeRejected(matchersUtil), actual = Promise.reject('AsyncExpectationSpec rejection'); @@ -13,8 +10,6 @@ describe('toBeRejected', function() { }); it('fails if the actual is resolved', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(), matcher = jasmineUnderTest.asyncMatchers.toBeRejected(matchersUtil), actual = Promise.resolve(); diff --git a/spec/core/matchers/async/toBeRejectedWithErrorSpec.js b/spec/core/matchers/async/toBeRejectedWithErrorSpec.js index d7d3f659..32a25ada 100644 --- a/spec/core/matchers/async/toBeRejectedWithErrorSpec.js +++ b/spec/core/matchers/async/toBeRejectedWithErrorSpec.js @@ -1,8 +1,5 @@ -/* eslint-disable compat/compat */ describe('#toBeRejectedWithError', function() { it('passes when Error type matches', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -23,8 +20,6 @@ describe('#toBeRejectedWithError', function() { }); it('passes when Error type and message matches', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -45,8 +40,6 @@ describe('#toBeRejectedWithError', function() { }); it('passes when Error matches and is exactly Error', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -67,8 +60,6 @@ describe('#toBeRejectedWithError', function() { }); it('passes when Error message matches a string', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -89,8 +80,6 @@ describe('#toBeRejectedWithError', function() { }); it('passes when Error message matches a RegExp', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -111,8 +100,6 @@ describe('#toBeRejectedWithError', function() { }); it('passes when Error message is empty', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -133,8 +120,6 @@ describe('#toBeRejectedWithError', function() { }); it('passes when no arguments', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -155,8 +140,6 @@ describe('#toBeRejectedWithError', function() { }); it('fails when resolved', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -176,8 +159,6 @@ describe('#toBeRejectedWithError', function() { }); it('fails when rejected with non Error type', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -198,8 +179,6 @@ describe('#toBeRejectedWithError', function() { }); it('fails when Error type mismatches', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -220,8 +199,6 @@ describe('#toBeRejectedWithError', function() { }); it('fails when Error message mismatches', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), diff --git a/spec/core/matchers/async/toBeRejectedWithSpec.js b/spec/core/matchers/async/toBeRejectedWithSpec.js index 9c663930..af96719f 100644 --- a/spec/core/matchers/async/toBeRejectedWithSpec.js +++ b/spec/core/matchers/async/toBeRejectedWithSpec.js @@ -1,8 +1,5 @@ -/* eslint-disable compat/compat */ describe('#toBeRejectedWith', function() { it('should return true if the promise is rejected with the expected value', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), actual = Promise.reject({ error: 'PEBCAK' }); @@ -13,8 +10,6 @@ describe('#toBeRejectedWith', function() { }); it('should fail if the promise resolves', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), actual = Promise.resolve(); @@ -25,8 +20,6 @@ describe('#toBeRejectedWith', function() { }); it('should fail if the promise is rejected with a different value', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -45,8 +38,6 @@ describe('#toBeRejectedWith', function() { }); it('should build its error correctly when negated', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -64,8 +55,6 @@ describe('#toBeRejectedWith', function() { }); it('should support custom equality testers', function() { - jasmine.getEnv().requirePromises(); - var customEqualityTesters = [ function() { return true; diff --git a/spec/core/matchers/async/toBeResolvedSpec.js b/spec/core/matchers/async/toBeResolvedSpec.js index b90a537d..42ce930e 100644 --- a/spec/core/matchers/async/toBeResolvedSpec.js +++ b/spec/core/matchers/async/toBeResolvedSpec.js @@ -1,8 +1,5 @@ -/* eslint-disable compat/compat */ describe('toBeResolved', function() { it('passes if the actual is resolved', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(), matcher = jasmineUnderTest.asyncMatchers.toBeResolved(matchersUtil), actual = Promise.resolve(); @@ -13,8 +10,6 @@ describe('toBeResolved', function() { }); it('fails if the actual is rejected', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter([]) }), diff --git a/spec/core/matchers/async/toBeResolvedToSpec.js b/spec/core/matchers/async/toBeResolvedToSpec.js index 734b780e..20f465d2 100644 --- a/spec/core/matchers/async/toBeResolvedToSpec.js +++ b/spec/core/matchers/async/toBeResolvedToSpec.js @@ -1,8 +1,5 @@ -/* eslint-disable compat/compat */ describe('#toBeResolvedTo', function() { it('passes if the promise is resolved to the expected value', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), actual = Promise.resolve({ foo: 42 }); @@ -13,8 +10,6 @@ describe('#toBeResolvedTo', function() { }); it('fails if the promise is rejected', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -34,8 +29,6 @@ describe('#toBeResolvedTo', function() { }); it('fails if the promise is resolved to a different value', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -54,8 +47,6 @@ describe('#toBeResolvedTo', function() { }); it('builds its message correctly when negated', function() { - jasmine.getEnv().requirePromises(); - var matchersUtil = new jasmineUnderTest.MatchersUtil({ pp: jasmineUnderTest.makePrettyPrinter() }), @@ -73,8 +64,6 @@ describe('#toBeResolvedTo', function() { }); it('supports custom equality testers', function() { - jasmine.getEnv().requirePromises(); - var customEqualityTesters = [ function() { return true; diff --git a/spec/core/matchers/matchersUtilSpec.js b/spec/core/matchers/matchersUtilSpec.js index 7fc9fc85..b9dc1727 100644 --- a/spec/core/matchers/matchersUtilSpec.js +++ b/spec/core/matchers/matchersUtilSpec.js @@ -94,7 +94,7 @@ describe('matchersUtil', function() { }); it('fails for Arrays that have different lengths', function() { - matchersUtil = new jasmineUnderTest.MatchersUtil(); + const matchersUtil = new jasmineUnderTest.MatchersUtil(); expect(matchersUtil.equals([1, 2], [1, 2, 3])).toBe(false); }); @@ -232,8 +232,8 @@ describe('matchersUtil', function() { return; } - var p1 = new Promise(function() {}), // eslint-disable-line compat/compat - p2 = new Promise(function() {}), // eslint-disable-line compat/compat + var p1 = new Promise(function() {}), + p2 = new Promise(function() {}), matchersUtil = new jasmineUnderTest.MatchersUtil(); expect(matchersUtil.equals(p1, p1)).toBe(true); @@ -367,13 +367,11 @@ describe('matchersUtil', function() { }); it('passes when MapContaining is used', function() { - jasmine.getEnv().requireFunctioningMaps(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var obj = new Map(); // eslint-disable-line compat/compat + var obj = new Map(); obj.set(1, 2); obj.set('foo', 'bar'); - var containing = new jasmineUnderTest.MapContaining(new Map()); // eslint-disable-line compat/compat + var containing = new jasmineUnderTest.MapContaining(new Map()); containing.sample.set('foo', 'bar'); expect(matchersUtil.equals(obj, containing)).toBe(true); @@ -381,13 +379,11 @@ describe('matchersUtil', function() { }); it('passes when SetContaining is used', function() { - jasmine.getEnv().requireFunctioningSets(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var obj = new Set(); // eslint-disable-line compat/compat + var obj = new Set(); obj.add(1); obj.add('foo'); - var containing = new jasmineUnderTest.SetContaining(new Set()); // eslint-disable-line compat/compat + var containing = new jasmineUnderTest.SetContaining(new Set()); containing.sample.add(1); expect(matchersUtil.equals(obj, containing)).toBe(true); @@ -427,19 +423,7 @@ describe('matchersUtil', function() { ).toBe(true); }); - it('passes when a custom equality matcher passed to equals returns true', function() { - // TODO: remove this in the next major release. - var tester = function(a, b) { - return true; - }, - matchersUtil = new jasmineUnderTest.MatchersUtil(); - - spyOn(jasmineUnderTest.getEnv(), 'deprecated'); // suppress warning - - expect(matchersUtil.equals(1, 2, [tester])).toBe(true); - }); - - it('passes when a custom equality matcher passed to the constructor returns true', function() { + it('passes when a custom equality matcher returns true', function() { var tester = function(a, b) { return true; }, @@ -456,20 +440,7 @@ describe('matchersUtil', function() { expect(matchersUtil.equals({}, {})).toBe(true); }); - describe("when a custom equality matcher is passed to equals that returns 'undefined'", function() { - // TODO: remove this in the next major release. - var tester = function(a, b) { - return jasmine.undefined; - }; - - it('passes for two empty Objects', function() { - var matchersUtil = new jasmineUnderTest.MatchersUtil(); - spyOn(jasmineUnderTest.getEnv(), 'deprecated'); // suppress warning - expect(matchersUtil.equals({}, {}, [tester])).toBe(true); - }); - }); - - describe("when a custom equality matcher is passed to the constructor that returns 'undefined'", function() { + describe("when a custom equality matcher returns 'undefined'", function() { var tester = function(a, b) { return jasmine.undefined; }; @@ -483,19 +454,7 @@ describe('matchersUtil', function() { }); }); - it('fails for equivalents when a custom equality matcher passed to equals returns false', function() { - // TODO: remove this in the next major release. - var tester = function(a, b) { - return false; - }, - matchersUtil = new jasmineUnderTest.MatchersUtil(); - - spyOn(jasmineUnderTest.getEnv(), 'deprecated'); // suppress warning - - expect(matchersUtil.equals(1, 1, [tester])).toBe(false); - }); - - it('fails for equivalents when a custom equality matcher passed to the constructor returns false', function() { + it('fails for equivalents when a custom equality matcher returns false', function() { var tester = function(a, b) { return false; }, @@ -507,29 +466,7 @@ describe('matchersUtil', function() { expect(matchersUtil.equals(1, 1)).toBe(false); }); - it('passes for an asymmetric equality tester that returns true when a custom equality tester passed to equals return false', function() { - // TODO: remove this in the next major release. - var asymmetricTester = { - asymmetricMatch: function(other) { - return true; - } - }, - symmetricTester = function(a, b) { - return false; - }, - matchersUtil = new jasmineUnderTest.MatchersUtil(); - - spyOn(jasmineUnderTest.getEnv(), 'deprecated'); // suppress warning - - expect( - matchersUtil.equals(asymmetricTester, true, [symmetricTester]) - ).toBe(true); - expect( - matchersUtil.equals(true, asymmetricTester, [symmetricTester]) - ).toBe(true); - }); - - it('passes for an asymmetric equality tester that returns true when a custom equality tester passed to the constructor return false', function() { + it('passes for an asymmetric equality tester that returns true when a custom equality tester return false', function() { var asymmetricTester = { asymmetricMatch: function(other) { return true; @@ -547,47 +484,6 @@ describe('matchersUtil', function() { expect(matchersUtil.equals(true, asymmetricTester)).toBe(true); }); - describe('The compatibility shim passed to asymmetric equality testers', function() { - describe('When equals is called with custom equality testers', function() { - it('is both a matchersUtil and the custom equality testers passed to equals', function() { - var asymmetricTester = jasmine.createSpyObj('tester', [ - 'asymmetricMatch' - ]), - symmetricTester = function() {}, - matchersUtil = new jasmineUnderTest.MatchersUtil(), - shim; - - spyOn(jasmineUnderTest.getEnv(), 'deprecated'); // suppress warning - matchersUtil.equals(true, asymmetricTester, [symmetricTester]); - shim = asymmetricTester.asymmetricMatch.calls.argsFor(0)[1]; - expect(shim).toEqual(jasmine.any(jasmineUnderTest.MatchersUtil)); - expect(shim.length).toEqual(1); - expect(shim[0]).toEqual(symmetricTester); - }); - }); - - describe('When equals is called with custom equality testers', function() { - it('is both a matchersUtil and the custom equality testers passed to the constructor', function() { - var asymmetricTester = jasmine.createSpyObj('tester', [ - 'asymmetricMatch' - ]), - symmetricTester = function() {}, - matchersUtil = new jasmineUnderTest.MatchersUtil({ - customTesters: [symmetricTester], - pp: function() {} - }), - shim; - - spyOn(jasmineUnderTest.getEnv(), 'deprecated'); // suppress warning - matchersUtil.equals(true, asymmetricTester); - shim = asymmetricTester.asymmetricMatch.calls.argsFor(0)[1]; - expect(shim).toEqual(jasmine.any(jasmineUnderTest.MatchersUtil)); - expect(shim.length).toEqual(1); - expect(shim[0]).toEqual(symmetricTester); - }); - }); - }); - it('passes when an Any is compared to an Any that checks for the same type', function() { var any1 = new jasmineUnderTest.Any(Function), any2 = new jasmineUnderTest.Any(Function), @@ -619,19 +515,16 @@ describe('matchersUtil', function() { }); it('passes when comparing two empty sets', function() { - jasmine.getEnv().requireFunctioningSets(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); - expect(matchersUtil.equals(new Set(), new Set())).toBe(true); // eslint-disable-line compat/compat + expect(matchersUtil.equals(new Set(), new Set())).toBe(true); }); it('passes when comparing identical sets', function() { - jasmine.getEnv().requireFunctioningSets(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var setA = new Set(); // eslint-disable-line compat/compat + var setA = new Set(); setA.add(6); setA.add(5); - var setB = new Set(); // eslint-disable-line compat/compat + var setB = new Set(); setB.add(6); setB.add(5); @@ -639,13 +532,11 @@ describe('matchersUtil', function() { }); it('passes when comparing identical sets with different insertion order and simple elements', function() { - jasmine.getEnv().requireFunctioningSets(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var setA = new Set(); // eslint-disable-line compat/compat + var setA = new Set(); setA.add(3); setA.add(6); - var setB = new Set(); // eslint-disable-line compat/compat + var setB = new Set(); setB.add(6); setB.add(3); @@ -653,26 +544,24 @@ describe('matchersUtil', function() { }); it('passes when comparing identical sets with different insertion order and complex elements 1', function() { - jasmine.getEnv().requireFunctioningSets(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var setA1 = new Set(); // eslint-disable-line compat/compat + var setA1 = new Set(); setA1.add(['a', 3]); setA1.add([6, 1]); - var setA2 = new Set(); // eslint-disable-line compat/compat + var setA2 = new Set(); setA1.add(['y', 3]); setA1.add([6, 1]); - var setA = new Set(); // eslint-disable-line compat/compat + var setA = new Set(); setA.add(setA1); setA.add(setA2); - var setB1 = new Set(); // eslint-disable-line compat/compat + var setB1 = new Set(); setB1.add([6, 1]); setB1.add(['a', 3]); - var setB2 = new Set(); // eslint-disable-line compat/compat + var setB2 = new Set(); setB1.add([6, 1]); setB1.add(['y', 3]); - var setB = new Set(); // eslint-disable-line compat/compat + var setB = new Set(); setB.add(setB1); setB.add(setB2); @@ -680,13 +569,11 @@ describe('matchersUtil', function() { }); it('passes when comparing identical sets with different insertion order and complex elements 2', function() { - jasmine.getEnv().requireFunctioningSets(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var setA = new Set(); // eslint-disable-line compat/compat + var setA = new Set(); setA.add([[1, 2], [3, 4]]); setA.add([[5, 6], [7, 8]]); - var setB = new Set(); // eslint-disable-line compat/compat + var setB = new Set(); setB.add([[5, 6], [7, 8]]); setB.add([[1, 2], [3, 4]]); @@ -694,13 +581,12 @@ describe('matchersUtil', function() { }); it('fails for sets with different elements', function() { - jasmine.getEnv().requireFunctioningSets(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var setA = new Set(); // eslint-disable-line compat/compat + var setA = new Set(); setA.add(6); setA.add(3); setA.add(5); - var setB = new Set(); // eslint-disable-line compat/compat + var setB = new Set(); setB.add(6); setB.add(4); setB.add(5); @@ -709,12 +595,11 @@ describe('matchersUtil', function() { }); it('fails for sets of different size', function() { - jasmine.getEnv().requireFunctioningSets(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var setA = new Set(); // eslint-disable-line compat/compat + var setA = new Set(); setA.add(6); setA.add(3); - var setB = new Set(); // eslint-disable-line compat/compat + var setB = new Set(); setB.add(6); setB.add(4); setB.add(5); @@ -723,40 +608,36 @@ describe('matchersUtil', function() { }); it('passes when comparing two empty maps', function() { - jasmine.getEnv().requireFunctioningMaps(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); - expect(matchersUtil.equals(new Map(), new Map())).toBe(true); // eslint-disable-line compat/compat + expect(matchersUtil.equals(new Map(), new Map())).toBe(true); }); it('passes when comparing identical maps', function() { - jasmine.getEnv().requireFunctioningMaps(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var mapA = new Map(); // eslint-disable-line compat/compat + var mapA = new Map(); mapA.set(6, 5); - var mapB = new Map(); // eslint-disable-line compat/compat + var mapB = new Map(); mapB.set(6, 5); expect(matchersUtil.equals(mapA, mapB)).toBe(true); }); it('passes when comparing identical maps with different insertion order', function() { - jasmine.getEnv().requireFunctioningMaps(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var mapA = new Map(); // eslint-disable-line compat/compat + var mapA = new Map(); mapA.set('a', 3); mapA.set(6, 1); - var mapB = new Map(); // eslint-disable-line compat/compat + var mapB = new Map(); mapB.set(6, 1); mapB.set('a', 3); expect(matchersUtil.equals(mapA, mapB)).toBe(true); }); it('fails for maps with different elements', function() { - jasmine.getEnv().requireFunctioningMaps(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var mapA = new Map(); // eslint-disable-line compat/compat + var mapA = new Map(); mapA.set(6, 3); mapA.set(5, 1); - var mapB = new Map(); // eslint-disable-line compat/compat + var mapB = new Map(); mapB.set(6, 4); mapB.set(5, 1); @@ -764,77 +645,61 @@ describe('matchersUtil', function() { }); it('fails for maps of different size', function() { - jasmine.getEnv().requireFunctioningMaps(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var mapA = new Map(); // eslint-disable-line compat/compat + var mapA = new Map(); mapA.set(6, 3); - var mapB = new Map(); // eslint-disable-line compat/compat + var mapB = new Map(); mapB.set(6, 4); mapB.set(5, 1); expect(matchersUtil.equals(mapA, mapB)).toBe(false); }); it('passes when comparing two identical URLs', function() { - jasmine.getEnv().requireUrls(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(); expect( matchersUtil.equals( - // eslint-disable-next-line compat/compat new URL('http://localhost/1'), - // eslint-disable-next-line compat/compat new URL('http://localhost/1') ) ).toBe(true); }); it('fails when comparing two different URLs', function() { - jasmine.getEnv().requireUrls(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(), - // eslint-disable-next-line compat/compat url1 = new URL('http://localhost/1'); - // eslint-disable-next-line compat/compat expect(matchersUtil.equals(url1, new URL('http://localhost/2'))).toBe( false ); - // eslint-disable-next-line compat/compat expect(matchersUtil.equals(url1, new URL('http://localhost/1?foo'))).toBe( false ); - // eslint-disable-next-line compat/compat expect(matchersUtil.equals(url1, new URL('http://localhost/1#foo'))).toBe( false ); - // eslint-disable-next-line compat/compat expect(matchersUtil.equals(url1, new URL('https://localhost/1'))).toBe( false ); expect( - // eslint-disable-next-line compat/compat matchersUtil.equals(url1, new URL('http://localhost:8080/1')) ).toBe(false); - // eslint-disable-next-line compat/compat expect(matchersUtil.equals(url1, new URL('http://example.com/1'))).toBe( false ); }); it('passes for ArrayBuffers with same length and content', function() { - jasmine.getEnv().requireFunctioningArrayBuffers(); - var buffer1 = new ArrayBuffer(4); // eslint-disable-line compat/compat - var buffer2 = new ArrayBuffer(4); // eslint-disable-line compat/compat + var buffer1 = new ArrayBuffer(4); + var buffer2 = new ArrayBuffer(4); var matchersUtil = new jasmineUnderTest.MatchersUtil(); expect(matchersUtil.equals(buffer1, buffer2)).toBe(true); }); it('fails for ArrayBuffers with same length but different content', function() { - jasmine.getEnv().requireFunctioningArrayBuffers(); - var buffer1 = new ArrayBuffer(4); // eslint-disable-line compat/compat - var buffer2 = new ArrayBuffer(4); // eslint-disable-line compat/compat - var array1 = new Uint8Array(buffer1); // eslint-disable-line compat/compat + var buffer1 = new ArrayBuffer(4); + var buffer2 = new ArrayBuffer(4); + var array1 = new Uint8Array(buffer1); array1[0] = 1; var matchersUtil = new jasmineUnderTest.MatchersUtil(); expect(matchersUtil.equals(buffer1, buffer2)).toBe(false); @@ -843,15 +708,12 @@ describe('matchersUtil', function() { describe('Typed arrays', function() { it('fails for typed arrays of same length and contents but different types', function() { var matchersUtil = new jasmineUnderTest.MatchersUtil(); - // eslint-disable-next-line compat/compat var a1 = new Int8Array(1); - // eslint-disable-next-line compat/compat var a2 = new Uint8Array(1); a1[0] = a2[0] = 0; expect(matchersUtil.equals(a1, a2)).toBe(false); }); - // eslint-disable-next-line compat/compat [ 'Int8Array', 'Uint8Array', @@ -863,20 +725,11 @@ describe('matchersUtil', function() { 'Float32Array', 'Float64Array' ].forEach(function(typeName) { - function requireType() { - var TypedArrayCtor = jasmine.getGlobal()[typeName]; - - if (!TypedArrayCtor) { - pending('Browser does not support ' + typeName); - } - - return TypedArrayCtor; - } + var TypedArrayCtor = jasmine.getGlobal()[typeName]; it( 'passes for ' + typeName + 's with same length and content', function() { - var TypedArrayCtor = requireType(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); var a1 = new TypedArrayCtor(2); var a2 = new TypedArrayCtor(2); @@ -887,7 +740,6 @@ describe('matchersUtil', function() { ); it('fails for ' + typeName + 's with different length', function() { - var TypedArrayCtor = requireType(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); var a1 = new TypedArrayCtor(2); var a2 = new TypedArrayCtor(1); @@ -898,7 +750,6 @@ describe('matchersUtil', function() { it( 'fails for ' + typeName + 's with same length but different content', function() { - var TypedArrayCtor = requireType(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); var a1 = new TypedArrayCtor(1); var a2 = new TypedArrayCtor(1); @@ -909,7 +760,6 @@ describe('matchersUtil', function() { ); it('checks nonstandard properties of ' + typeName, function() { - var TypedArrayCtor = requireType(); var matchersUtil = new jasmineUnderTest.MatchersUtil(); var a1 = new TypedArrayCtor(1); var a2 = new TypedArrayCtor(1); @@ -919,7 +769,6 @@ describe('matchersUtil', function() { }); it('works with custom equality testers with ' + typeName, function() { - var TypedArrayCtor = requireType(); var a1 = new TypedArrayCtor(1); var a2 = new TypedArrayCtor(1); var matchersUtil = new jasmineUnderTest.MatchersUtil({ @@ -993,11 +842,16 @@ describe('matchersUtil', function() { Array.prototype, 'findIndex' ); - if (!findIndexDescriptor) { - return; - } beforeEach(function() { + if (!findIndexDescriptor) { + jasmine + .getEnv() + .pending( + 'Environment does not have a property descriptor for Array.prototype.findIndex' + ); + } + Object.defineProperty(Array.prototype, 'findIndex', { enumerable: true, value: function(predicate) { @@ -1105,57 +959,6 @@ describe('matchersUtil', function() { }); }); - it('logs a deprecation warning when custom equality testers are passed', function() { - var matchersUtil = new jasmineUnderTest.MatchersUtil(), - deprecated = spyOn(jasmineUnderTest.getEnv(), 'deprecated'); - - matchersUtil.equals(0, 0, []); - - expect(deprecated).toHaveBeenCalledWith( - jasmine.stringMatching( - 'Passing custom equality testers ' + - 'to MatchersUtil#equals is deprecated. ' + - 'See for details.' - ) - ); - }); - - it('logs a deprecation warning when a diffBuilder is provided as the fourth argument', function() { - var matchersUtil = new jasmineUnderTest.MatchersUtil(), - deprecated = spyOn(jasmineUnderTest.getEnv(), 'deprecated'); - - matchersUtil.equals(0, 0, null, new jasmineUnderTest.NullDiffBuilder()); - - expect(deprecated).toHaveBeenCalledWith( - jasmine.stringMatching( - 'Diff builder should be passed as the ' + - 'third argument to MatchersUtil#equals, not the fourth. ' + - 'See for details.' - ) - ); - }); - - it('uses a diffBuilder if one is provided as the fourth argument', function() { - // TODO: remove this in the next major release. - var diffBuilder = new jasmineUnderTest.DiffBuilder(), - matchersUtil = new jasmineUnderTest.MatchersUtil(); - - spyOn(jasmineUnderTest.getEnv(), 'deprecated'); // suppress warning - spyOn(diffBuilder, 'recordMismatch'); - spyOn(diffBuilder, 'withPath').and.callThrough(); - - matchersUtil.equals([1], [2], [], diffBuilder); - expect(diffBuilder.withPath).toHaveBeenCalledWith( - 'length', - jasmine.any(Function) - ); - expect(diffBuilder.withPath).toHaveBeenCalledWith( - 0, - jasmine.any(Function) - ); - expect(diffBuilder.recordMismatch).toHaveBeenCalledWith(); - }); - it('uses a diffBuilder if one is provided as the third argument', function() { var diffBuilder = new jasmineUnderTest.DiffBuilder(), matchersUtil = new jasmineUnderTest.MatchersUtil(); @@ -1205,25 +1008,7 @@ describe('matchersUtil', function() { ).toBe(true); }); - it('uses custom equality testers if passed to contains and actual is an Array', function() { - // TODO: remove this in the next major release. - var customTester = function(a, b) { - return true; - }, - matchersUtil = new jasmineUnderTest.MatchersUtil(), - deprecated = spyOn(jasmineUnderTest.getEnv(), 'deprecated'); - - expect(matchersUtil.contains([1, 2], 3, [customTester])).toBe(true); - - expect(deprecated).toHaveBeenCalledWith( - jasmine.stringMatching( - 'Passing custom equality testers to MatchersUtil#contains is deprecated. ' + - 'See for details.' - ) - ); - }); - - it('uses custom equality testers if passed to the constructor and actual is an Array', function() { + it('uses custom equality testers if actual is an Array', function() { var customTester = function(a, b) { return true; }, @@ -1235,22 +1020,6 @@ describe('matchersUtil', function() { expect(matchersUtil.contains([1, 2], 3)).toBe(true); }); - it('logs a single deprecation warning when custom equality testers are passed', function() { - // TODO: remove this in the next major release. - var matchersUtil = new jasmineUnderTest.MatchersUtil(), - deprecated = spyOn(jasmineUnderTest.getEnv(), 'deprecated'); - - matchersUtil.contains([0], 0, []); - - expect(deprecated).toHaveBeenCalledOnceWith( - jasmine.stringMatching( - 'Passing custom equality testers ' + - 'to MatchersUtil#contains is deprecated. ' + - 'See for details.' - ) - ); - }); - it('fails when actual is undefined', function() { var matchersUtil = new jasmineUnderTest.MatchersUtil(); expect(matchersUtil.contains(undefined, 'A')).toBe(false); @@ -1261,7 +1030,7 @@ describe('matchersUtil', function() { expect(matchersUtil.contains(null, 'A')).toBe(false); }); - it('passes with array-like objects', function() { + it('works with array-like objects that implement iterable', function() { var capturedArgs = null, matchersUtil = new jasmineUnderTest.MatchersUtil(); @@ -1271,28 +1040,36 @@ describe('matchersUtil', function() { testFunction('foo', 'bar'); expect(matchersUtil.contains(capturedArgs, 'bar')).toBe(true); + expect(matchersUtil.contains(capturedArgs, 'baz')).toBe(false); + }); + + it("passes with array-like objects that don't implement iterable", function() { + const arrayLike = { + 0: 'a', + 1: 'b', + length: 2 + }; + const matchersUtil = new jasmineUnderTest.MatchersUtil(); + + expect(matchersUtil.contains(arrayLike, 'b')).toBe(true); + expect(matchersUtil.contains(arrayLike, 'c')).toBe(false); }); it('passes for set members', function() { - jasmine.getEnv().requireFunctioningSets(); - var matchersUtil = new jasmineUnderTest.MatchersUtil(); var setItem = { foo: 'bar' }; - var set = new Set(); // eslint-disable-line compat/compat + var set = new Set(); set.add(setItem); expect(matchersUtil.contains(set, setItem)).toBe(true); }); - // documenting current behavior - it('fails (!) for objects that equal to a set member', function() { - jasmine.getEnv().requireFunctioningSets(); - + it('passes for objects that equal to a set member', function() { var matchersUtil = new jasmineUnderTest.MatchersUtil(); - var set = new Set(); // eslint-disable-line compat/compat + var set = new Set(); set.add({ foo: 'bar' }); - expect(matchersUtil.contains(set, { foo: 'bar' })).toBe(false); + expect(matchersUtil.contains(set, { foo: 'bar' })).toBe(true); }); }); diff --git a/spec/core/matchers/toBeInstanceOfSpec.js b/spec/core/matchers/toBeInstanceOfSpec.js index f63ec842..252122f1 100644 --- a/spec/core/matchers/toBeInstanceOfSpec.js +++ b/spec/core/matchers/toBeInstanceOfSpec.js @@ -104,8 +104,6 @@ describe('toBeInstanceOf', function() { }); it('passes for an async function', function() { - jasmine.getEnv().requireAsyncAwait(); - var fn = eval("(async function fn() { return 'foo'; })"); var matcher = jasmineUnderTest.matchers.toBeInstanceOf(); diff --git a/spec/core/matchers/toEqualSpec.js b/spec/core/matchers/toEqualSpec.js index 06a4f982..5eed167d 100644 --- a/spec/core/matchers/toEqualSpec.js +++ b/spec/core/matchers/toEqualSpec.js @@ -257,8 +257,8 @@ describe('toEqual', function() { }); it('reports mismatches between arrays of different types', function() { - var actual = new Uint32Array([1, 2, 3]), // eslint-disable-line compat/compat - expected = new Uint16Array([1, 2, 3]), // eslint-disable-line compat/compat + var actual = new Uint32Array([1, 2, 3]), + expected = new Uint16Array([1, 2, 3]), message = 'Expected Uint32Array [ 1, 2, 3 ] to equal Uint16Array [ 1, 2, 3 ].'; @@ -460,11 +460,9 @@ describe('toEqual', function() { // == Sets == it('reports mismatches between Sets', function() { - jasmine.getEnv().requireFunctioningSets(); - - var actual = new Set(); // eslint-disable-line compat/compat + var actual = new Set(); actual.add(1); - var expected = new Set(); // eslint-disable-line compat/compat + var expected = new Set(); expected.add(2); var message = 'Expected Set( 1 ) to equal Set( 2 ).'; @@ -472,11 +470,9 @@ describe('toEqual', function() { }); it('reports deep mismatches within Sets', function() { - jasmine.getEnv().requireFunctioningSets(); - - var actual = new Set(); // eslint-disable-line compat/compat + var actual = new Set(); actual.add({ x: 1 }); - var expected = new Set(); // eslint-disable-line compat/compat + var expected = new Set(); expected.add({ x: 2 }); var message = 'Expected Set( Object({ x: 1 }) ) to equal Set( Object({ x: 2 }) ).'; @@ -485,11 +481,9 @@ describe('toEqual', function() { }); it('reports mismatches between Sets nested in objects', function() { - jasmine.getEnv().requireFunctioningSets(); - - var actualSet = new Set(); // eslint-disable-line compat/compat + var actualSet = new Set(); actualSet.add(1); - var expectedSet = new Set(); // eslint-disable-line compat/compat + var expectedSet = new Set(); expectedSet.add(2); var actual = { sets: [actualSet] }; @@ -500,12 +494,10 @@ describe('toEqual', function() { }); it('reports mismatches between Sets of different lengths', function() { - jasmine.getEnv().requireFunctioningSets(); - - var actual = new Set(); // eslint-disable-line compat/compat + var actual = new Set(); actual.add(1); actual.add(2); - var expected = new Set(); // eslint-disable-line compat/compat + var expected = new Set(); expected.add(2); var message = 'Expected Set( 1, 2 ) to equal Set( 2 ).'; @@ -513,13 +505,11 @@ describe('toEqual', function() { }); it('reports mismatches between Sets where actual is missing a value from expected', function() { - jasmine.getEnv().requireFunctioningSets(); - // Use 'duplicate' object in actual so sizes match - var actual = new Set(); // eslint-disable-line compat/compat + var actual = new Set(); actual.add({ x: 1 }); actual.add({ x: 1 }); - var expected = new Set(); // eslint-disable-line compat/compat + var expected = new Set(); expected.add({ x: 1 }); expected.add({ x: 2 }); var message = @@ -529,13 +519,11 @@ describe('toEqual', function() { }); it('reports mismatches between Sets where actual has a value missing from expected', function() { - jasmine.getEnv().requireFunctioningSets(); - // Use 'duplicate' object in expected so sizes match - var actual = new Set(); // eslint-disable-line compat/compat + var actual = new Set(); actual.add({ x: 1 }); actual.add({ x: 2 }); - var expected = new Set(); // eslint-disable-line compat/compat + var expected = new Set(); expected.add({ x: 1 }); expected.add({ x: 1 }); var message = @@ -547,23 +535,19 @@ describe('toEqual', function() { // == Maps == it('does not report mismatches between deep equal Maps', function() { - jasmine.getEnv().requireFunctioningMaps(); - // values are the same but with different object identity - var actual = new Map(); // eslint-disable-line compat/compat + var actual = new Map(); actual.set('a', { x: 1 }); - var expected = new Map(); // eslint-disable-line compat/compat + var expected = new Map(); expected.set('a', { x: 1 }); expect(compareEquals(actual, expected).pass).toBe(true); }); it('reports deep mismatches within Maps', function() { - jasmine.getEnv().requireFunctioningMaps(); - - var actual = new Map(); // eslint-disable-line compat/compat + var actual = new Map(); actual.set('a', { x: 1 }); - var expected = new Map(); // eslint-disable-line compat/compat + var expected = new Map(); expected.set('a', { x: 2 }); var message = "Expected Map( [ 'a', Object({ x: 1 }) ] ) to equal Map( [ 'a', Object({ x: 2 }) ] )."; @@ -572,11 +556,9 @@ describe('toEqual', function() { }); it('reports mismatches between Maps nested in objects', function() { - jasmine.getEnv().requireFunctioningMaps(); - - var actual = { Maps: [new Map()] }; // eslint-disable-line compat/compat + var actual = { Maps: [new Map()] }; actual.Maps[0].set('a', 1); - var expected = { Maps: [new Map()] }; // eslint-disable-line compat/compat + var expected = { Maps: [new Map()] }; expected.Maps[0].set('a', 2); var message = @@ -586,11 +568,9 @@ describe('toEqual', function() { }); it('reports mismatches between Maps of different lengths', function() { - jasmine.getEnv().requireFunctioningMaps(); - - var actual = new Map(); // eslint-disable-line compat/compat + var actual = new Map(); actual.set('a', 1); - var expected = new Map(); // eslint-disable-line compat/compat + var expected = new Map(); expected.set('a', 2); expected.set('b', 1); var message = @@ -600,11 +580,9 @@ describe('toEqual', function() { }); it('reports mismatches between Maps with equal values but differing keys', function() { - jasmine.getEnv().requireFunctioningMaps(); - - var actual = new Map(); // eslint-disable-line compat/compat + var actual = new Map(); actual.set('a', 1); - var expected = new Map(); // eslint-disable-line compat/compat + var expected = new Map(); expected.set('b', 1); var message = "Expected Map( [ 'a', 1 ] ) to equal Map( [ 'b', 1 ] )."; @@ -612,22 +590,19 @@ describe('toEqual', function() { }); it('does not report mismatches between Maps with keys with same object identity', function() { - jasmine.getEnv().requireFunctioningMaps(); var key = { x: 1 }; - var actual = new Map(); // eslint-disable-line compat/compat + var actual = new Map(); actual.set(key, 2); - var expected = new Map(); // eslint-disable-line compat/compat + var expected = new Map(); expected.set(key, 2); expect(compareEquals(actual, expected).pass).toBe(true); }); it('reports mismatches between Maps with identical keys with different object identity', function() { - jasmine.getEnv().requireFunctioningMaps(); - - var actual = new Map(); // eslint-disable-line compat/compat + var actual = new Map(); actual.set({ x: 1 }, 2); - var expected = new Map(); // eslint-disable-line compat/compat + var expected = new Map(); expected.set({ x: 1 }, 2); var message = 'Expected Map( [ Object({ x: 1 }), 2 ] ) to equal Map( [ Object({ x: 1 }), 2 ] ).'; @@ -636,37 +611,29 @@ describe('toEqual', function() { }); it('does not report mismatches when comparing Map key to jasmine.anything()', function() { - jasmine.getEnv().requireFunctioningMaps(); - - var actual = new Map(); // eslint-disable-line compat/compat + var actual = new Map(); actual.set('a', 1); - var expected = new Map(); // eslint-disable-line compat/compat + var expected = new Map(); expected.set(jasmineUnderTest.anything(), 1); expect(compareEquals(actual, expected).pass).toBe(true); }); it('does not report mismatches when comparing Maps with the same symbol keys', function() { - jasmine.getEnv().requireFunctioningMaps(); - jasmine.getEnv().requireFunctioningSymbols(); - - var key = Symbol(); // eslint-disable-line compat/compat - var actual = new Map(); // eslint-disable-line compat/compat + var key = Symbol(); + var actual = new Map(); actual.set(key, 1); - var expected = new Map(); // eslint-disable-line compat/compat + var expected = new Map(); expected.set(key, 1); expect(compareEquals(actual, expected).pass).toBe(true); }); it('reports mismatches between Maps with different symbol keys', function() { - jasmine.getEnv().requireFunctioningMaps(); - jasmine.getEnv().requireFunctioningSymbols(); - - var actual = new Map(); // eslint-disable-line compat/compat - actual.set(Symbol(), 1); // eslint-disable-line compat/compat - var expected = new Map(); // eslint-disable-line compat/compat - expected.set(Symbol(), 1); // eslint-disable-line compat/compat + var actual = new Map(); + actual.set(Symbol(), 1); + var expected = new Map(); + expected.set(Symbol(), 1); var message = 'Expected Map( [ Symbol(), 1 ] ) to equal Map( [ Symbol(), 1 ] ).'; @@ -674,12 +641,9 @@ describe('toEqual', function() { }); it('does not report mismatches when comparing Map symbol key to jasmine.anything()', function() { - jasmine.getEnv().requireFunctioningMaps(); - jasmine.getEnv().requireFunctioningSymbols(); - - var actual = new Map(); // eslint-disable-line compat/compat - actual.set(Symbol(), 1); // eslint-disable-line compat/compat - var expected = new Map(); // eslint-disable-line compat/compat + var actual = new Map(); + actual.set(Symbol(), 1); + var expected = new Map(); expected.set(jasmineUnderTest.anything(), 1); expect(compareEquals(actual, expected).pass).toBe(true); diff --git a/spec/core/matchers/toHaveBeenCalledBeforeSpec.js b/spec/core/matchers/toHaveBeenCalledBeforeSpec.js index 2bf316e3..b8ad4951 100644 --- a/spec/core/matchers/toHaveBeenCalledBeforeSpec.js +++ b/spec/core/matchers/toHaveBeenCalledBeforeSpec.js @@ -30,7 +30,7 @@ describe('toHaveBeenCalledBefore', function() { secondSpy(); - result = matcher.compare(firstSpy, secondSpy); + const result = matcher.compare(firstSpy, secondSpy); expect(result.pass).toBe(false); expect(result.message).toMatch( /Expected spy first spy to have been called./ @@ -44,7 +44,7 @@ describe('toHaveBeenCalledBefore', function() { firstSpy(); - result = matcher.compare(firstSpy, secondSpy); + const result = matcher.compare(firstSpy, secondSpy); expect(result.pass).toBe(false); expect(result.message).toMatch( /Expected spy second spy to have been called./ diff --git a/spec/core/matchers/toHaveSizeSpec.js b/spec/core/matchers/toHaveSizeSpec.js index fc5baf91..afcf8e81 100644 --- a/spec/core/matchers/toHaveSizeSpec.js +++ b/spec/core/matchers/toHaveSizeSpec.js @@ -1,4 +1,3 @@ -/* eslint-disable compat/compat */ describe('toHaveSize', function() { 'use strict'; @@ -59,8 +58,6 @@ describe('toHaveSize', function() { }); it('passes for a Map whose length matches', function() { - jasmine.getEnv().requireFunctioningMaps(); - var map = new Map(); map.set('a', 1); map.set('b', 2); @@ -72,8 +69,6 @@ describe('toHaveSize', function() { }); it('fails for a Map whose length does not match', function() { - jasmine.getEnv().requireFunctioningMaps(); - var map = new Map(); map.set('a', 1); map.set('b', 2); @@ -85,8 +80,6 @@ describe('toHaveSize', function() { }); it('passes for a Set whose length matches', function() { - jasmine.getEnv().requireFunctioningSets(); - var set = new Set(); set.add('a'); set.add('b'); @@ -98,8 +91,6 @@ describe('toHaveSize', function() { }); it('fails for a Set whose length does not match', function() { - jasmine.getEnv().requireFunctioningSets(); - var set = new Set(); set.add('a'); set.add('b'); @@ -111,7 +102,6 @@ describe('toHaveSize', function() { }); it('throws an error for WeakSet', function() { - jasmine.getEnv().requireWeakSets(); var matcher = jasmineUnderTest.matchers.toHaveSize(); expect(function() { @@ -120,7 +110,6 @@ describe('toHaveSize', function() { }); it('throws an error for WeakMap', function() { - jasmine.getEnv().requireWeakMaps(); var matcher = jasmineUnderTest.matchers.toHaveSize(); expect(function() { diff --git a/spec/core/matchers/toThrowErrorSpec.js b/spec/core/matchers/toThrowErrorSpec.js index c8532276..6d76a1d1 100644 --- a/spec/core/matchers/toThrowErrorSpec.js +++ b/spec/core/matchers/toThrowErrorSpec.js @@ -92,16 +92,9 @@ describe('toThrowError', function() { iframe.src = 'about:blank'; var iframeDocument = iframe.contentWindow.document; - if (iframeDocument.body) { - iframeDocument.body.appendChild( - iframeDocument.createElement('script') - ).textContent = "function method() { throw new Error('foo'); }"; - } else { - // IE 10 and older - iframeDocument.write( - "" - ); - } + iframeDocument.body.appendChild( + iframeDocument.createElement('script') + ).textContent = "function method() { throw new Error('foo'); }"; var result = matcher.compare(iframe.contentWindow.method); expect(result.pass).toBe(true); diff --git a/spec/helpers/asyncAwait.js b/spec/helpers/asyncAwait.js deleted file mode 100644 index 9cdead0d..00000000 --- a/spec/helpers/asyncAwait.js +++ /dev/null @@ -1,26 +0,0 @@ -(function(env) { - function getAsyncCtor() { - try { - eval('var func = async function(){};'); - } catch (e) { - return null; - } - - return Object.getPrototypeOf(func).constructor; - } - - function hasAsyncAwaitSupport() { - return getAsyncCtor() !== null; - } - - env.makeAsyncAwaitFunction = function() { - var AsyncFunction = getAsyncCtor(); - return new AsyncFunction(''); - }; - - env.requireAsyncAwait = function() { - if (!hasAsyncAwaitSupport()) { - env.pending('Environment does not support async/await functions'); - } - }; -})(jasmine.getEnv()); diff --git a/spec/helpers/checkForArrayBuffer.js b/spec/helpers/checkForArrayBuffer.js deleted file mode 100644 index bf49a531..00000000 --- a/spec/helpers/checkForArrayBuffer.js +++ /dev/null @@ -1,24 +0,0 @@ -/* eslint-disable compat/compat */ -(function(env) { - function hasFunctioningArrayBuffers() { - if (typeof ArrayBuffer === 'undefined') { - return false; - } - - try { - var buffer = new ArrayBuffer(2); - var view8bit = new Uint8Array(buffer); - var view16bit = new Uint16Array(buffer); - view16bit[0] = 0xabcd; - return view8bit[0] === 0xcd && view8bit[1] === 0xab; - } catch (e) { - return false; - } - } - - env.requireFunctioningArrayBuffers = function() { - if (!hasFunctioningArrayBuffers()) { - env.pending('Browser has incomplete or missing support for ArrayBuffer'); - } - }; -})(jasmine.getEnv()); diff --git a/spec/helpers/checkForMap.js b/spec/helpers/checkForMap.js deleted file mode 100644 index b8bdacd3..00000000 --- a/spec/helpers/checkForMap.js +++ /dev/null @@ -1,53 +0,0 @@ -/* eslint-disable compat/compat */ -(function(env) { - env.hasFunctioningMaps = function() { - if (typeof Map === 'undefined') { - return false; - } - - try { - var s = new Map(); - s.set('a', 1); - s.set('b', 2); - - if (s.size !== 2) { - return false; - } - if (s.has('a') !== true) { - return false; - } - - var iterations = 0; - var ifForEachWorking = true; - s.forEach(function(value, key, map) { - ifForEachWorking = ifForEachWorking && map === s; - if (key === 'a') { - ifForEachWorking = ifForEachWorking && value === 1; - } - iterations++; - }); - if (iterations !== 2) { - return false; - } - if (ifForEachWorking !== true) { - return false; - } - - return true; - } catch (e) { - return false; - } - }; - - env.requireFunctioningMaps = function() { - if (!env.hasFunctioningMaps()) { - env.pending('Browser has incomplete or missing support for Maps'); - } - }; - - env.requireWeakMaps = function() { - if (typeof WeakMap === 'undefined') { - env.pending('Browser does not have support for WeakMap'); - } - }; -})(jasmine.getEnv()); diff --git a/spec/helpers/checkForProxy.js b/spec/helpers/checkForProxy.js deleted file mode 100644 index b4062d0b..00000000 --- a/spec/helpers/checkForProxy.js +++ /dev/null @@ -1,17 +0,0 @@ -/* eslint-disable compat/compat */ -(function(env) { - function hasProxyConstructor() { - try { - new Proxy({}, {}); - return true; - } catch (e) { - return false; - } - } - - env.requireProxy = function() { - if (!hasProxyConstructor()) { - env.pending('Environment does not support Proxy'); - } - }; -})(jasmine.getEnv()); diff --git a/spec/helpers/checkForSet.js b/spec/helpers/checkForSet.js deleted file mode 100644 index cae95db7..00000000 --- a/spec/helpers/checkForSet.js +++ /dev/null @@ -1,57 +0,0 @@ -/* eslint-disable compat/compat */ -(function(env) { - env.hasFunctioningSets = function() { - if (typeof Set === 'undefined') { - return false; - } - - try { - var s = new Set(); - s.add(1); - s.add(2); - - if (s.size !== 2) { - return false; - } - if (s.has(1) !== true) { - return false; - } - - var iterations = 0; - var isForEachWorking = true; - s.forEach(function(value, key, set) { - isForEachWorking = isForEachWorking && set === s; - - if (iterations === 0) { - isForEachWorking = isForEachWorking && key === value && value === 1; - } else if (iterations === 1) { - isForEachWorking = isForEachWorking && key === value && value === 2; - } - - iterations++; - }); - if (iterations !== 2) { - return false; - } - if (isForEachWorking !== true) { - return false; - } - - return true; - } catch (e) { - return false; - } - }; - - env.requireFunctioningSets = function() { - if (!env.hasFunctioningSets()) { - env.pending('Browser has incomplete or missing support for Sets'); - } - }; - - env.requireWeakSets = function() { - if (typeof WeakSet === 'undefined') { - env.pending('Browser does not have support for WeakSet'); - } - }; -})(jasmine.getEnv()); diff --git a/spec/helpers/checkForSymbol.js b/spec/helpers/checkForSymbol.js deleted file mode 100644 index 8b5e4b1e..00000000 --- a/spec/helpers/checkForSymbol.js +++ /dev/null @@ -1,28 +0,0 @@ -/* eslint-disable compat/compat */ -(function(env) { - function hasFunctioningSymbols() { - if (typeof Symbol === 'undefined') { - return false; - } - - try { - var s1 = Symbol(); - var s2 = Symbol(); - if (typeof s1 !== 'symbol') { - return false; - } - if (s1 === s2) { - return false; - } - return true; - } catch (e) { - return false; - } - } - - env.requireFunctioningSymbols = function() { - if (!hasFunctioningSymbols()) { - env.pending('Browser has incomplete or missing support for Symbols'); - } - }; -})(jasmine.getEnv()); diff --git a/spec/helpers/checkForUrl.js b/spec/helpers/checkForUrl.js deleted file mode 100644 index f8401fbb..00000000 --- a/spec/helpers/checkForUrl.js +++ /dev/null @@ -1,17 +0,0 @@ -/* eslint-disable compat/compat */ -(function(env) { - function hasUrlConstructor() { - try { - new URL('http://localhost/'); - return true; - } catch (e) { - return false; - } - } - - env.requireUrls = function() { - if (!hasUrlConstructor()) { - env.pending('Environment does not support URLs'); - } - }; -})(jasmine.getEnv()); diff --git a/spec/helpers/generator.js b/spec/helpers/generator.js deleted file mode 100644 index b62f5acd..00000000 --- a/spec/helpers/generator.js +++ /dev/null @@ -1,22 +0,0 @@ -(function(env) { - function getGeneratorFuncCtor() { - try { - eval('var func = function*() {}'); - } catch (e) { - return null; - } - - return Object.getPrototypeOf(func).constructor; - } - - env.makeGeneratorFunction = function(text) { - var GeneratorFunction = getGeneratorFuncCtor(); - return new GeneratorFunction(text || ''); - }; - - env.requireGeneratorFunctions = function() { - if (!getGeneratorFuncCtor()) { - env.pending('Environment does not support generator functions'); - } - }; -})(jasmine.getEnv()); diff --git a/spec/helpers/nodeDefineJasmineUnderTest.js b/spec/helpers/nodeDefineJasmineUnderTest.js index 739c20af..c91bdc5f 100644 --- a/spec/helpers/nodeDefineJasmineUnderTest.js +++ b/spec/helpers/nodeDefineJasmineUnderTest.js @@ -1,6 +1,6 @@ (function() { var path = require('path'), - fg = require('fast-glob'); + glob = require('glob'); var jasmineUnderTestRequire = require(path.join( __dirname, @@ -16,7 +16,8 @@ return path.join(__dirname, '../../', 'src/', file); }); - fg.sync(src_files).forEach(function(resolvedFile) { + const files = src_files.flatMap(g => glob.sync(g)); + files.forEach(function(resolvedFile) { require(resolvedFile); }); } diff --git a/spec/helpers/promises.js b/spec/helpers/promises.js deleted file mode 100644 index 208a9f70..00000000 --- a/spec/helpers/promises.js +++ /dev/null @@ -1,13 +0,0 @@ -(function(env) { - env.requirePromises = function() { - if (typeof Promise !== 'function') { - env.pending('Environment does not support promises'); - } - }; - - env.requireNoPromises = function() { - if (typeof Promise === 'function') { - env.pending('Environment supports promises'); - } - }; -})(jasmine.getEnv()); diff --git a/spec/html/HtmlReporterSpec.js b/spec/html/HtmlReporterSpec.js index d098fbc1..8a8ae4f2 100644 --- a/spec/html/HtmlReporterSpec.js +++ b/spec/html/HtmlReporterSpec.js @@ -73,10 +73,6 @@ describe('HtmlReporter', function() { describe('and no expectations ran', function() { var container, reporter; beforeEach(function() { - if (typeof console === 'undefined') { - console = { warn: function() {}, error: function() {} }; - } - container = document.createElement('div'); reporter = new jasmineUnderTest.HtmlReporter({ env: env, @@ -704,6 +700,50 @@ describe('HtmlReporter', function() { expect(alertBars[2].innerHTML).not.toMatch(/line/); }); + it('does not display the "AfterAll" prefix for other error types', function() { + const container = document.createElement('div'); + const getContainer = function() { + return container; + }; + const reporter = new jasmineUnderTest.HtmlReporter({ + env: env, + getContainer: getContainer, + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + } + }); + + reporter.initialize(); + + reporter.jasmineStarted({}); + reporter.jasmineDone({ + failedExpectations: [ + { message: 'load error', globalErrorType: 'load' }, + { + message: 'lateExpectation error', + globalErrorType: 'lateExpectation' + }, + { message: 'lateError error', globalErrorType: 'lateError' } + ] + }); + + const alertBars = container.querySelectorAll( + '.jasmine-alert .jasmine-bar' + ); + + expect(alertBars.length).toEqual(4); + expect(alertBars[1].textContent).toContain('load error'); + expect(alertBars[2].textContent).toContain('lateExpectation error'); + expect(alertBars[3].textContent).toContain('lateError error'); + + for (let bar of alertBars) { + expect(bar.textContent).not.toContain('AfterAll'); + } + }); + it('displays file and line information if available', function() { var container = document.createElement('div'), getContainer = function() { @@ -818,7 +858,10 @@ describe('HtmlReporter', function() { var stopOnFailureUI = container.querySelector('.jasmine-fail-fast'); stopOnFailureUI.click(); - expect(navigationHandler).toHaveBeenCalledWith('failFast', true); + expect(navigationHandler).toHaveBeenCalledWith( + 'stopOnSpecFailure', + true + ); }); it('should navigate and turn the setting off', function() { @@ -847,7 +890,10 @@ describe('HtmlReporter', function() { var stopOnFailureUI = container.querySelector('.jasmine-fail-fast'); stopOnFailureUI.click(); - expect(navigationHandler).toHaveBeenCalledWith('failFast', false); + expect(navigationHandler).toHaveBeenCalledWith( + 'stopOnSpecFailure', + false + ); }); }); @@ -924,7 +970,10 @@ describe('HtmlReporter', function() { var throwingExpectationsUI = container.querySelector('.jasmine-throw'); throwingExpectationsUI.click(); - expect(navigateHandler).toHaveBeenCalledWith('oneFailurePerSpec', true); + expect(navigateHandler).toHaveBeenCalledWith( + 'stopSpecOnExpectationFailure', + true + ); }); it('should navigate and change the setting to off', function() { @@ -954,7 +1003,7 @@ describe('HtmlReporter', function() { throwingExpectationsUI.click(); expect(navigateHandler).toHaveBeenCalledWith( - 'oneFailurePerSpec', + 'stopSpecOnExpectationFailure', false ); }); @@ -1461,6 +1510,23 @@ describe('HtmlReporter', function() { } ] }; + var failingSpecResultWithDebugLogs = { + id: 567, + status: 'failed', + description: 'a failing spec', + fullName: 'a suite inner suite a failing spec', + passedExpectations: [], + failedExpectations: [ + { + message: 'a failure message', + stack: 'a stack trace' + } + ], + debugLogs: [ + { timestamp: 123, message: 'msg 1' }, + { timestamp: 456, message: 'msg 1' } + ] + }; var passingSuiteResult = { id: 1, @@ -1478,18 +1544,20 @@ describe('HtmlReporter', function() { reporter.suiteDone(passingSuiteResult); reporter.suiteDone(failingSuiteResult); reporter.suiteDone(passingSuiteResult); + reporter.specStarted(failingSpecResultWithDebugLogs); + reporter.specDone(failingSpecResultWithDebugLogs); reporter.jasmineDone({}); }); it('reports the specs counts', function() { var alertBar = container.querySelector('.jasmine-alert .jasmine-bar'); - expect(alertBar.innerHTML).toMatch(/2 specs, 2 failure/); + expect(alertBar.innerHTML).toMatch(/3 specs, 3 failures/); }); it('reports failure messages and stack traces', function() { var specFailures = container.querySelector('.jasmine-failures'); - expect(specFailures.childNodes.length).toEqual(2); + expect(specFailures.childNodes.length).toEqual(3); var specFailure = specFailures.childNodes[0]; expect(specFailure.getAttribute('class')).toMatch(/jasmine-failed/); @@ -1530,6 +1598,18 @@ describe('HtmlReporter', function() { expect(suiteStackTrace.innerHTML).toEqual('a stack trace'); }); + it('reports traces when present', function() { + var specFailure = container.querySelectorAll( + '.jasmine-spec-detail.jasmine-failed' + )[2], + debugLogs = specFailure.querySelector('.jasmine-debug-log table'), + rows; + + expect(debugLogs).toBeTruthy(); + rows = debugLogs.querySelectorAll('tbody tr'); + expect(rows.length).toEqual(2); + }); + it('provides links to focus on a failure and each containing suite', function() { var description = container.querySelector( '.jasmine-failures .jasmine-description' @@ -1573,6 +1653,61 @@ describe('HtmlReporter', function() { ); }); }); + + it('counts failures that are reported in the jasmineDone event', function() { + const container = document.createElement('div'); + function getContainer() { + return container; + } + const reporter = new jasmineUnderTest.HtmlReporter({ + env: env, + getContainer: getContainer, + createElement: function() { + return document.createElement.apply(document, arguments); + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments); + }, + addToExistingQueryString: function(key, value) { + return '?' + key + '=' + value; + } + }); + reporter.initialize(); + + reporter.jasmineStarted({ totalSpecsDefined: 1 }); + + const failingSpecResult = { + id: 124, + status: 'failed', + description: 'a failing spec', + fullName: 'a suite inner suite a failing spec', + passedExpectations: [], + failedExpectations: [ + { + message: 'a failure message', + stack: 'a stack trace' + } + ] + }; + + reporter.specStarted(failingSpecResult); + reporter.specDone(failingSpecResult); + reporter.jasmineDone({ + failedExpectations: [ + { + message: 'a failure message', + stack: 'a stack trace' + }, + { + message: 'a failure message', + stack: 'a stack trace' + } + ] + }); + + const alertBar = container.querySelector('.jasmine-alert .jasmine-bar'); + expect(alertBar.innerHTML).toMatch(/1 spec, 3 failures/); + }); }); describe('The overall result bar', function() { diff --git a/spec/html/SpyRegistryHtmlSpec.js b/spec/html/SpyRegistryHtmlSpec.js index e43e9eeb..bad2d2bd 100644 --- a/spec/html/SpyRegistryHtmlSpec.js +++ b/spec/html/SpyRegistryHtmlSpec.js @@ -4,8 +4,6 @@ describe('Spy Registry browser-specific behavior', function() { } it('can spy on and unspy window.onerror', function() { - requireWriteableOnerror(); - var spies = [], spyRegistry = new jasmineUnderTest.SpyRegistry({ currentSpies: function() { @@ -24,18 +22,4 @@ describe('Spy Registry browser-specific behavior', function() { window.onerror = originalHandler; } }); - - function requireWriteableOnerror() { - var descriptor; - - try { - descriptor = Object.getOwnPropertyDescriptor(window, 'onerror'); - } catch (e) { - // IE 8 doesn't support `definePropery` on non-DOM nodes - } - - if (descriptor && !(descriptor.writable || descriptor.set)) { - pending('Browser declares window.onerror to be readonly'); - } - } }); diff --git a/spec/npmPackage/npmPackageSpec.js b/spec/npmPackage/npmPackageSpec.js index b4a67a83..f5995c92 100644 --- a/spec/npmPackage/npmPackageSpec.js +++ b/spec/npmPackage/npmPackageSpec.js @@ -55,8 +55,7 @@ describe('npm package', function() { it('has jsFiles', function() { expect(this.packagedCore.files.jsFiles).toEqual([ 'jasmine.js', - 'jasmine-html.js', - 'json2.js' + 'jasmine-html.js' ]); var packagedCore = this.packagedCore; @@ -83,10 +82,6 @@ describe('npm package', function() { expect(fileName).toExistInPath(packagedCore.files.bootDir); }); - // For backwards compatibility, boot.js should be packaged even though - // it is no longer in bootFiles. - expect('boot.js').toExistInPath(packagedCore.files.bootDir); - var packagedCore = this.packagedCore; this.packagedCore.files.nodeBootFiles.forEach(function(fileName) { expect(fileName).toExistInPath(packagedCore.files.bootDir); @@ -148,7 +143,7 @@ describe('npm package', function() { j; for (j = 0; j < dirents.length; j++) { - dirent = dirents[j]; + const dirent = dirents[j]; if (dirent.isDirectory()) { getFiles(path.resolve(dir, dirent.name)); diff --git a/spec/support/index.html.ejs b/spec/support/index.html.ejs deleted file mode 100644 index 972f09be..00000000 --- a/spec/support/index.html.ejs +++ /dev/null @@ -1,12 +0,0 @@ - - - - Jasmine suite - - - <% files.forEach(function(file) { %> - - <% }) %> - - - diff --git a/spec/support/jasmine-browser.js b/spec/support/jasmine-browser.js index 9c8bdae3..04950c16 100644 --- a/spec/support/jasmine-browser.js +++ b/spec/support/jasmine-browser.js @@ -12,23 +12,16 @@ module.exports = { 'core/Suite.js', 'core/**/*.js', 'html/**/*.js', - '**/*.js' + '**/*.js', + '!boot/**.js' ], specDir: 'spec', specFiles: ['**/*[Ss]pec.js', '!npmPackage/**/*'], helpers: [ - 'helpers/asyncAwait.js', 'helpers/generator.js', 'helpers/BrowserFlags.js', - 'helpers/checkForArrayBuffer.js', - 'helpers/checkForMap.js', - 'helpers/checkForProxy.js', - 'helpers/checkForSet.js', - 'helpers/checkForSymbol.js', - 'helpers/checkForUrl.js', 'helpers/domHelpers.js', 'helpers/integrationMatchers.js', - 'helpers/promises.js', 'helpers/defineJasmineUnderTest.js', 'helpers/resetEnv.js' ], diff --git a/spec/support/jasmine.json b/spec/support/jasmine.json index 275803b4..f24ab080 100644 --- a/spec/support/jasmine.json +++ b/spec/support/jasmine.json @@ -5,17 +5,8 @@ "npmPackage/**/*[Ss]pec.js" ], "helpers": [ - "helpers/asyncAwait.js", - "helpers/generator.js", - "helpers/checkForArrayBuffer.js", - "helpers/checkForMap.js", - "helpers/checkForProxy.js", - "helpers/checkForSet.js", - "helpers/checkForSymbol.js", - "helpers/checkForUrl.js", "helpers/domHelpers.js", "helpers/integrationMatchers.js", - "helpers/promises.js", "helpers/overrideConsoleLogForCircleCi.js", "helpers/nodeDefineJasmineUnderTest.js", "helpers/resetEnv.js" diff --git a/lib/jasmine-core/boot/boot0.js b/src/boot/boot0.js similarity index 99% rename from lib/jasmine-core/boot/boot0.js rename to src/boot/boot0.js index ca72e496..80500089 100644 --- a/lib/jasmine-core/boot/boot0.js +++ b/src/boot/boot0.js @@ -39,4 +39,4 @@ for (var property in jasmineInterface) { global[property] = jasmineInterface[property]; } -}()); +})(); diff --git a/lib/jasmine-core/boot/boot1.js b/src/boot/boot1.js similarity index 59% rename from lib/jasmine-core/boot/boot1.js rename to src/boot/boot1.js index 6100ae3e..20ec9562 100644 --- a/lib/jasmine-core/boot/boot1.js +++ b/src/boot/boot1.js @@ -1,5 +1,5 @@ /** - 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 specs. This file should be loaded after `boot0.js` but before any project source files or spec files are loaded. Thus this file can also be used to @@ -21,24 +21,28 @@ */ var queryString = new jasmine.QueryString({ - getWindowLocation: function() { return window.location; } + getWindowLocation: function() { + return window.location; + } }); - var filterSpecs = !!queryString.getParam("spec"); + var filterSpecs = !!queryString.getParam('spec'); var config = { - stopOnSpecFailure: queryString.getParam("failFast"), - stopSpecOnExpectationFailure: queryString.getParam("oneFailurePerSpec"), - hideDisabled: queryString.getParam("hideDisabled") + stopOnSpecFailure: queryString.getParam('stopOnSpecFailure'), + stopSpecOnExpectationFailure: queryString.getParam( + 'stopSpecOnExpectationFailure' + ), + hideDisabled: queryString.getParam('hideDisabled') }; - var random = queryString.getParam("random"); + var random = queryString.getParam('random'); - if (random !== undefined && random !== "") { + if (random !== undefined && random !== '') { config.random = random; } - var seed = queryString.getParam("seed"); + var seed = queryString.getParam('seed'); if (seed) { config.seed = seed; } @@ -49,11 +53,21 @@ */ var htmlReporter = new jasmine.HtmlReporter({ env: env, - navigateWithNewParam: function(key, value) { return queryString.navigateWithNewParam(key, value); }, - addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); }, - getContainer: function() { return document.body; }, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); }, + navigateWithNewParam: function(key, value) { + return queryString.navigateWithNewParam(key, value); + }, + addToExistingQueryString: function(key, value) { + return queryString.fullStringWithNewParam(key, value); + }, + getContainer: function() { + 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 }); @@ -68,7 +82,9 @@ * Filter which specs will be run by matching the start of the full name against the `spec` query param. */ var specFilter = new jasmine.HtmlSpecFilter({ - filterString: function() { return queryString.getParam("spec"); } + filterString: function() { + return queryString.getParam('spec'); + } }); config.specFilter = function(spec) { @@ -77,14 +93,6 @@ env.configure(config); - /** - * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. - */ - window.setTimeout = window.setTimeout; - window.setInterval = window.setInterval; - window.clearTimeout = window.clearTimeout; - window.clearInterval = window.clearInterval; - /** * ## Execution * @@ -99,13 +107,4 @@ htmlReporter.initialize(); env.execute(); }; - - /** - * Helper function for readability above. - */ - function extend(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; - } - -}()); +})(); diff --git a/lib/jasmine-core/boot/node_boot.js b/src/boot/node_boot.js similarity index 86% rename from lib/jasmine-core/boot/node_boot.js rename to src/boot/node_boot.js index 89ee49b1..af588102 100644 --- a/lib/jasmine-core/boot/node_boot.js +++ b/src/boot/node_boot.js @@ -1,7 +1,7 @@ module.exports = function(jasmineRequire) { var jasmine = jasmineRequire.core(jasmineRequire); - var env = jasmine.getEnv({suppressLoadErrors: true}); + var env = jasmine.getEnv({ suppressLoadErrors: true }); var jasmineInterface = jasmineRequire.interface(jasmine, env); diff --git a/src/core/CompleteOnFirstErrorSkipPolicy.js b/src/core/CompleteOnFirstErrorSkipPolicy.js new file mode 100644 index 00000000..1dcc4019 --- /dev/null +++ b/src/core/CompleteOnFirstErrorSkipPolicy.js @@ -0,0 +1,51 @@ +getJasmineRequireObj().CompleteOnFirstErrorSkipPolicy = function(j$) { + function CompleteOnFirstErrorSkipPolicy(queueableFns) { + this.queueableFns_ = queueableFns; + this.erroredFnIx_ = null; + } + + CompleteOnFirstErrorSkipPolicy.prototype.skipTo = function(lastRanFnIx) { + let i; + + for ( + i = lastRanFnIx + 1; + i < this.queueableFns_.length && this.shouldSkip_(i); + i++ + ) {} + return i; + }; + + CompleteOnFirstErrorSkipPolicy.prototype.fnErrored = function(fnIx) { + this.erroredFnIx_ = fnIx; + }; + + CompleteOnFirstErrorSkipPolicy.prototype.shouldSkip_ = function(fnIx) { + if (this.erroredFnIx_ === null) { + return false; + } + + const fn = this.queueableFns_[fnIx]; + const candidateSuite = fn.suite; + const errorSuite = this.queueableFns_[this.erroredFnIx_].suite; + const wasCleanupFn = + fn.type === 'afterEach' || + fn.type === 'afterAll' || + fn.type === 'specCleanup'; + return ( + !wasCleanupFn || + (candidateSuite && isDescendent(candidateSuite, errorSuite)) + ); + }; + + function isDescendent(candidate, ancestor) { + if (!candidate.parentSuite) { + return false; + } else if (candidate.parentSuite === ancestor) { + return true; + } else { + return isDescendent(candidate.parentSuite, ancestor); + } + } + + return CompleteOnFirstErrorSkipPolicy; +}; diff --git a/src/core/DelayedFunctionScheduler.js b/src/core/DelayedFunctionScheduler.js index fe1e2665..aabdd911 100644 --- a/src/core/DelayedFunctionScheduler.js +++ b/src/core/DelayedFunctionScheduler.js @@ -6,31 +6,12 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { var currentTime = 0; var delayedFnCount = 0; var deletedKeys = []; - var ticking = false; self.tick = function(millis, tickDate) { - if (ticking) { - j$.getEnv().deprecated( - 'The behavior of reentrant calls to jasmine.clock().tick() will ' + - 'change in a future version. Either modify the affected spec to ' + - 'not call tick() from within a setTimeout or setInterval handler, ' + - 'or be aware that it may behave differently in the future. See ' + - ' ' + - 'for details.' - ); - } + millis = millis || 0; + var endTime = currentTime + millis; - ticking = true; - - try { - millis = millis || 0; - var endTime = currentTime + millis; - - runScheduledFunctions(endTime, tickDate); - currentTime = endTime; - } finally { - ticking = false; - } + runScheduledFunctions(endTime, tickDate); }; self.scheduleFunction = function( @@ -148,16 +129,20 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { function runScheduledFunctions(endTime, tickDate) { tickDate = tickDate || function() {}; if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) { - tickDate(endTime - currentTime); + if (endTime >= currentTime) { + tickDate(endTime - currentTime); + currentTime = endTime; + } return; } do { deletedKeys = []; var newCurrentTime = scheduledLookup.shift(); - tickDate(newCurrentTime - currentTime); - - currentTime = newCurrentTime; + if (newCurrentTime >= currentTime) { + tickDate(newCurrentTime - currentTime); + currentTime = newCurrentTime; + } var funcsToRun = scheduledFunctions[currentTime]; @@ -186,8 +171,9 @@ getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { ); // ran out of functions to call, but still time left on the clock - if (currentTime !== endTime) { + if (endTime >= currentTime) { tickDate(endTime - currentTime); + currentTime = endTime; } } } diff --git a/src/core/Env.js b/src/core/Env.js index 65233780..677dacce 100644 --- a/src/core/Env.js +++ b/src/core/Env.js @@ -12,7 +12,6 @@ getJasmineRequireObj().Env = function(j$) { var self = this; var global = options.global || j$.getGlobal(); - var customPromise; var totalSpecsDefined = 0; @@ -59,15 +58,6 @@ getJasmineRequireObj().Env = function(j$) { * @default null */ seed: null, - /** - * Whether to stop execution of the suite after the first spec failure - * @name Configuration#failFast - * @since 3.3.0 - * @type Boolean - * @default false - * @deprecated Use the `stopOnSpecFailure` config property instead. - */ - failFast: false, /** * Whether to stop execution of the suite after the first spec failure * @name Configuration#stopOnSpecFailure @@ -86,15 +76,6 @@ getJasmineRequireObj().Env = function(j$) { * @default false */ failSpecWithNoExpectations: false, - /** - * Whether to cause specs to only have one expectation failure. - * @name Configuration#oneFailurePerSpec - * @since 3.3.0 - * @type Boolean - * @default false - * @deprecated Use the `stopSpecOnExpectationFailure` config property instead. - */ - oneFailurePerSpec: false, /** * Whether to cause specs to only have one expectation failure. * @name Configuration#stopSpecOnExpectationFailure @@ -129,18 +110,6 @@ getJasmineRequireObj().Env = function(j$) { * @default false */ hideDisabled: false, - /** - * Set to provide a custom promise library that Jasmine will use if it needs - * to create a promise. If not set, it will default to whatever global Promise - * library is available (if any). - * @name Configuration#Promise - * @since 3.5.0 - * @type function - * @default undefined - * @deprecated In a future version, Jasmine will ignore the Promise config - * property and always create native promises instead. - */ - Promise: undefined, /** * Clean closures when a suite is done running (done by clearing the stored function reference). * This prevents memory leaks, but you won't be able to run jasmine multiple times. @@ -215,6 +184,8 @@ getJasmineRequireObj().Env = function(j$) { 'random', 'failSpecWithNoExpectations', 'hideDisabled', + 'stopOnSpecFailure', + 'stopSpecOnExpectationFailure', 'autoCleanClosures' ]; @@ -224,70 +195,6 @@ getJasmineRequireObj().Env = function(j$) { } }); - if (typeof configuration.failFast !== 'undefined') { - // We can't unconditionally issue a warning here because then users who - // get the configuration from Jasmine, modify it, and pass it back would - // see the warning. - if (configuration.failFast !== config.failFast) { - this.deprecated( - 'The `failFast` config property is deprecated and will be removed ' + - 'in a future version of Jasmine. Please use `stopOnSpecFailure` ' + - 'instead.', - { ignoreRunnable: true } - ); - } - - if (typeof configuration.stopOnSpecFailure !== 'undefined') { - if (configuration.stopOnSpecFailure !== configuration.failFast) { - throw new Error( - 'stopOnSpecFailure and failFast are aliases for ' + - "each other. Don't set failFast if you also set stopOnSpecFailure." - ); - } - } - - config.failFast = configuration.failFast; - config.stopOnSpecFailure = configuration.failFast; - } else if (typeof configuration.stopOnSpecFailure !== 'undefined') { - config.failFast = configuration.stopOnSpecFailure; - config.stopOnSpecFailure = configuration.stopOnSpecFailure; - } - - if (typeof configuration.oneFailurePerSpec !== 'undefined') { - // We can't unconditionally issue a warning here because then users who - // get the configuration from Jasmine, modify it, and pass it back would - // see the warning. - if (configuration.oneFailurePerSpec !== config.oneFailurePerSpec) { - this.deprecated( - 'The `oneFailurePerSpec` config property is deprecated and will be ' + - 'removed in a future version of Jasmine. Please use ' + - '`stopSpecOnExpectationFailure` instead.', - { ignoreRunnable: true } - ); - } - - if (typeof configuration.stopSpecOnExpectationFailure !== 'undefined') { - if ( - configuration.stopSpecOnExpectationFailure !== - configuration.oneFailurePerSpec - ) { - throw new Error( - 'stopSpecOnExpectationFailure and oneFailurePerSpec are aliases for ' + - "each other. Don't set oneFailurePerSpec if you also set stopSpecOnExpectationFailure." - ); - } - } - - config.oneFailurePerSpec = configuration.oneFailurePerSpec; - config.stopSpecOnExpectationFailure = configuration.oneFailurePerSpec; - } else if ( - typeof configuration.stopSpecOnExpectationFailure !== 'undefined' - ) { - config.oneFailurePerSpec = configuration.stopSpecOnExpectationFailure; - config.stopSpecOnExpectationFailure = - configuration.stopSpecOnExpectationFailure; - } - if (configuration.specFilter) { config.specFilter = configuration.specFilter; } @@ -296,27 +203,6 @@ getJasmineRequireObj().Env = function(j$) { config.seed = configuration.seed; } - // Don't use hasOwnProperty to check for Promise existence because Promise - // can be initialized to undefined, either explicitly or by using the - // object returned from Env#configuration. In particular, Karma does this. - if (configuration.Promise) { - if ( - typeof configuration.Promise.resolve === 'function' && - typeof configuration.Promise.reject === 'function' - ) { - customPromise = configuration.Promise; - self.deprecated( - 'The `Promise` config property is deprecated. Future versions ' + - 'of Jasmine will create native promises even if the `Promise` ' + - 'config property is set. Please remove it.' - ); - } else { - throw new Error( - 'Custom promise library missing `resolve`/`reject` functions' - ); - } - } - if (configuration.hasOwnProperty('verboseDeprecations')) { config.verboseDeprecations = configuration.verboseDeprecations; deprecator.verboseDeprecations(config.verboseDeprecations); @@ -338,27 +224,6 @@ getJasmineRequireObj().Env = function(j$) { return result; }; - Object.defineProperty(this, 'specFilter', { - get: function() { - self.deprecated( - 'Getting specFilter directly from Env is deprecated and will be ' + - 'removed in a future version of Jasmine. Please check the ' + - 'specFilter option from `configuration` instead.', - { ignoreRunnable: true } - ); - return config.specFilter; - }, - set: function(val) { - self.deprecated( - 'Setting specFilter directly on Env is deprecated and will be ' + - 'removed in a future version of Jasmine. Please use the ' + - 'specFilter option in `configure` instead.', - { ignoreRunnable: true } - ); - config.specFilter = val; - } - }); - this.setDefaultSpyStrategy = function(defaultStrategyFn) { if (!currentRunnable()) { throw new Error( @@ -400,17 +265,6 @@ getJasmineRequireObj().Env = function(j$) { runnableResources[currentRunnable().id].customMatchers; for (var matcherName in matchersToAdd) { - if (matchersToAdd[matcherName].length > 1) { - self.deprecated( - 'The matcher factory for "' + - matcherName + - '" ' + - 'accepts custom equality testers, but this parameter will no longer be ' + - 'passed in a future release. ' + - 'See for details.' - ); - } - customMatchers[matcherName] = matchersToAdd[matcherName]; } }; @@ -425,17 +279,6 @@ getJasmineRequireObj().Env = function(j$) { runnableResources[currentRunnable().id].customAsyncMatchers; for (var matcherName in matchersToAdd) { - if (matchersToAdd[matcherName].length > 1) { - self.deprecated( - 'The matcher factory for "' + - matcherName + - '" ' + - 'accepts custom equality testers, but this parameter will no longer be ' + - 'passed in a future release. ' + - 'See for details.' - ); - } - customAsyncMatchers[matcherName] = matchersToAdd[matcherName]; } }; @@ -472,21 +315,23 @@ getJasmineRequireObj().Env = function(j$) { }; var makeMatchersUtil = function() { - var customEqualityTesters = - runnableResources[currentRunnable().id].customEqualityTesters; - return new j$.MatchersUtil({ - customTesters: customEqualityTesters, - pp: makePrettyPrinter() - }); + const cr = currentRunnable(); + + if (cr) { + const customEqualityTesters = + runnableResources[cr.id].customEqualityTesters; + return new j$.MatchersUtil({ + customTesters: customEqualityTesters, + pp: makePrettyPrinter() + }); + } else { + return new j$.MatchersUtil({ pp: j$.basicPrettyPrinter_ }); + } }; var expectationFactory = function(actual, spec) { - var customEqualityTesters = - runnableResources[spec.id].customEqualityTesters; - return j$.Expectation.factory({ matchersUtil: makeMatchersUtil(), - customEqualityTesters: customEqualityTesters, customMatchers: runnableResources[spec.id].customMatchers, actual: actual, addExpectationResult: addExpectationResult @@ -497,6 +342,18 @@ getJasmineRequireObj().Env = function(j$) { } }; + function recordLateError(error) { + const result = expectationResultFactory({ + error, + passed: false, + matcherName: '', + expected: '', + actual: '' + }); + result.globalErrorType = 'lateError'; + topSuite.result.failedExpectations.push(result); + } + function recordLateExpectation(runable, runableType, result) { var delayedExpectationResult = {}; Object.keys(result).forEach(function(k) { @@ -528,7 +385,6 @@ getJasmineRequireObj().Env = function(j$) { var asyncExpectationFactory = function(actual, spec, runableType) { return j$.Expectation.asyncFactory({ matchersUtil: makeMatchersUtil(), - customEqualityTesters: runnableResources[spec.id].customEqualityTesters, customAsyncMatchers: runnableResources[spec.id].customAsyncMatchers, actual: actual, addExpectationResult: addExpectationResult @@ -573,6 +429,9 @@ getJasmineRequireObj().Env = function(j$) { resources.customObjectFormatters = j$.util.clone( runnableResources[parentRunnableId].customObjectFormatters ); + resources.customSpyStrategies = j$.util.clone( + runnableResources[parentRunnableId].customSpyStrategies + ); resources.defaultStrategyFn = runnableResources[parentRunnableId].defaultStrategyFn; } @@ -625,138 +484,6 @@ getJasmineRequireObj().Env = function(j$) { return buildExpectationResult(attrs); }; - /** - * Sets whether Jasmine should throw an Error when an expectation fails. - * This causes a spec to only have one expectation failure. - * @name Env#throwOnExpectationFailure - * @since 2.3.0 - * @function - * @param {Boolean} value Whether to throw when a expectation fails - * @deprecated Use the `stopSpecOnExpectationFailure` option with {@link Env#configure} - */ - this.throwOnExpectationFailure = function(value) { - this.deprecated( - 'Setting throwOnExpectationFailure directly on Env is deprecated and ' + - 'will be removed in a future version of Jasmine. Please use the ' + - 'stopSpecOnExpectationFailure option in `configure`.', - { ignoreRunnable: true } - ); - this.configure({ oneFailurePerSpec: !!value }); - }; - - this.throwingExpectationFailures = function() { - this.deprecated( - 'Getting throwingExpectationFailures directly from Env is deprecated ' + - 'and will be removed in a future version of Jasmine. Please check ' + - 'the stopSpecOnExpectationFailure option from `configuration`.', - { ignoreRunnable: true } - ); - return config.oneFailurePerSpec; - }; - - /** - * Set whether to stop suite execution when a spec fails - * @name Env#stopOnSpecFailure - * @since 2.7.0 - * @function - * @param {Boolean} value Whether to stop suite execution when a spec fails - * @deprecated Use the `stopOnSpecFailure` option with {@link Env#configure} - */ - this.stopOnSpecFailure = function(value) { - this.deprecated( - 'Setting stopOnSpecFailure directly is deprecated and will be ' + - 'removed in a future version of Jasmine. Please use the ' + - 'stopOnSpecFailure option in `configure`.', - { ignoreRunnable: true } - ); - this.configure({ stopOnSpecFailure: !!value }); - }; - - this.stoppingOnSpecFailure = function() { - this.deprecated( - 'Getting stoppingOnSpecFailure directly from Env is deprecated and ' + - 'will be removed in a future version of Jasmine. Please check the ' + - 'stopOnSpecFailure option from `configuration`.', - { ignoreRunnable: true } - ); - return config.failFast; - }; - - /** - * Set whether to randomize test execution order - * @name Env#randomizeTests - * @since 2.4.0 - * @function - * @param {Boolean} value Whether to randomize execution order - * @deprecated Use the `random` option with {@link Env#configure} - */ - this.randomizeTests = function(value) { - this.deprecated( - 'Setting randomizeTests directly is deprecated and will be removed ' + - 'in a future version of Jasmine. Please use the random option in ' + - '`configure` instead.', - { ignoreRunnable: true } - ); - config.random = !!value; - }; - - this.randomTests = function() { - this.deprecated( - 'Getting randomTests directly from Env is deprecated and will be ' + - 'removed in a future version of Jasmine. Please check the random ' + - 'option from `configuration` instead.', - { ignoreRunnable: true } - ); - return config.random; - }; - - /** - * Set the random number seed for spec randomization - * @name Env#seed - * @since 2.4.0 - * @function - * @param {Number} value The seed value - * @deprecated Use the `seed` option with {@link Env#configure} - */ - this.seed = function(value) { - this.deprecated( - 'Setting seed directly is deprecated and will be removed in a ' + - 'future version of Jasmine. Please use the seed option in ' + - '`configure` instead.', - { ignoreRunnable: true } - ); - if (value) { - config.seed = value; - } - return config.seed; - }; - - this.hidingDisabled = function(value) { - this.deprecated( - 'Getting hidingDisabled directly from Env is deprecated and will ' + - 'be removed in a future version of Jasmine. Please check the ' + - 'hideDisabled option from `configuration` instead.', - { ignoreRunnable: true } - ); - return config.hideDisabled; - }; - - /** - * @name Env#hideDisabled - * @since 3.2.0 - * @function - * @deprecated Use the `hideDisabled` option with {@link Env#configure} - */ - this.hideDisabled = function(value) { - this.deprecated( - 'Setting hideDisabled directly is deprecated and will be removed ' + - 'in a future version of Jasmine. Please use the hideDisabled option ' + - 'in `configure` instead.', - { ignoreRunnable: true } - ); - config.hideDisabled = !!value; - }; - /** * Causes a deprecation warning to be logged to the console and reported to * reporters. @@ -785,12 +512,21 @@ getJasmineRequireObj().Env = function(j$) { }; var queueRunnerFactory = function(options, args) { - var failFast = false; if (options.isLeaf) { - failFast = config.stopSpecOnExpectationFailure; - } else if (!options.isReporter) { - failFast = config.stopOnSpecFailure; + // A spec + options.SkipPolicy = j$.CompleteOnFirstErrorSkipPolicy; + } else if (options.isReporter) { + // A reporter queue + options.SkipPolicy = j$.NeverSkipPolicy; + } else { + // A suite + if (config.stopOnSpecFailure) { + options.SkipPolicy = j$.CompleteOnFirstErrorSkipPolicy; + } else { + options.SkipPolicy = j$.SkipAfterBeforeAllErrorPolicy; + } } + options.clearStack = options.clearStack || clearStack; options.timeout = { setTimeout: realSetTimeout, @@ -798,7 +534,6 @@ getJasmineRequireObj().Env = function(j$) { }; options.fail = self.fail; options.globalErrors = globalErrors; - options.completeOnFirstError = failFast; options.onException = options.onException || function(e) { @@ -810,13 +545,13 @@ getJasmineRequireObj().Env = function(j$) { }; var topSuite = new j$.Suite({ - env: this, id: getNextSuiteId(), description: 'Jasmine__TopLevel__Suite', expectationFactory: expectationFactory, asyncExpectationFactory: suiteAsyncExpectationFactory, expectationResultFactory: expectationResultFactory, - autoCleanClosures: config.autoCleanClosures + autoCleanClosures: config.autoCleanClosures, + onLateError: recordLateError }); var deprecator = new j$.Deprecator(topSuite); currentDeclarationSuite = topSuite; @@ -830,7 +565,7 @@ getJasmineRequireObj().Env = function(j$) { * @since 2.0.0 */ this.topSuite = function() { - return j$.deprecatingSuiteProxy(topSuite, null, this); + return topSuite.metadata; }; /** @@ -906,7 +641,7 @@ getJasmineRequireObj().Env = function(j$) { 'specDone' ], queueRunnerFactory, - self.deprecated + recordLateError ); /** @@ -920,21 +655,25 @@ getJasmineRequireObj().Env = function(j$) { * * Both parameters are optional, but a completion callback is only valid as * the second parameter. To specify a completion callback but not a list of - * specs/suites to run, pass null or undefined as the first parameter. + * specs/suites to run, pass null or undefined as the first parameter. The + * completion callback is supported for backward compatibility. In most + * cases it will be more convenient to use the returned promise instead. * - * execute should not be called more than once. + * execute should not be called more than once unless the env has been + * configured with `{autoCleanClosures: false}`. * - * If the environment supports promises, execute will return a promise that - * is resolved after the suite finishes executing. The promise will be - * resolved (not rejected) as long as the suite runs to completion. Use a - * {@link Reporter} to determine whether or not the suite passed. + * execute returns a promise. The promise will be resolved to the same + * {@link JasmineDoneInfo|overall result} that's passed to a reporter's + * `jasmineDone` method, even if the suite did not pass. To determine + * whether the suite passed, check the value that the promise resolves to + * or use a {@link Reporter}. * * @name Env#execute * @since 2.0.0 * @function * @param {(string[])=} runnablesToRun IDs of suites and/or specs to run * @param {Function=} onComplete Function that will be called after all specs have run - * @return {Promise} + * @return {Promise} */ this.execute = function(runnablesToRun, onComplete) { if (this._executedBefore) { @@ -980,7 +719,14 @@ getJasmineRequireObj().Env = function(j$) { hasFailures = true; } suite.endTimer(); - reporter.suiteDone(result, next); + + if (suite.hadBeforeAllFailure) { + reportChildrenOfBeforeAllFailure(suite).then(function() { + reporter.suiteDone(result, next); + }); + } else { + reporter.suiteDone(result, next); + } }, orderChildren: function(node) { return order.sort(node.children); @@ -999,25 +745,15 @@ getJasmineRequireObj().Env = function(j$) { var jasmineTimer = new j$.Timer(); jasmineTimer.start(); - var Promise = customPromise || global.Promise; - - if (Promise) { - return new Promise(function(resolve) { - runAll(function() { - if (onComplete) { - onComplete(); - } - - resolve(); - }); - }); - } else { - runAll(function() { + return new Promise(function(resolve) { + runAll(function(jasmineDoneInfo) { if (onComplete) { onComplete(); } + + resolve(jasmineDoneInfo); }); - } + }); function runAll(done) { /** @@ -1036,51 +772,98 @@ getJasmineRequireObj().Env = function(j$) { currentlyExecutingSuites.push(topSuite); processor.execute(function() { - clearResourcesForRunnable(topSuite.id); - currentlyExecutingSuites.pop(); - var overallStatus, incompleteReason; + (async function() { + if (topSuite.hadBeforeAllFailure) { + await reportChildrenOfBeforeAllFailure(topSuite); + } - if ( - hasFailures || - topSuite.result.failedExpectations.length > 0 - ) { - overallStatus = 'failed'; - } else if (focusedRunnables.length > 0) { - overallStatus = 'incomplete'; - incompleteReason = 'fit() or fdescribe() was found'; - } else if (totalSpecsDefined === 0) { - overallStatus = 'incomplete'; - incompleteReason = 'No specs found'; - } else { - overallStatus = 'passed'; - } + clearResourcesForRunnable(topSuite.id); + currentlyExecutingSuites.pop(); + var overallStatus, incompleteReason; - /** - * Information passed to the {@link Reporter#jasmineDone} event. - * @typedef JasmineDoneInfo - * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. - * @property {Int} totalTime - The total time (in ms) that it took to execute the suite - * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. - * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. - * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. - * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. - * @since 2.4.0 - */ - reporter.jasmineDone( - { + if ( + hasFailures || + topSuite.result.failedExpectations.length > 0 + ) { + overallStatus = 'failed'; + } else if (focusedRunnables.length > 0) { + overallStatus = 'incomplete'; + incompleteReason = 'fit() or fdescribe() was found'; + } else if (totalSpecsDefined === 0) { + overallStatus = 'incomplete'; + incompleteReason = 'No specs found'; + } else { + overallStatus = 'passed'; + } + + /** + * Information passed to the {@link Reporter#jasmineDone} event. + * @typedef JasmineDoneInfo + * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. + * @property {Int} totalTime - The total time (in ms) that it took to execute the suite + * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. + * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. + * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. + * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. + * @since 2.4.0 + */ + const jasmineDoneInfo = { overallStatus: overallStatus, totalTime: jasmineTimer.elapsed(), incompleteReason: incompleteReason, order: order, failedExpectations: topSuite.result.failedExpectations, deprecationWarnings: topSuite.result.deprecationWarnings - }, - done - ); + }; + reporter.jasmineDone(jasmineDoneInfo, function() { + done(jasmineDoneInfo); + }); + })(); }); } ); } + + async function reportChildrenOfBeforeAllFailure(suite) { + for (const child of suite.children) { + if (child instanceof j$.Suite) { + await new Promise(function(resolve) { + reporter.suiteStarted(child.result, resolve); + }); + await reportChildrenOfBeforeAllFailure(child); + + // Marking the suite passed is consistent with how suites that + // contain failed specs but no suite-level failures are reported. + child.result.status = 'passed'; + + await new Promise(function(resolve) { + reporter.suiteDone(child.result, resolve); + }); + } else { + /* a spec */ + await new Promise(function(resolve) { + reporter.specStarted(child.result, resolve); + }); + + child.addExpectationResult( + false, + { + passed: false, + message: + 'Not run because a beforeAll function failed. The ' + + 'beforeAll failure will be reported on the suite that ' + + 'caused it.' + }, + true + ); + child.result.status = 'failed'; + + await new Promise(function(resolve) { + reporter.specDone(child.result, resolve); + }); + } + } + } }; /** @@ -1136,9 +919,7 @@ getJasmineRequireObj().Env = function(j$) { return undefined; }, - function getPromise() { - return customPromise || global.Promise; - } + makeMatchersUtil ); var spyRegistry = new j$.SpyRegistry({ @@ -1220,7 +1001,6 @@ getJasmineRequireObj().Env = function(j$) { var suiteFactory = function(description) { var suite = new j$.Suite({ - env: self, id: getNextSuiteId(), description: description, parentSuite: currentDeclarationSuite, @@ -1228,8 +1008,9 @@ getJasmineRequireObj().Env = function(j$) { expectationFactory: expectationFactory, asyncExpectationFactory: suiteAsyncExpectationFactory, expectationResultFactory: expectationResultFactory, - throwOnExpectationFailure: config.oneFailurePerSpec, - autoCleanClosures: config.autoCleanClosures + throwOnExpectationFailure: config.stopSpecOnExpectationFailure, + autoCleanClosures: config.autoCleanClosures, + onLateError: recordLateError }); return suite; @@ -1247,13 +1028,9 @@ getJasmineRequireObj().Env = function(j$) { } addSpecsToSuite(suite, specDefinitions); if (suite.parentSuite && !suite.children.length) { - this.deprecated( - 'describe with no children (describe() or it()) is ' + - 'deprecated and will be removed in a future version of Jasmine. ' + - 'Please either remove the describe or add children to it.' - ); + throw new Error('describe with no children (describe() or it())'); } - return j$.deprecatingSuiteProxy(suite, suite.parentSuite, this); + return suite.metadata; }; this.xdescribe = function(description, specDefinitions) { @@ -1262,7 +1039,7 @@ getJasmineRequireObj().Env = function(j$) { var suite = suiteFactory(description); suite.exclude(); addSpecsToSuite(suite, specDefinitions); - return j$.deprecatingSuiteProxy(suite, suite.parentSuite, this); + return suite.metadata; }; var focusedRunnables = []; @@ -1277,7 +1054,7 @@ getJasmineRequireObj().Env = function(j$) { unfocusAncestor(); addSpecsToSuite(suite, specDefinitions); - return j$.deprecatingSuiteProxy(suite, suite.parentSuite, this); + return suite.metadata; }; function addSpecsToSuite(suite, specDefinitions) { @@ -1287,7 +1064,7 @@ getJasmineRequireObj().Env = function(j$) { var declarationError = null; try { - specDefinitions.call(j$.deprecatingThisProxy(suite, self)); + specDefinitions(); } catch (e) { declarationError = e; } @@ -1329,7 +1106,7 @@ getJasmineRequireObj().Env = function(j$) { beforeAndAfterFns: beforeAndAfterFns(suite), expectationFactory: expectationFactory, asyncExpectationFactory: specAsyncExpectationFactory, - deprecated: self.deprecated, + onLateError: recordLateError, resultCallback: specResultCallback, getSpecName: function(spec) { return getSpecName(spec, suite); @@ -1345,7 +1122,7 @@ getJasmineRequireObj().Env = function(j$) { fn: fn, timeout: timeout || 0 }, - throwOnExpectationFailure: config.oneFailurePerSpec, + throwOnExpectationFailure: config.stopSpecOnExpectationFailure, autoCleanClosures: config.autoCleanClosures, timer: new j$.Timer() }); @@ -1391,8 +1168,8 @@ getJasmineRequireObj().Env = function(j$) { }; this.it = function(description, fn, timeout) { - var spec = this.it_(description, fn, timeout); - return j$.deprecatingSpecProxy(spec, this); + const spec = this.it_(description, fn, timeout); + return spec.metadata; }; this.xit = function(description, fn, timeout) { @@ -1404,7 +1181,7 @@ getJasmineRequireObj().Env = function(j$) { } var spec = this.it_.apply(this, arguments); spec.exclude('Temporarily disabled with xit'); - return j$.deprecatingSpecProxy(spec, this); + return spec.metadata; }; this.fit = function(description, fn, timeout) { @@ -1418,7 +1195,7 @@ getJasmineRequireObj().Env = function(j$) { currentDeclarationSuite.addChild(spec); focusedRunnables.push(spec.id); unfocusAncestor(); - return j$.deprecatingSpecProxy(spec, this); + return spec.metadata; }; /** @@ -1455,6 +1232,16 @@ getJasmineRequireObj().Env = function(j$) { currentSuite().setSuiteProperty(key, value); }; + this.debugLog = function(msg) { + var maybeSpec = currentRunnable(); + + if (!maybeSpec || !maybeSpec.debugLog) { + throw new Error("'debugLog' was called when there was no current spec"); + } + + maybeSpec.debugLog(msg); + }; + this.expect = function(actual) { if (!currentRunnable()) { throw new Error( @@ -1569,7 +1356,7 @@ getJasmineRequireObj().Env = function(j$) { error: error && error.message ? error : null }); - if (config.oneFailurePerSpec) { + if (config.stopSpecOnExpectationFailure) { throw new Error(message); } }; diff --git a/src/core/ExceptionFormatter.js b/src/core/ExceptionFormatter.js index 113f7af7..a36d1422 100644 --- a/src/core/ExceptionFormatter.js +++ b/src/core/ExceptionFormatter.js @@ -38,7 +38,7 @@ getJasmineRequireObj().ExceptionFormatter = function(j$) { return message; }; - this.stack = function(error) { + this.stack = function(error, { omitMessage } = {}) { if (!error || !error.stack) { return null; } @@ -47,7 +47,7 @@ getJasmineRequireObj().ExceptionFormatter = function(j$) { var lines = filterJasmine(stackTrace); var result = ''; - if (stackTrace.message) { + if (stackTrace.message && !omitMessage) { lines.unshift(stackTrace.message); } diff --git a/src/core/Expectation.js b/src/core/Expectation.js index 5545e1b0..4d34de0b 100644 --- a/src/core/Expectation.js +++ b/src/core/Expectation.js @@ -75,15 +75,8 @@ getJasmineRequireObj().Expectation = function(j$) { * @namespace async-matchers */ function AsyncExpectation(options) { - var global = options.global || j$.getGlobal(); this.expector = new j$.Expector(options); - if (!global.Promise) { - throw new Error( - 'expectAsync is unavailable because the environment does not support promises.' - ); - } - var customAsyncMatchers = options.customAsyncMatchers || {}; for (var matcherName in customAsyncMatchers) { this[matcherName] = wrapAsyncCompare( diff --git a/src/core/ExpectationResult.js b/src/core/ExpectationResult.js index d3ea5cb3..23c91013 100644 --- a/src/core/ExpectationResult.js +++ b/src/core/ExpectationResult.js @@ -12,6 +12,9 @@ getJasmineRequireObj().buildExpectationResult = function(j$) { * @property {Boolean} passed - Whether the expectation passed or failed. * @property {Object} expected - If the expectation failed, what was the expected value. * @property {Object} actual - If the expectation failed, what actual value was produced. + * @property {String|undefined} globalErrorType - The type of an error that + * is reported on the top suite. Valid values are undefined, "afterAll", + * "load", "lateExpectation", and "lateError". */ var result = { matcherName: options.matcherName, @@ -73,7 +76,9 @@ getJasmineRequireObj().buildExpectationResult = function(j$) { } } } - return stackFormatter(error); + // Omit the message from the stack trace because it will be + // included elsewhere. + return stackFormatter(error, { omitMessage: true }); } } diff --git a/src/core/Expector.js b/src/core/Expector.js index c4a560ca..df4878da 100644 --- a/src/core/Expector.js +++ b/src/core/Expector.js @@ -3,7 +3,6 @@ getJasmineRequireObj().Expector = function(j$) { this.matchersUtil = options.matchersUtil || { buildFailureMessage: function() {} }; - this.customEqualityTesters = options.customEqualityTesters || []; this.actual = options.actual; this.addExpectationResult = options.addExpectationResult || function() {}; this.filters = new j$.ExpectationFilterChain(); @@ -20,14 +19,7 @@ getJasmineRequireObj().Expector = function(j$) { this.args.unshift(this.actual); - // TODO: Remove support for passing customEqualityTesters in the next major release. - var matcher; - - if (matcherFactory.length >= 2) { - matcher = matcherFactory(this.matchersUtil, this.customEqualityTesters); - } else { - matcher = matcherFactory(this.matchersUtil); - } + var matcher = matcherFactory(this.matchersUtil); var comparisonFunc = this.filters.selectComparisonFunc(matcher); return comparisonFunc || matcher.compare; diff --git a/src/core/MockDate.js b/src/core/MockDate.js index 74a6956f..feefe458 100644 --- a/src/core/MockDate.js +++ b/src/core/MockDate.js @@ -17,10 +17,9 @@ getJasmineRequireObj().MockDate = function(j$) { currentTime = mockDate.getTime(); } else { if (!j$.util.isUndefined(mockDate)) { - j$.getEnv().deprecated( + throw new Error( 'The argument to jasmine.clock().mockDate(), if specified, ' + - 'should be a Date instance. Passing anything other than a Date ' + - 'will be treated as an error in a future release.' + 'should be a Date instance.' ); } @@ -95,11 +94,7 @@ getJasmineRequireObj().MockDate = function(j$) { FakeDate.prototype = GlobalDate.prototype; FakeDate.now = function() { - if (GlobalDate.now) { - return currentTime; - } else { - throw new Error('Browser does not support Date.now()'); - } + return currentTime; }; FakeDate.toSource = GlobalDate.toSource; diff --git a/src/core/NeverSkipPolicy.js b/src/core/NeverSkipPolicy.js new file mode 100644 index 00000000..7d72cd50 --- /dev/null +++ b/src/core/NeverSkipPolicy.js @@ -0,0 +1,11 @@ +getJasmineRequireObj().NeverSkipPolicy = function(j$) { + function NeverSkipPolicy(queueableFns) {} + + NeverSkipPolicy.prototype.skipTo = function(lastRanFnIx) { + return lastRanFnIx + 1; + }; + + NeverSkipPolicy.prototype.fnErrored = function(fnIx) {}; + + return NeverSkipPolicy; +}; diff --git a/src/core/QueueRunner.js b/src/core/QueueRunner.js index 7b6ebdd2..ebf3b5c3 100644 --- a/src/core/QueueRunner.js +++ b/src/core/QueueRunner.js @@ -35,9 +35,7 @@ getJasmineRequireObj().QueueRunner = function(j$) { function QueueRunner(attrs) { this.id_ = nextid++; - var queueableFns = attrs.queueableFns || []; - this.queueableFns = queueableFns.concat(attrs.cleanupFns || []); - this.firstCleanupIx = queueableFns.length; + this.queueableFns = attrs.queueableFns || []; this.onComplete = attrs.onComplete || emptyFn; this.clearStack = attrs.clearStack || @@ -56,8 +54,10 @@ getJasmineRequireObj().QueueRunner = function(j$) { pushListener: emptyFn, popListener: emptyFn }; - this.completeOnFirstError = !!attrs.completeOnFirstError; - this.errored = false; + + const SkipPolicy = attrs.SkipPolicy || j$.NeverSkipPolicy; + this.skipPolicy_ = new SkipPolicy(this.queueableFns); + this.errored_ = false; if (typeof this.onComplete !== 'function') { throw new Error('invalid onComplete ' + JSON.stringify(this.onComplete)); @@ -77,14 +77,6 @@ getJasmineRequireObj().QueueRunner = function(j$) { this.run(0); }; - QueueRunner.prototype.skipToCleanup = function(lastRanIndex) { - if (lastRanIndex < this.firstCleanupIx) { - this.run(this.firstCleanupIx); - } else { - this.run(lastRanIndex + 1); - } - }; - QueueRunner.prototype.clearTimeout = function(timeoutId) { Function.prototype.apply.apply(this.timeout.clearTimeout, [ j$.getGlobal(), @@ -117,25 +109,15 @@ getJasmineRequireObj().QueueRunner = function(j$) { function next(err) { cleanup(); - if (j$.isError_(err)) { + if (typeof err !== 'undefined') { if (!(err instanceof StopExecutionError) && !err.jasmineMessage) { self.fail(err); } - self.errored = errored = true; - } else if (typeof err !== 'undefined' && !self.errored) { - self.deprecated( - 'Any argument passed to a done callback will be treated as an ' + - 'error in a future release. Call the done callback without ' + - "arguments if you don't want to trigger a spec failure." - ); + self.recordError_(iterativeIndex); } function runNext() { - if (self.completeOnFirstError && errored) { - self.skipToCleanup(iterativeIndex); - } else { - self.run(iterativeIndex + 1); - } + self.run(self.nextFnIx_(iterativeIndex)); } if (completedSynchronously) { @@ -157,7 +139,6 @@ getJasmineRequireObj().QueueRunner = function(j$) { } } ), - errored = false, timedOut = false, queueableFn = self.queueableFns[iterativeIndex], timeoutId, @@ -165,7 +146,7 @@ getJasmineRequireObj().QueueRunner = function(j$) { next.fail = function nextFail() { self.fail.apply(null, arguments); - self.errored = errored = true; + self.recordError_(iterativeIndex); next(); }; @@ -208,15 +189,15 @@ getJasmineRequireObj().QueueRunner = function(j$) { } } catch (e) { onException(e); - self.errored = errored = true; + self.recordError_(iterativeIndex); } cleanup(); - return { completedSynchronously: true, errored: errored }; + return { completedSynchronously: true }; function onException(e) { self.onException(e); - self.errored = errored = true; + self.recordError_(iterativeIndex); } function onPromiseRejection(e) { @@ -233,26 +214,19 @@ getJasmineRequireObj().QueueRunner = function(j$) { for ( iterativeIndex = recursiveIndex; iterativeIndex < length; - iterativeIndex++ + iterativeIndex = this.nextFnIx_(iterativeIndex) ) { var result = this.attempt(iterativeIndex); if (!result.completedSynchronously) { return; } - - self.errored = self.errored || result.errored; - - if (this.completeOnFirstError && result.errored) { - this.skipToCleanup(iterativeIndex); - return; - } } this.clearStack(function() { self.globalErrors.popListener(self.handleFinalError); - if (self.errored) { + if (self.errored_) { self.onComplete(new StopExecutionError()); } else { self.onComplete(); @@ -260,6 +234,21 @@ getJasmineRequireObj().QueueRunner = function(j$) { }); }; + QueueRunner.prototype.nextFnIx_ = function(currentFnIx) { + const result = this.skipPolicy_.skipTo(currentFnIx); + + if (result === currentFnIx) { + throw new Error("Can't skip to the same queueable fn that just finished"); + } + + return result; + }; + + QueueRunner.prototype.recordError_ = function(currentFnIx) { + this.errored_ = true; + this.skipPolicy_.fnErrored(currentFnIx); + }; + QueueRunner.prototype.diagnoseConflictingAsync_ = function(fn, retval) { var msg; @@ -268,19 +257,19 @@ getJasmineRequireObj().QueueRunner = function(j$) { // Omit the stack trace because there's almost certainly no user code // on the stack at this point. if (j$.isAsyncFunction_(fn)) { - msg = + this.onException( 'An asynchronous before/it/after ' + - 'function was defined with the async keyword but also took a ' + - 'done callback. This is not supported and will stop working in' + - ' the future. Either remove the done callback (recommended) or ' + - 'remove the async keyword.'; + 'function was defined with the async keyword but also took a ' + + 'done callback. Either remove the done callback (recommended) or ' + + 'remove the async keyword.' + ); } else { - msg = + this.onException( 'An asynchronous before/it/after ' + - 'function took a done callback but also returned a promise. ' + - 'This is not supported and will stop working in the future. ' + - 'Either remove the done callback (recommended) or change the ' + - 'function to not return a promise.'; + 'function took a done callback but also returned a promise. ' + + 'Either remove the done callback (recommended) or change the ' + + 'function to not return a promise.' + ); } this.deprecated(msg, { omitStackTrace: true }); diff --git a/src/core/ReportDispatcher.js b/src/core/ReportDispatcher.js index 84a242c5..c2f957dc 100644 --- a/src/core/ReportDispatcher.js +++ b/src/core/ReportDispatcher.js @@ -1,5 +1,5 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { - function ReportDispatcher(methods, queueRunnerFactory, deprecated) { + function ReportDispatcher(methods, queueRunnerFactory, onLateError) { var dispatchedMethods = methods || []; for (var i = 0; i < dispatchedMethods.length; i++) { @@ -45,14 +45,11 @@ getJasmineRequireObj().ReportDispatcher = function(j$) { onComplete: onComplete, isReporter: true, onMultipleDone: function() { - deprecated( - "An asynchronous reporter callback called its 'done' callback " + - 'more than once. This is a bug in the reporter callback in ' + - 'question. This will be treated as an error in a future ' + - 'version. See' + - ' ' + - 'for more information.', - { ignoreRunnable: true } + onLateError( + new Error( + "An asynchronous reporter callback called its 'done' callback " + + 'more than once.' + ) ); } }); diff --git a/src/core/SkipAfterBeforeAllErrorPolicy.js b/src/core/SkipAfterBeforeAllErrorPolicy.js new file mode 100644 index 00000000..57d88127 --- /dev/null +++ b/src/core/SkipAfterBeforeAllErrorPolicy.js @@ -0,0 +1,38 @@ +getJasmineRequireObj().SkipAfterBeforeAllErrorPolicy = function(j$) { + function SkipAfterBeforeAllErrorPolicy(queueableFns) { + this.queueableFns_ = queueableFns; + this.skipping_ = false; + } + + SkipAfterBeforeAllErrorPolicy.prototype.skipTo = function(lastRanFnIx) { + if (this.skipping_) { + return this.nextAfterAllAfter_(lastRanFnIx); + } else { + return lastRanFnIx + 1; + } + }; + + SkipAfterBeforeAllErrorPolicy.prototype.nextAfterAllAfter_ = function(i) { + for ( + i++; + i < this.queueableFns_.length && + this.queueableFns_[i].type !== 'afterAll'; + i++ + ) {} + return i; + }; + + SkipAfterBeforeAllErrorPolicy.prototype.fnErrored = function(fnIx) { + if (this.queueableFns_[fnIx].type === 'beforeAll') { + this.skipping_ = true; + // Failures need to be reported for each contained spec. But we can't do + // that from here because reporting is async. This function isn't async + // (and can't be without greatly complicating QueueRunner). Mark the + // failure so that the code that reports the suite result (which is + // already async) can detect the failure and report the specs. + this.queueableFns_[fnIx].suite.hadBeforeAllFailure = true; + } + }; + + return SkipAfterBeforeAllErrorPolicy; +}; diff --git a/src/core/Spec.js b/src/core/Spec.js index 22e715fe..f9a774a8 100644 --- a/src/core/Spec.js +++ b/src/core/Spec.js @@ -45,7 +45,7 @@ getJasmineRequireObj().Spec = function(j$) { }; this.expectationResultFactory = attrs.expectationResultFactory || function() {}; - this.deprecated = attrs.deprecated || function() {}; + this.onLateError = attrs.onLateError || function() {}; this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; this.catchingExceptions = attrs.catchingExceptions || @@ -71,8 +71,9 @@ getJasmineRequireObj().Spec = function(j$) { * @property {String} status - Once the spec has completed, this string represents the pass/fail status of this spec. * @property {number} duration - The time in ms used by the spec execution, including any before/afterEach. * @property {Object} properties - User-supplied properties, if any, that were set using {@link Env#setSpecProperty} + * @property {DebugLogEntry[]|null} debugLogs - Messages, if any, that were logged using {@link jasmine.debugLog} during a failing spec. * @since 2.0.0 -x */ + */ this.result = { id: this.id, description: this.description, @@ -82,7 +83,8 @@ x */ deprecationWarnings: [], pendingReason: '', duration: null, - properties: null + properties: null, + debugLogs: null }; } @@ -129,17 +131,21 @@ x */ } self.result.status = self.status(excluded, failSpecWithNoExp); self.result.duration = self.timer.elapsed(); + + if (self.result.status !== 'failed') { + self.result.debugLogs = null; + } + self.resultCallback(self.result, done); - } + }, + type: 'specCleanup' }; var fns = this.beforeAndAfterFns(); - var regularFns = fns.befores.concat(this.queueableFn); var runnerConfig = { isLeaf: true, - queueableFns: regularFns, - cleanupFns: fns.afters, + queueableFns: [...fns.befores, this.queueableFn, ...fns.afters], onException: function() { self.onException.apply(self, arguments); }, @@ -147,17 +153,13 @@ x */ // Issue a deprecation. Include the context ourselves and pass // ignoreRunnable: true, since getting here always means that we've already // moved on and the current runnable isn't the one that caused the problem. - self.deprecated( - "An asynchronous function called its 'done' " + - 'callback more than once. This is a bug in the spec, beforeAll, ' + - 'beforeEach, afterAll, or afterEach function in question. This will ' + - 'be treated as an error in a future version. See' + - ' ' + - 'for more information.\n' + - '(in spec: ' + - self.getFullName() + - ')', - { ignoreRunnable: true } + self.onLateError( + new Error( + 'An asynchronous spec, beforeEach, or afterEach function called its ' + + "'done' callback more than once.\n(in spec: " + + self.getFullName() + + ')' + ) ); }, onComplete: function() { @@ -173,30 +175,15 @@ x */ if (this.markedPending || excluded === true) { runnerConfig.queueableFns = []; - runnerConfig.cleanupFns = []; } runnerConfig.queueableFns.unshift(onStart); - runnerConfig.cleanupFns.push(complete); + runnerConfig.queueableFns.push(complete); this.queueRunnerFactory(runnerConfig); }; Spec.prototype.reset = function() { - /** - * @typedef SpecResult - * @property {Int} id - The unique id of this spec. - * @property {String} description - The description passed to the {@link it} that created this spec. - * @property {String} fullName - The full description including all ancestors of this spec. - * @property {Expectation[]} failedExpectations - The list of expectations that failed during execution of this spec. - * @property {Expectation[]} passedExpectations - The list of expectations that passed during execution of this spec. - * @property {Expectation[]} deprecationWarnings - The list of deprecation warnings that occurred during execution this spec. - * @property {String} pendingReason - If the spec is {@link pending}, this will be the reason. - * @property {String} status - Once the spec has completed, this string represents the pass/fail status of this spec. - * @property {number} duration - The time in ms used by the spec execution, including any before/afterEach. - * @property {Object} properties - User-supplied properties, if any, that were set using {@link Env#setSpecProperty} - * @since 2.0.0 - */ this.result = { id: this.id, description: this.description, @@ -207,7 +194,7 @@ x */ pendingReason: this.excludeMessage, duration: null, properties: null, - trace: null + debugLogs: null }; this.markedPending = this.markedExcluding; }; @@ -306,6 +293,23 @@ x */ ); }; + Spec.prototype.debugLog = function(msg) { + if (!this.result.debugLogs) { + this.result.debugLogs = []; + } + + /** + * @typedef DebugLogEntry + * @property {String} message - The message that was passed to {@link jasmine.debugLog}. + * @property {number} timestamp - The time when the entry was added, in + * milliseconds from the spec's start time + */ + this.result.debugLogs.push({ + message: msg, + timestamp: this.timer.elapsed() + }); + }; + var extractCustomPendingMessage = function(e) { var fullMessage = e.toString(), boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), @@ -325,10 +329,43 @@ x */ ); }; + /** + * @interface Spec + * @see Configuration#specFilter + */ + Object.defineProperty(Spec.prototype, 'metadata', { + get: function() { + if (!this.metadata_) { + this.metadata_ = { + /** + * The unique ID of this spec. + * @name Spec#id + * @readonly + * @type {string} + */ + id: this.id, + + /** + * The description passed to the {@link it} that created this spec. + * @name Spec#description + * @readonly + * @type {string} + */ + description: this.description, + + /** + * The full description including all ancestors of this spec. + * @name Spec#getFullName + * @function + * @returns {string} + */ + getFullName: this.getFullName.bind(this) + }; + } + + return this.metadata_; + } + }); + return Spec; }; - -if (typeof window == void 0 && typeof exports == 'object') { - /* globals exports */ - exports.Spec = jasmineRequire.Spec; -} diff --git a/src/core/Spy.js b/src/core/Spy.js index 101725a9..26d4b6b4 100644 --- a/src/core/Spy.js +++ b/src/core/Spy.js @@ -7,11 +7,6 @@ getJasmineRequireObj().Spy = function(j$) { }; })(); - var matchersUtil = new j$.MatchersUtil({ - customTesters: [], - pp: j$.makePrettyPrinter() - }); - /** * @classdesc _Note:_ Do not construct this directly. Use {@link spyOn}, * {@link spyOnProperty}, {@link jasmine.createSpy}, or @@ -19,26 +14,24 @@ getJasmineRequireObj().Spy = function(j$) { * @class Spy * @hideconstructor */ - function Spy( - name, - originalFn, - customStrategies, - defaultStrategyFn, - getPromise - ) { + function Spy(name, matchersUtil, optionals) { + const { originalFn, customStrategies, defaultStrategyFn } = optionals || {}; + var numArgs = typeof originalFn === 'function' ? originalFn.length : 0, wrapper = makeFunc(numArgs, function(context, args, invokeNew) { return spy(context, args, invokeNew); }), - strategyDispatcher = new SpyStrategyDispatcher({ - name: name, - fn: originalFn, - getSpy: function() { - return wrapper; + strategyDispatcher = new SpyStrategyDispatcher( + { + name: name, + fn: originalFn, + getSpy: function() { + return wrapper; + }, + customStrategies: customStrategies }, - customStrategies: customStrategies, - getPromise: getPromise - }), + matchersUtil + ), callTracker = new j$.CallTracker(), spy = function(context, args, invokeNew) { /** @@ -150,11 +143,11 @@ getJasmineRequireObj().Spy = function(j$) { return wrapper; } - function SpyStrategyDispatcher(strategyArgs) { + function SpyStrategyDispatcher(strategyArgs, matchersUtil) { var baseStrategy = new j$.SpyStrategy(strategyArgs); var argsStrategies = new StrategyDict(function() { return new j$.SpyStrategy(strategyArgs); - }); + }, matchersUtil); this.and = baseStrategy; @@ -183,9 +176,10 @@ getJasmineRequireObj().Spy = function(j$) { }; } - function StrategyDict(strategyFactory) { + function StrategyDict(strategyFactory, matchersUtil) { this.strategies = []; this.strategyFactory = strategyFactory; + this.matchersUtil = matchersUtil; } StrategyDict.prototype.any = function() { @@ -210,7 +204,7 @@ getJasmineRequireObj().Spy = function(j$) { var i; for (i = 0; i < this.strategies.length; i++) { - if (matchersUtil.equals(args, this.strategies[i].args)) { + if (this.matchersUtil.equals(args, this.strategies[i].args)) { return this.strategies[i].strategy; } } diff --git a/src/core/SpyFactory.js b/src/core/SpyFactory.js index 0f29a3b1..03bd6035 100644 --- a/src/core/SpyFactory.js +++ b/src/core/SpyFactory.js @@ -1,15 +1,17 @@ getJasmineRequireObj().SpyFactory = function(j$) { - function SpyFactory(getCustomStrategies, getDefaultStrategyFn, getPromise) { + function SpyFactory( + getCustomStrategies, + getDefaultStrategyFn, + getMatchersUtil + ) { var self = this; this.createSpy = function(name, originalFn) { - return j$.Spy( - name, + return j$.Spy(name, getMatchersUtil(), { originalFn, - getCustomStrategies(), - getDefaultStrategyFn(), - getPromise - ); + customStrategies: getCustomStrategies(), + defaultStrategyFn: getDefaultStrategyFn() + }); }; this.createSpyObj = function(baseName, methodNames, propertyNames) { diff --git a/src/core/SpyStrategy.js b/src/core/SpyStrategy.js index 382164b6..c4334611 100644 --- a/src/core/SpyStrategy.js +++ b/src/core/SpyStrategy.js @@ -27,24 +27,6 @@ getJasmineRequireObj().SpyStrategy = function(j$) { } } - var getPromise = - typeof options.getPromise === 'function' - ? options.getPromise - : function() {}; - - var requirePromise = function(name) { - var Promise = getPromise(); - - if (!Promise) { - throw new Error( - name + - ' requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`' - ); - } - - return Promise; - }; - /** * Tell the spy to return a promise resolving to the specified value when invoked. * @name SpyStrategy#resolveTo @@ -53,7 +35,6 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {*} value The value to return. */ this.resolveTo = function(value) { - var Promise = requirePromise('resolveTo'); self.plan = function() { return Promise.resolve(value); }; @@ -68,8 +49,6 @@ getJasmineRequireObj().SpyStrategy = function(j$) { * @param {*} value The value to return. */ this.rejectWith = function(value) { - var Promise = requirePromise('rejectWith'); - self.plan = function() { return Promise.reject(value); }; diff --git a/src/core/StackTrace.js b/src/core/StackTrace.js index 44db4ff1..32d9d1f2 100644 --- a/src/core/StackTrace.js +++ b/src/core/StackTrace.js @@ -17,7 +17,7 @@ getJasmineRequireObj().StackTrace = function(j$) { } var framePatterns = [ - // PhantomJS on Linux, Node, Chrome, IE, Edge + // Node, Chrome, Edge // e.g. " at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)" // Note that the "function name" can include a surprisingly large set of // characters, including angle brackets and square brackets. @@ -36,7 +36,7 @@ getJasmineRequireObj().StackTrace = function(j$) { // e.g. "run@http://localhost:8888/__jasmine__/jasmine.js:4320:27" // or "http://localhost:8888/__jasmine__/jasmine.js:4320:27" { - re: /^(([^@\s]+)@)?([^\s]+)$/, + re: /^(?:(([^@\s]+)@)|@)?([^\s]+)$/, fnIx: 2, fileLineColIx: 3, style: 'webkit' diff --git a/src/core/Suite.js b/src/core/Suite.js index 799485e6..43e3ce22 100644 --- a/src/core/Suite.js +++ b/src/core/Suite.js @@ -14,12 +14,6 @@ getJasmineRequireObj().Suite = function(j$) { * @since 2.0.0 */ this.id = attrs.id; - /** - * The parent of this suite, or null if this is the top suite. - * @name Suite#parentSuite - * @readonly - * @type {Suite} - */ this.parentSuite = attrs.parentSuite; /** * The description passed to the {@link describe} that created this suite. @@ -35,12 +29,12 @@ getJasmineRequireObj().Suite = function(j$) { this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; this.autoCleanClosures = attrs.autoCleanClosures === undefined ? true : !!attrs.autoCleanClosures; + this.onLateError = attrs.onLateError; this.beforeFns = []; this.afterFns = []; this.beforeAllFns = []; this.afterAllFns = []; - this.timer = attrs.timer || new j$.Timer(); /** @@ -105,19 +99,19 @@ getJasmineRequireObj().Suite = function(j$) { }; Suite.prototype.beforeEach = function(fn) { - this.beforeFns.unshift(fn); + this.beforeFns.unshift({ ...fn, suite: this }); }; Suite.prototype.beforeAll = function(fn) { - this.beforeAllFns.push(fn); + this.beforeAllFns.push({ ...fn, type: 'beforeAll', suite: this }); }; Suite.prototype.afterEach = function(fn) { - this.afterFns.unshift(fn); + this.afterFns.unshift({ ...fn, suite: this, type: 'afterEach' }); }; Suite.prototype.afterAll = function(fn) { - this.afterAllFns.unshift(fn); + this.afterAllFns.unshift({ ...fn, type: 'afterAll' }); }; Suite.prototype.startTimer = function() { @@ -232,33 +226,25 @@ getJasmineRequireObj().Suite = function(j$) { }; Suite.prototype.onMultipleDone = function() { - var msg; + let msg; // Issue a deprecation. Include the context ourselves and pass // ignoreRunnable: true, since getting here always means that we've already // moved on and the current runnable isn't the one that caused the problem. if (this.parentSuite) { msg = - "An asynchronous function called its 'done' callback more than " + - 'once. This is a bug in the spec, beforeAll, beforeEach, afterAll, ' + - 'or afterEach function in question. This will be treated as an error ' + - 'in a future version. See' + - ' ' + - 'for more information.\n' + + "An asynchronous beforeAll or afterAll function called its 'done' " + + 'callback more than once.\n' + '(in suite: ' + this.getFullName() + ')'; } else { msg = 'A top-level beforeAll or afterAll function called its ' + - "'done' callback more than once. This is a bug in the beforeAll " + - 'or afterAll function in question. This will be treated as an ' + - 'error in a future version. See' + - ' ' + - 'for more information.'; + "'done' callback more than once."; } - this.env.deprecated(msg, { ignoreRunnable: true }); + this.onLateError(new Error(msg)); }; Suite.prototype.addExpectationResult = function() { @@ -280,14 +266,71 @@ getJasmineRequireObj().Suite = function(j$) { ); }; + Object.defineProperty(Suite.prototype, 'metadata', { + get: function() { + if (!this.metadata_) { + this.metadata_ = new SuiteMetadata(this); + } + + return this.metadata_; + } + }); + + /** + * @interface Suite + * @see Env#topSuite + */ + function SuiteMetadata(suite) { + this.suite_ = suite; + /** + * The unique ID of this suite. + * @name Suite#id + * @readonly + * @type {string} + */ + this.id = suite.id; + + /** + * The parent of this suite, or null if this is the top suite. + * @name Suite#parentSuite + * @readonly + * @type {Suite} + */ + this.parentSuite = suite.parentSuite ? suite.parentSuite.metadata : null; + + /** + * The description passed to the {@link describe} that created this suite. + * @name Suite#description + * @readonly + * @type {string} + */ + this.description = suite.description; + } + + /** + * The full description including all ancestors of this suite. + * @name Suite#getFullName + * @function + * @returns {string} + */ + SuiteMetadata.prototype.getFullName = function() { + return this.suite_.getFullName(); + }; + + /** + * The suite's children. + * @name Suite#children + * @type {Array.<(Spec|Suite)>} + */ + Object.defineProperty(SuiteMetadata.prototype, 'children', { + get: function() { + return this.suite_.children.map(child => child.metadata); + } + }); + function isFailure(args) { return !args[0]; } return Suite; }; - -if (typeof window == void 0 && typeof exports == 'object') { - /* globals exports */ - exports.Suite = jasmineRequire.Suite; -} diff --git a/src/core/asymmetricEqualityTesterArgCompatShim.js b/src/core/asymmetricEqualityTesterArgCompatShim.js deleted file mode 100644 index 2a16b48f..00000000 --- a/src/core/asymmetricEqualityTesterArgCompatShim.js +++ /dev/null @@ -1,122 +0,0 @@ -getJasmineRequireObj().asymmetricEqualityTesterArgCompatShim = function(j$) { - /* - Older versions of Jasmine passed an array of custom equality testers as the - second argument to each asymmetric equality tester's `asymmetricMatch` - method. Newer versions will pass a `MatchersUtil` instance. The - asymmetricEqualityTesterArgCompatShim allows for a graceful migration from - the old interface to the new by "being" both an array of custom equality - testers and a `MatchersUtil` at the same time. - - This code should be removed in the next major release. - */ - - var likelyArrayProps = [ - 'concat', - 'constructor', - 'copyWithin', - 'entries', - 'every', - 'fill', - 'filter', - 'find', - 'findIndex', - 'flat', - 'flatMap', - 'forEach', - 'includes', - 'indexOf', - 'join', - 'keys', - 'lastIndexOf', - 'length', - 'map', - 'pop', - 'push', - 'reduce', - 'reduceRight', - 'reverse', - 'shift', - 'slice', - 'some', - 'sort', - 'splice', - 'toLocaleString', - 'toSource', - 'toString', - 'unshift', - 'values' - ]; - - function asymmetricEqualityTesterArgCompatShim( - matchersUtil, - customEqualityTesters - ) { - var self = Object.create(matchersUtil); - - copyAndDeprecate(self, customEqualityTesters, 'length'); - - for (i = 0; i < customEqualityTesters.length; i++) { - copyAndDeprecate(self, customEqualityTesters, i); - } - - // Avoid copying array props if we've previously done so, - // to avoid triggering our own deprecation warnings. - if (!self.isAsymmetricEqualityTesterArgCompatShim_) { - copyAndDeprecateArrayMethods(self); - } - - self.isAsymmetricEqualityTesterArgCompatShim_ = true; - return self; - } - - function copyAndDeprecateArrayMethods(dest) { - var props = arrayProps(), - i, - k; - - for (i = 0; i < props.length; i++) { - k = props[i]; - - // Skip length (dealt with above), and anything that collides with - // MatchesUtil e.g. an Array.prototype.contains method added by user code - if (k !== 'length' && !dest[k]) { - copyAndDeprecate(dest, Array.prototype, k); - } - } - } - - function copyAndDeprecate(dest, src, propName) { - Object.defineProperty(dest, propName, { - get: function() { - j$.getEnv().deprecated( - 'The second argument to asymmetricMatch is now a ' + - 'MatchersUtil. Using it as an array of custom equality testers is ' + - 'deprecated and will stop working in a future release. ' + - 'See for details.' - ); - return src[propName]; - } - }); - } - - function arrayProps() { - var props, a, k; - - if (!Object.getOwnPropertyDescriptors) { - return likelyArrayProps.filter(function(k) { - return Array.prototype.hasOwnProperty(k); - }); - } - - props = Object.getOwnPropertyDescriptors(Array.prototype); // eslint-disable-line compat/compat - a = []; - - for (k in props) { - a.push(k); - } - - return a; - } - - return asymmetricEqualityTesterArgCompatShim; -}; diff --git a/src/core/asymmetric_equality/MapContaining.js b/src/core/asymmetric_equality/MapContaining.js index 8e29fbe9..9e0ee422 100644 --- a/src/core/asymmetric_equality/MapContaining.js +++ b/src/core/asymmetric_equality/MapContaining.js @@ -13,27 +13,26 @@ getJasmineRequireObj().MapContaining = function(j$) { MapContaining.prototype.asymmetricMatch = function(other, matchersUtil) { if (!j$.isMap(other)) return false; - var hasAllMatches = true; - j$.util.forEachBreakable(this.sample, function(breakLoop, value, key) { + for (const [key, value] of this.sample) { // for each key/value pair in `sample` // there should be at least one pair in `other` whose key and value both match var hasMatch = false; - j$.util.forEachBreakable(other, function(oBreakLoop, oValue, oKey) { + for (const [oKey, oValue] of other) { if ( matchersUtil.equals(oKey, key) && matchersUtil.equals(oValue, value) ) { hasMatch = true; - oBreakLoop(); + break; } - }); - if (!hasMatch) { - hasAllMatches = false; - breakLoop(); } - }); - return hasAllMatches; + if (!hasMatch) { + return false; + } + } + + return true; }; MapContaining.prototype.jasmineToString = function(pp) { diff --git a/src/core/asymmetric_equality/ObjectContaining.js b/src/core/asymmetric_equality/ObjectContaining.js index 5e473033..249716c7 100644 --- a/src/core/asymmetric_equality/ObjectContaining.js +++ b/src/core/asymmetric_equality/ObjectContaining.js @@ -3,18 +3,6 @@ getJasmineRequireObj().ObjectContaining = function(j$) { this.sample = sample; } - function getPrototype(obj) { - if (Object.getPrototypeOf) { - return Object.getPrototypeOf(obj); - } - - if (obj.constructor.prototype == obj) { - return null; - } - - return obj.constructor.prototype; - } - function hasProperty(obj, property) { if (!obj || typeof obj !== 'object') { return false; @@ -24,7 +12,7 @@ getJasmineRequireObj().ObjectContaining = function(j$) { return true; } - return hasProperty(getPrototype(obj), property); + return hasProperty(Object.getPrototypeOf(obj), property); } ObjectContaining.prototype.asymmetricMatch = function(other, matchersUtil) { diff --git a/src/core/asymmetric_equality/SetContaining.js b/src/core/asymmetric_equality/SetContaining.js index fe4d6293..46c0e88c 100644 --- a/src/core/asymmetric_equality/SetContaining.js +++ b/src/core/asymmetric_equality/SetContaining.js @@ -13,25 +13,24 @@ getJasmineRequireObj().SetContaining = function(j$) { SetContaining.prototype.asymmetricMatch = function(other, matchersUtil) { if (!j$.isSet(other)) return false; - var hasAllMatches = true; - j$.util.forEachBreakable(this.sample, function(breakLoop, item) { + for (const item of this.sample) { // for each item in `sample` there should be at least one matching item in `other` // (not using `matchersUtil.contains` because it compares set members by reference, // not by deep value equality) var hasMatch = false; - j$.util.forEachBreakable(other, function(oBreakLoop, oItem) { + for (const oItem of other) { if (matchersUtil.equals(oItem, item)) { hasMatch = true; - oBreakLoop(); + break; } - }); - if (!hasMatch) { - hasAllMatches = false; - breakLoop(); } - }); - return hasAllMatches; + if (!hasMatch) { + return false; + } + } + + return true; }; SetContaining.prototype.jasmineToString = function(pp) { diff --git a/src/core/base.js b/src/core/base.js index ee5c0cad..2e953541 100644 --- a/src/core/base.js +++ b/src/core/base.js @@ -128,25 +128,8 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { if (value instanceof Error) { return true; } - if ( - typeof window !== 'undefined' && - typeof window.trustedTypes !== 'undefined' - ) { - return ( - typeof value.stack === 'string' && typeof value.message === 'string' - ); - } - if (value && value.constructor && value.constructor.constructor) { - var valueGlobal = value.constructor.constructor('return this'); - if (j$.isFunction_(valueGlobal)) { - valueGlobal = valueGlobal(); - } - if (valueGlobal.Error && value instanceof valueGlobal.Error) { - return true; - } - } - return false; + return typeof value.stack === 'string' && typeof value.message === 'string'; }; j$.isAsymmetricEqualityTester_ = function(obj) { @@ -172,7 +155,6 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return ( obj !== null && typeof obj !== 'undefined' && - typeof jasmineGlobal.Map !== 'undefined' && obj.constructor === jasmineGlobal.Map ); }; @@ -181,7 +163,6 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return ( obj !== null && typeof obj !== 'undefined' && - typeof jasmineGlobal.Set !== 'undefined' && obj.constructor === jasmineGlobal.Set ); }; @@ -190,7 +171,6 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return ( obj !== null && typeof obj !== 'undefined' && - typeof jasmineGlobal.WeakMap !== 'undefined' && obj.constructor === jasmineGlobal.WeakMap ); }; @@ -199,26 +179,24 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { return ( obj !== null && typeof obj !== 'undefined' && - typeof jasmineGlobal.URL !== 'undefined' && obj.constructor === jasmineGlobal.URL ); }; + j$.isIterable_ = function(value) { + return value && !!value[Symbol.iterator]; + }; + j$.isDataView = function(obj) { return ( obj !== null && typeof obj !== 'undefined' && - typeof jasmineGlobal.DataView !== 'undefined' && obj.constructor === jasmineGlobal.DataView ); }; j$.isPromise = function(obj) { - return ( - typeof jasmineGlobal.Promise !== 'undefined' && - !!obj && - obj.constructor === jasmineGlobal.Promise - ); + return !!obj && obj.constructor === jasmineGlobal.Promise; }; j$.isPromiseLike = function(obj) { @@ -239,7 +217,6 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { j$.isPending_ = function(promise) { var sentinel = {}; - // eslint-disable-next-line compat/compat return Promise.race([promise, Promise.resolve(sentinel)]).then( function(result) { return result === sentinel; @@ -420,4 +397,20 @@ getJasmineRequireObj().base = function(j$, jasmineGlobal) { putativeSpy.calls instanceof j$.CallTracker ); }; + + /** + * Logs a message for use in debugging. If the spec fails, trace messages + * will be included in the {@link SpecResult|result} passed to the + * reporter's specDone method. + * + * This method should be called only when a spec (including any associated + * beforeEach or afterEach functions) is running. + * @function + * @name jasmine.debugLog + * @since 4.0.0 + * @param {String} msg - The message to log + */ + j$.debugLog = function(msg) { + j$.getEnv().debugLog(msg); + }; }; diff --git a/src/core/deprecatingSpecProxy.js b/src/core/deprecatingSpecProxy.js deleted file mode 100644 index ed80919c..00000000 --- a/src/core/deprecatingSpecProxy.js +++ /dev/null @@ -1,70 +0,0 @@ -/* eslint-disable compat/compat */ -// TODO: Remove this in the next major release. -getJasmineRequireObj().deprecatingSpecProxy = function(j$) { - function isMember(target, prop) { - return ( - Object.keys(target).indexOf(prop) !== -1 || - Object.keys(j$.Spec.prototype).indexOf(prop) !== -1 - ); - } - - function isAllowedMember(prop) { - return prop === 'id' || prop === 'description' || prop === 'getFullName'; - } - - function msg(member) { - var memberName = member.toString().replace(/^Symbol\((.+)\)$/, '$1'); - return ( - 'Access to private Spec members (in this case `' + - memberName + - '`) is not supported and will break in ' + - 'a future release. See ' + - 'for correct usage.' - ); - } - - try { - new Proxy({}, {}); - } catch (e) { - // Environment does not support Poxy. - return function(spec) { - return spec; - }; - } - - function DeprecatingSpecProxyHandler(env) { - this._env = env; - } - - DeprecatingSpecProxyHandler.prototype.get = function(target, prop, receiver) { - this._maybeDeprecate(target, prop); - - if (prop === 'getFullName') { - // getFullName calls a private method. Re-bind 'this' to avoid a bogus - // deprecation warning. - return target.getFullName.bind(target); - } else { - return target[prop]; - } - }; - - DeprecatingSpecProxyHandler.prototype.set = function(target, prop, value) { - this._maybeDeprecate(target, prop); - return (target[prop] = value); - }; - - DeprecatingSpecProxyHandler.prototype._maybeDeprecate = function( - target, - prop - ) { - if (isMember(target, prop) && !isAllowedMember(prop)) { - this._env.deprecated(msg(prop)); - } - }; - - function deprecatingSpecProxy(spec, env) { - return new Proxy(spec, new DeprecatingSpecProxyHandler(env)); - } - - return deprecatingSpecProxy; -}; diff --git a/src/core/deprecatingSuiteProxy.js b/src/core/deprecatingSuiteProxy.js deleted file mode 100644 index e3cf8999..00000000 --- a/src/core/deprecatingSuiteProxy.js +++ /dev/null @@ -1,98 +0,0 @@ -/* eslint-disable compat/compat */ -// TODO: Remove this in the next major release. -getJasmineRequireObj().deprecatingSuiteProxy = function(j$) { - var allowedMembers = [ - 'id', - 'children', - 'description', - 'parentSuite', - 'getFullName' - ]; - - function isMember(target, prop) { - return ( - Object.keys(target).indexOf(prop) !== -1 || - Object.keys(j$.Suite.prototype).indexOf(prop) !== -1 - ); - } - - function isAllowedMember(prop) { - return allowedMembers.indexOf(prop) !== -1; - } - - function msg(member) { - var memberName = member.toString().replace(/^Symbol\((.+)\)$/, '$1'); - return ( - 'Access to private Suite members (in this case `' + - memberName + - '`) is not supported and will break in ' + - 'a future release. See ' + - 'for correct usage.' - ); - } - try { - new Proxy({}, {}); - } catch (e) { - // Environment does not support Poxy. - return function(suite) { - return suite; - }; - } - - function DeprecatingSuiteProxyHandler(parentSuite, env) { - this._parentSuite = parentSuite; - this._env = env; - } - - DeprecatingSuiteProxyHandler.prototype.get = function( - target, - prop, - receiver - ) { - if (prop === 'children') { - if (!this._children) { - this._children = target.children.map( - this._proxyForChild.bind(this, receiver) - ); - } - - return this._children; - } else if (prop === 'parentSuite') { - return this._parentSuite; - } else { - this._maybeDeprecate(target, prop); - return target[prop]; - } - }; - - DeprecatingSuiteProxyHandler.prototype.set = function(target, prop, value) { - this._maybeDeprecate(target, prop); - return (target[prop] = value); - }; - - DeprecatingSuiteProxyHandler.prototype._maybeDeprecate = function( - target, - prop - ) { - if (isMember(target, prop) && !isAllowedMember(prop)) { - this._env.deprecated(msg(prop)); - } - }; - - DeprecatingSuiteProxyHandler.prototype._proxyForChild = function( - ownProxy, - child - ) { - if (child.children) { - return deprecatingSuiteProxy(child, ownProxy, this._env); - } else { - return j$.deprecatingSpecProxy(child, this._env); - } - }; - - function deprecatingSuiteProxy(suite, parentSuite, env) { - return new Proxy(suite, new DeprecatingSuiteProxyHandler(parentSuite, env)); - } - - return deprecatingSuiteProxy; -}; diff --git a/src/core/deprecatingThisProxy.js b/src/core/deprecatingThisProxy.js deleted file mode 100644 index aaa72e8d..00000000 --- a/src/core/deprecatingThisProxy.js +++ /dev/null @@ -1,34 +0,0 @@ -/* eslint-disable compat/compat */ -// TODO: Remove this in the next major release. -getJasmineRequireObj().deprecatingThisProxy = function(j$) { - var msg = - "Access to 'this' in describe functions (and in arrow functions " + - 'inside describe functions) is deprecated.'; - - try { - new Proxy({}, {}); - } catch (e) { - // Environment does not support Poxy. - return function(suite) { - return suite; - }; - } - - function DeprecatingThisProxyHandler(env) { - this._env = env; - } - - DeprecatingThisProxyHandler.prototype.get = function(target, prop, receiver) { - this._env.deprecated(msg); - return target[prop]; - }; - - DeprecatingThisProxyHandler.prototype.set = function(target, prop, value) { - this._env.deprecated(msg); - return (target[prop] = value); - }; - - return function(suite, env) { - return new Proxy(suite, new DeprecatingThisProxyHandler(env)); - }; -}; diff --git a/src/core/matchers/async/toBePending.js b/src/core/matchers/async/toBePending.js index 1e438d4f..d6703d7b 100644 --- a/src/core/matchers/async/toBePending.js +++ b/src/core/matchers/async/toBePending.js @@ -1,4 +1,3 @@ -/* eslint-disable compat/compat */ getJasmineRequireObj().toBePending = function(j$) { /** * Expect a promise to be pending, i.e. the promise is neither resolved nor rejected. diff --git a/src/core/matchers/matchersUtil.js b/src/core/matchers/matchersUtil.js index f8819549..9c9a2c36 100644 --- a/src/core/matchers/matchersUtil.js +++ b/src/core/matchers/matchersUtil.js @@ -29,41 +29,48 @@ getJasmineRequireObj().MatchersUtil = function(j$) { * @since 2.0.0 * @param {*} haystack The collection to search * @param {*} needle The value to search for - * @param [customTesters] An array of custom equality testers. Deprecated. - * As of 3.6 this parameter no longer needs to be passed. It will be removed in 4.0. * @returns {boolean} True if `needle` was found in `haystack` */ - MatchersUtil.prototype.contains = function(haystack, needle, customTesters) { - if (customTesters) { - j$.getEnv().deprecated( - 'Passing custom equality testers ' + - 'to MatchersUtil#contains is deprecated. ' + - 'See for details.' - ); - } - - if (j$.isSet(haystack)) { - return haystack.has(needle); - } - - if ( - Object.prototype.toString.apply(haystack) === '[object Array]' || - (!!haystack && !haystack.indexOf) - ) { - for (var i = 0; i < haystack.length; i++) { - try { - this.suppressDeprecation_ = true; - if (this.equals(haystack[i], needle, customTesters)) { - return true; - } - } finally { - this.suppressDeprecation_ = false; - } - } + MatchersUtil.prototype.contains = function(haystack, needle) { + if (!haystack) { return false; } - return !!haystack && haystack.indexOf(needle) >= 0; + if (j$.isSet(haystack)) { + // Try .has() first. It should be faster in cases where + // needle === something in haystack. Fall back to .equals() comparison + // if that fails. + if (haystack.has(needle)) { + return true; + } + } + + if (j$.isIterable_(haystack) && !j$.isString_(haystack)) { + // Arrays, Sets, etc. + for (const candidate of haystack) { + if (this.equals(candidate, needle)) { + return true; + } + } + + return false; + } + + if (haystack.indexOf) { + // Mainly strings + return haystack.indexOf(needle) >= 0; + } + + if (j$.isNumber_(haystack.length)) { + // Objects that are shaped like arrays but aren't iterable + for (var i = 0; i < haystack.length; i++) { + if (this.equals(haystack[i], needle)) { + return true; + } + } + } + + return false; }; MatchersUtil.prototype.buildFailureMessage = function() { @@ -100,19 +107,11 @@ getJasmineRequireObj().MatchersUtil = function(j$) { b, aStack, bStack, - customTesters, diffBuilder ) { if (j$.isFunction_(b.valuesForDiff_)) { var values = b.valuesForDiff_(a, this.pp); - this.eq_( - values.other, - values.self, - aStack, - bStack, - customTesters, - diffBuilder - ); + this.eq_(values.other, values.self, aStack, bStack, diffBuilder); } else { diffBuilder.recordMismatch(); } @@ -123,22 +122,18 @@ getJasmineRequireObj().MatchersUtil = function(j$) { b, aStack, bStack, - customTesters, diffBuilder ) { var asymmetricA = j$.isAsymmetricEqualityTester_(a), asymmetricB = j$.isAsymmetricEqualityTester_(b), - shim, result; if (asymmetricA === asymmetricB) { return undefined; } - shim = j$.asymmetricEqualityTesterArgCompatShim(this, customTesters); - if (asymmetricA) { - result = a.asymmetricMatch(b, shim); + result = a.asymmetricMatch(b, this); if (!result) { diffBuilder.recordMismatch(); } @@ -146,9 +141,9 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } if (asymmetricB) { - result = b.asymmetricMatch(a, shim); + result = b.asymmetricMatch(a, this); if (!result) { - this.asymmetricDiff_(a, b, aStack, bStack, customTesters, diffBuilder); + this.asymmetricDiff_(a, b, aStack, bStack, diffBuilder); } return result; } @@ -161,58 +156,18 @@ getJasmineRequireObj().MatchersUtil = function(j$) { * @since 2.0.0 * @param {*} a The first value to compare * @param {*} b The second value to compare - * @param [customTesters] An array of custom equality testers. Deprecated. - * As of 3.6 this parameter no longer needs to be passed. It will be removed in 4.0. * @returns {boolean} True if the values are equal */ - MatchersUtil.prototype.equals = function( - a, - b, - customTestersOrDiffBuilder, - diffBuilderOrNothing - ) { - var customTesters, diffBuilder; - - if (isDiffBuilder(customTestersOrDiffBuilder)) { - diffBuilder = customTestersOrDiffBuilder; - } else { - if (customTestersOrDiffBuilder && !this.suppressDeprecation_) { - j$.getEnv().deprecated( - 'Passing custom equality testers ' + - 'to MatchersUtil#equals is deprecated. ' + - 'See for details.' - ); - } - - if (diffBuilderOrNothing) { - j$.getEnv().deprecated( - 'Diff builder should be passed ' + - 'as the third argument to MatchersUtil#equals, not the fourth. ' + - 'See for details.' - ); - } - - customTesters = customTestersOrDiffBuilder; - diffBuilder = diffBuilderOrNothing; - } - - customTesters = customTesters || this.customTesters_; + MatchersUtil.prototype.equals = function(a, b, diffBuilder) { diffBuilder = diffBuilder || j$.NullDiffBuilder(); diffBuilder.setRoots(a, b); - return this.eq_(a, b, [], [], customTesters, diffBuilder); + return this.eq_(a, b, [], [], diffBuilder); }; // Equality function lovingly adapted from isEqual in // [Underscore](http://underscorejs.org) - MatchersUtil.prototype.eq_ = function( - a, - b, - aStack, - bStack, - customTesters, - diffBuilder - ) { + MatchersUtil.prototype.eq_ = function(a, b, aStack, bStack, diffBuilder) { var result = true, self = this, i; @@ -222,15 +177,14 @@ getJasmineRequireObj().MatchersUtil = function(j$) { b, aStack, bStack, - customTesters, diffBuilder ); if (!j$.util.isUndefined(asymmetricResult)) { return asymmetricResult; } - for (i = 0; i < customTesters.length; i++) { - var customTesterResult = customTesters[i](a, b); + for (i = 0; i < this.customTesters_.length; i++) { + var customTesterResult = this.customTesters_[i](a, b); if (!j$.util.isUndefined(customTesterResult)) { if (!customTesterResult) { diffBuilder.recordMismatch(); @@ -302,11 +256,10 @@ getJasmineRequireObj().MatchersUtil = function(j$) { // If we have an instance of ArrayBuffer the Uint8Array ctor // will be defined as well return self.eq_( - new Uint8Array(a), // eslint-disable-line compat/compat - new Uint8Array(b), // eslint-disable-line compat/compat + new Uint8Array(a), + new Uint8Array(b), aStack, bStack, - customTesters, diffBuilder ); // RegExps are compared by their source patterns and flags. @@ -385,7 +338,6 @@ getJasmineRequireObj().MatchersUtil = function(j$) { i < bLength ? b[i] : void 0, aStack, bStack, - customTesters, diffBuilder ) && result; } @@ -430,14 +382,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { if ( j$.isAsymmetricEqualityTester_(mapKey) || (j$.isAsymmetricEqualityTester_(cmpKey) && - this.eq_( - mapKey, - cmpKey, - aStack, - bStack, - customTesters, - j$.NullDiffBuilder() - )) + this.eq_(mapKey, cmpKey, aStack, bStack, j$.NullDiffBuilder())) ) { mapValueB = b.get(cmpKey); } else { @@ -448,7 +393,6 @@ getJasmineRequireObj().MatchersUtil = function(j$) { mapValueB, aStack, bStack, - customTesters, j$.NullDiffBuilder() ); } @@ -499,7 +443,6 @@ getJasmineRequireObj().MatchersUtil = function(j$) { otherValue, baseStack, otherStack, - customTesters, j$.NullDiffBuilder() ); if (!found && prevStackSize !== baseStack.length) { @@ -564,9 +507,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) { } diffBuilder.withPath(key, function() { - if ( - !self.eq_(a[key], b[key], aStack, bStack, customTesters, diffBuilder) - ) { + if (!self.eq_(a[key], b[key], aStack, bStack, diffBuilder)) { result = false; } }); @@ -678,10 +619,6 @@ getJasmineRequireObj().MatchersUtil = function(j$) { return formatted; } - function isDiffBuilder(obj) { - return obj && typeof obj.recordMismatch === 'function'; - } - return MatchersUtil; }; diff --git a/src/core/matchers/toHaveSize.js b/src/core/matchers/toHaveSize.js index 403080a8..87b75af7 100644 --- a/src/core/matchers/toHaveSize.js +++ b/src/core/matchers/toHaveSize.js @@ -37,7 +37,7 @@ getJasmineRequireObj().toHaveSize = function(j$) { }; } - var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // eslint-disable-line compat/compat + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; function isLength(value) { return ( typeof value == 'number' && diff --git a/src/core/requireCore.js b/src/core/requireCore.js index 1b8b5238..e8e17994 100644 --- a/src/core/requireCore.js +++ b/src/core/requireCore.js @@ -44,9 +44,6 @@ var getJasmineRequireObj = (function(jasmineGlobal) { j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(j$); j$.Deprecator = jRequire.Deprecator(j$); j$.Env = jRequire.Env(j$); - j$.deprecatingThisProxy = jRequire.deprecatingThisProxy(j$); - j$.deprecatingSuiteProxy = jRequire.deprecatingSuiteProxy(j$); - j$.deprecatingSpecProxy = jRequire.deprecatingSpecProxy(j$); j$.StackTrace = jRequire.StackTrace(j$); j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); j$.ExpectationFilterChain = jRequire.ExpectationFilterChain(); @@ -54,46 +51,22 @@ var getJasmineRequireObj = (function(jasmineGlobal) { j$.Expectation = jRequire.Expectation(j$); j$.buildExpectationResult = jRequire.buildExpectationResult(j$); j$.JsApiReporter = jRequire.JsApiReporter(j$); - j$.asymmetricEqualityTesterArgCompatShim = jRequire.asymmetricEqualityTesterArgCompatShim( - j$ - ); j$.makePrettyPrinter = jRequire.makePrettyPrinter(j$); j$.basicPrettyPrinter_ = j$.makePrettyPrinter(); - Object.defineProperty(j$, 'pp', { - get: function() { - j$.getEnv().deprecated( - 'jasmine.pp is deprecated and will be removed in a future release. ' + - 'Use the pp method of the matchersUtil passed to the matcher factory ' + - "or the asymmetric equality tester's `asymmetricMatch` method " + - 'instead. See ' + - ' for details.' - ); - return j$.basicPrettyPrinter_; - } - }); j$.MatchersUtil = jRequire.MatchersUtil(j$); - var staticMatchersUtil = new j$.MatchersUtil({ - customTesters: [], - pp: j$.basicPrettyPrinter_ - }); - Object.defineProperty(j$, 'matchersUtil', { - get: function() { - j$.getEnv().deprecated( - 'jasmine.matchersUtil is deprecated and will be removed ' + - 'in a future release. Use the instance passed to the matcher factory or ' + - "the asymmetric equality tester's `asymmetricMatch` method instead. " + - 'See for details.' - ); - return staticMatchersUtil; - } - }); - j$.ObjectContaining = jRequire.ObjectContaining(j$); j$.ArrayContaining = jRequire.ArrayContaining(j$); j$.ArrayWithExactContents = jRequire.ArrayWithExactContents(j$); j$.MapContaining = jRequire.MapContaining(j$); j$.SetContaining = jRequire.SetContaining(j$); j$.QueueRunner = jRequire.QueueRunner(j$); + j$.NeverSkipPolicy = jRequire.NeverSkipPolicy(j$); + j$.SkipAfterBeforeAllErrorPolicy = jRequire.SkipAfterBeforeAllErrorPolicy( + j$ + ); + j$.CompleteOnFirstErrorSkipPolicy = jRequire.CompleteOnFirstErrorSkipPolicy( + j$ + ); j$.ReportDispatcher = jRequire.ReportDispatcher(j$); j$.Spec = jRequire.Spec(j$); j$.Spy = jRequire.Spy(j$); diff --git a/src/core/util.js b/src/core/util.js index c45e38fe..b65a1113 100644 --- a/src/core/util.js +++ b/src/core/util.js @@ -90,20 +90,10 @@ getJasmineRequireObj().util = function(j$) { }; util.errorWithStack = function errorWithStack() { - // Don't throw and catch if we don't have to, because it makes it harder - // for users to debug their code with exception breakpoints. - var error = new Error(); - - if (error.stack) { - return error; - } - - // But some browsers (e.g. Phantom) only provide a stack trace if we throw. - try { - throw new Error(); - } catch (e) { - return e; - } + // Don't throw and catch. That makes it harder for users to debug their + // code with exception breakpoints, and it's unnecessary since all + // supported environments populate new Error().stack + return new Error(); }; function callerFile() { @@ -127,21 +117,6 @@ getJasmineRequireObj().util = function(j$) { StopIteration.prototype = Object.create(Error.prototype); StopIteration.prototype.constructor = StopIteration; - // useful for maps and sets since `forEach` is the only IE11-compatible way to iterate them - util.forEachBreakable = function(iterable, iteratee) { - function breakLoop() { - throw new StopIteration(); - } - - try { - iterable.forEach(function(value, key) { - iteratee(breakLoop, value, key, iterable); - }); - } catch (error) { - if (!(error instanceof StopIteration)) throw error; - } - }; - util.validateTimeout = function(timeout, msgPrefix) { // Timeouts are implemented with setTimeout, which only supports a limited // range of values. The limit is unspecified, as is the behavior when it's diff --git a/src/html/HtmlReporter.js b/src/html/HtmlReporter.js index ac5a4213..7f69cb57 100644 --- a/src/html/HtmlReporter.js +++ b/src/html/HtmlReporter.js @@ -41,6 +41,12 @@ jasmineRequire.HtmlReporter = function(j$) { } }; + ResultsStateBuilder.prototype.jasmineDone = function(result) { + if (result.failedExpectations) { + this.failureCount += result.failedExpectations.length; + } + }; + function HtmlReporter(options) { var config = function() { return (options.env && options.env.configuration()) || {}; @@ -156,6 +162,7 @@ jasmineRequire.HtmlReporter = function(j$) { }; this.jasmineDone = function(doneResult) { + stateBuilder.jasmineDone(doneResult); var banner = find('.jasmine-banner'); var alert = find('.jasmine-alert'); var order = doneResult && doneResult.order; @@ -272,8 +279,10 @@ jasmineRequire.HtmlReporter = function(j$) { } else { return prefix; } - } else { + } else if (failure.globalErrorType === 'afterAll') { return afterAllMessagePrefix + failure.message; + } else { + return failure.message; } } @@ -403,9 +412,53 @@ jasmineRequire.HtmlReporter = function(j$) { ); } + if (result.debugLogs) { + messages.appendChild(debugLogTable(result.debugLogs)); + } + return failure; } + function debugLogTable(debugLogs) { + var tbody = createDom('tbody'); + + debugLogs.forEach(function(entry) { + tbody.appendChild( + createDom( + 'tr', + {}, + createDom('td', {}, entry.timestamp.toString()), + createDom('td', {}, entry.message) + ) + ); + }); + + return createDom( + 'div', + { className: 'jasmine-debug-log' }, + createDom( + 'div', + { className: 'jasmine-debug-log-header' }, + 'Debug logs' + ), + createDom( + 'table', + {}, + createDom( + 'thead', + {}, + createDom( + 'tr', + {}, + createDom('th', {}, 'Time (ms)'), + createDom('th', {}, 'Message') + ) + ), + tbody + ) + ); + } + function summaryList(resultsTree, domParent) { var specListNode; for (var i = 0; i < resultsTree.children.length; i++) { @@ -540,7 +593,7 @@ jasmineRequire.HtmlReporter = function(j$) { var failFastCheckbox = optionsMenuDom.querySelector('#jasmine-fail-fast'); failFastCheckbox.checked = config.stopOnSpecFailure; failFastCheckbox.onclick = function() { - navigateWithNewParam('failFast', !config.stopOnSpecFailure); + navigateWithNewParam('stopOnSpecFailure', !config.stopOnSpecFailure); }; var throwCheckbox = optionsMenuDom.querySelector( @@ -549,7 +602,7 @@ jasmineRequire.HtmlReporter = function(j$) { throwCheckbox.checked = config.stopSpecOnExpectationFailure; throwCheckbox.onclick = function() { navigateWithNewParam( - 'oneFailurePerSpec', + 'stopSpecOnExpectationFailure', !config.stopSpecOnExpectationFailure ); }; diff --git a/src/html/_HTMLReporter.scss b/src/html/_HTMLReporter.scss index dc06ff95..712f6fbb 100644 --- a/src/html/_HTMLReporter.scss +++ b/src/html/_HTMLReporter.scss @@ -413,4 +413,20 @@ body { margin-left: $margin-unit; padding: 5px; } + + .jasmine-debug-log { + margin: 5px 0 0 0; + padding: 5px; + color: $light-text-color; + border: 1px solid #ddd; + background: white; + + table { + border-spacing: 0; + } + + table, th, td { + border: 1px solid #ddd; + } + } } diff --git a/src/templates/version.rb.erb b/src/templates/version.rb.erb deleted file mode 100644 index 7fb8433d..00000000 --- a/src/templates/version.rb.erb +++ /dev/null @@ -1,6 +0,0 @@ -module Jasmine - module Core - VERSION = "<%= "#{major}.#{minor}.#{build}" %><%= ".rc#{release_candidate}" if release_candidate %>" - end -end -