Compare commits

...

299 Commits

Author SHA1 Message Date
Steve Gravrock
d51da18808 Bump version to 3.6.0 2020-07-23 16:02:30 -07:00
Steve Gravrock
6f3e85f755 Only run long property tests once on CI 2020-07-16 13:03:04 -07:00
Steve Gravrock
d04b813cab Merge https://github.com/buildgroundwork/jasmine
* Merges #1766 from @amilligan
2020-07-16 10:18:08 -07:00
Steve Gravrock
70c416d5c9 Fixed jsdocs for recent additions 2020-07-10 15:41:02 -07:00
Steve Gravrock
226d3ba939 Added IE back to the Travis matrix
Now that jasmine-browser works correctly with IE, we can resume testing
against it.
2020-07-09 11:42:29 -07:00
Steve Gravrock
aa6cc31057 Show diffs involving root-level asymmetric equality testers
* Fixes #1831
2020-07-08 17:02:11 -07:00
Steve Gravrock
f8ae3eaeaa Built distribution 2020-07-08 16:53:53 -07:00
Steve Gravrock
db6aa8f3f8 Use a version of eslint that works on Node 8 2020-07-02 08:49:23 -07:00
Steve Gravrock
4e2f703615 Check for syntax and standard library objects that don't work in IE 2020-07-01 17:34:59 -07:00
Steve Gravrock
ba2aae63be Run eslint against all files 2020-07-01 16:09:14 -07:00
Steve Gravrock
fb23277367 Removed IE from Travis build matrix
We still support IE 10 and 11, but the Node selenium-webdriver has
serious problems with it. Until that's fixed or worked around, IE builds
won't pass. This gets us otherwise green so we can easily see if
anything else is broken.
2020-07-01 12:30:24 -07:00
Steve Gravrock
8cd4873e48 Removed broken Sauce status image 2020-06-29 14:37:08 -07:00
Steve Gravrock
11b63e4e3e Fixed references to master in docs 2020-06-29 14:36:00 -07:00
Steve Gravrock
b3ab9fad9d Updated toHaveBeenCalledOnceWith for new matcher interface 2020-06-26 15:14:02 -07:00
Steve Gravrock
13b967b59c Merge branch 'feat/to-have-been-called-once-with' of https://github.com/Maximaximum/jasmine into pr-merge
* Merges #1801 from @Maximaximum
* Fixes #1717
2020-06-26 15:05:04 -07:00
Steve Gravrock
0253d4fb71 Merge branch 'update-throwError-to-throw-objects' of https://github.com/terencehonles/jasmine
* Merges #1822 from @terencehonles
2020-06-26 15:00:32 -07:00
Steve Gravrock
44875673c1 Merge branch '1821-tests' of https://github.com/dasch-swiss/jasmine
* Merges #1829 from @tobiasschweizer
* Fixes #1821
2020-06-26 14:56:08 -07:00
Terence D. Honles
3943cc2ddb allow spy throwError to throw an Object
When using the following code to simulate a node error:

  spyOn(process, 'kill').and.throwError({code: 'ESRCH'})

The object passed in will be converted to a string by the Error
constructor and result in '[object Object]' which is not very useful.
This PR changes the ``throwError`` spy strategy to only convert
strings into an Error object, but any other objects which are passed
in will be thrown as is. This means the spy strategy can never emulate
throwing a bare string ``throw 'error'``, but this would be a backward
incompatible change.
2020-06-25 18:12:00 -07:00
Steve Gravrock
f4753ac0a4 Fixed syntax errors in IE 10 2020-06-25 07:36:06 -07:00
Tobias Schweizer
ce2161ca32 Add additional test for equals matcher 2020-06-25 09:41:39 +02:00
Steve Gravrock
17eda7a2de Depend on head of jasmine-browser
This should fix CI, and can be reverted once a new version of
jasmine-browser that contains 33bd0fcb0ba990102dcd846e673d07b11041dd44
has been published.
2020-06-24 17:50:16 -07:00
Steve Gravrock
7119720fc7 Merge branch 'dp/missing-punctation' of https://github.com/dirkpuge/jasmine
* Merges #1828 from @dirkpuge
2020-06-23 17:02:47 -07:00
Steve Gravrock
f4e192a428 Merge branch 'expose-property' of https://github.com/johnjbarton/jasmine
* Merges #1820 from @johnjbarton
2020-06-23 16:58:54 -07:00
Dirk Puge
45ad7fd13c Added missing periods 2020-06-21 11:48:05 -04:00
johnjbarton
0cb304131f fix(env): expose setSpec/SuiteProperty on interface 2020-05-26 14:50:01 -07:00
Steve Gravrock
8a731e17a7 Improved jsdocs for user-specified spec/suite properties 2020-05-05 17:58:16 -07:00
Steve Gravrock
7416c176a7 Merge branch 'properties' of https://github.com/johnjbarton/jasmine
* Merges #1763 from @johnjbarton
2020-05-05 17:45:43 -07:00
Maksym Kobieliev
0f6ebaa784 Merge branch 'master' into feat/to-have-been-called-once-with 2020-04-14 22:08:13 +03:00
Maksym Kobieliev
f14f620e15 Merge pull request #1 from jasmine/master
Merge master
2020-04-14 22:07:34 +03:00
Maksym Kobieliev
e94e6c5b75 Fix failing unit test 2020-04-14 22:01:56 +03:00
johnjbarton
f90d9943fe feat(env): setSpecProperty/setSuiteProperty(key, value) to attach data to tests
Use setSpecProperty to attach key/value pairs to spec results that can be
picked up in specialized jasmine reporters.  Example use-cases
include:
  * Tagging specs with URLs or string-tokens referencing test-plan docs.
  * Recording performance information for blocks of JS.
Similarly setSuiteProperty attaches key/value pairs to suite results
2020-04-14 11:27:14 -07:00
Steve Gravrock
8991b1bba3 Fixed toHaveSize matcher on IE 10 & 11 2020-04-12 21:22:14 -07:00
Steve Gravrock
78c3a007ad Fixed test failure in Firefox 74 2020-04-11 12:08:49 -07:00
Steve Gravrock
30b31096b8 Merge branch 'master' of https://github.com/chivesrs/jasmine
* Merges #1802 from @chivesrs
2020-04-11 11:32:08 -07:00
Steve Gravrock
2b318a6154 Merge branch 'master' of https://github.com/parloti/jasmine
* Merges #1807 from @parloti
* Fixes #1775
* Prevents undesired reloads when karma-jasmine-html-reporter is used
2020-04-11 11:30:25 -07:00
Steve Gravrock
41293714fd Merge branch 'tobepending' of https://github.com/DCtheTall/jasmine
* Merges #1808 from @DCtheTall
* Fixes #1803
2020-04-11 11:17:49 -07:00
DCtheTall
08779f2657 add missing trailing newline 2020-04-09 15:20:23 -04:00
DCtheTall
76a99aef86 add missing trailing newline 2020-04-09 15:19:47 -04:00
DCtheTall
6b213a958d Add expectAsync().toBePending() 2020-04-09 15:13:33 -04:00
Alex Parloti
9a7dfb15d2 fix #26
fix #26
Returning false will cause 'zone.js' to invoke e.preventDefault(), preventing the page from reloading.
2020-04-02 21:01:56 +02:00
Maksym Kobieliev
ec9904bf52 Fix test 2020-04-02 21:38:54 +03:00
Maksym Kobieliev
bcc28d7063 Output a diff if there was only one call, but with wrong parameters 2020-04-02 21:31:17 +03:00
Gregg Van Hove
79d55216fc Use internal type checks instead of instanceof to support browsers that don't include the types 2020-03-18 08:57:44 -07:00
Gregg Van Hove
7e940542f8 Merge branch 'wokier-toHaveSize'
- Merges #1796 from @wokier
2020-03-18 08:13:50 -07:00
Gregg Van Hove
ec3ebcb7bb Clean up toHaveSize 2020-03-18 08:13:21 -07:00
Francois Wauquier
c521b4d47c toHaveSize 2020-03-18 08:13:10 -07:00
Chives
66fe69a149 Add test for resolveTo/rejectWith with empty parameters 2020-03-16 03:15:58 -04:00
Maksym Kobieliev
e13fd13529 Add a toHaveBeenCalledOnceWith matcher 2020-03-13 20:41:24 +02:00
Gregg Van Hove
f1eac6fb04 Merge branch 'chivesrs-master'
- Merges #1797 from @chivesrs
2020-03-12 12:28:08 -07:00
Chives
6440ca434d Add trailing newlines to example code 2020-02-29 04:30:03 -05:00
Steve Gravrock
93ad31e0af Correctly report spec and suite duration
Previously, suite duration was always reported as 0 and spec duration
was always reported as null. Suites always used a no-op timer, and
specs set their result.duration after the result had already been sent
to reporters.

Fixes #1676.
2020-02-22 16:53:36 -08:00
Steve Gravrock
a6a9550d1e Fixed 'since' versions for MatchersUtil 2020-02-13 10:52:54 -08:00
Steve Gravrock
6c68715554 Removed unnecessary uses of new 2020-02-13 09:26:33 -08:00
Steve Gravrock
258d55469e Merge branch 'cof-merge-candidate'
* Simplifies the matcher interface
* Adds support for custom object formatters
2020-02-12 15:16:28 -08:00
Steve Gravrock
5096d9af4e Don't construct unnecessarily asymmetricEqualityTesterArgCompatShims
This speeds up MatchersUtil#equals by about 6-7x.
2020-02-12 14:23:03 -08:00
Steve Gravrock
3be797c8d8 Fixed diffs involving jasmine.objectContaining 2020-02-12 14:22:51 -08:00
Gregg Van Hove
d10e8c2ddf Merge branch 'enelson/callThrough-constructor' of https://github.com/elliot-nelson/jasmine into elliot-nelson-enelson/callThrough-constructor
- Merges #1782 from @enelson
- Fixes #1760
2020-02-12 11:39:29 -08:00
Steve Gravrock
c2ada1af95 Merge branch 'custom-object-formatters' into cof-merge-candidate 2020-02-11 13:51:17 -08:00
Pivotal
ea3dd9dffc Refer to MatchersUtil instances as matchersUtil, not util 2020-02-10 17:26:05 -08:00
Steve Gravrock
d41139fea2 Added jsdocs for MatchersUtil 2020-02-10 17:26:05 -08:00
Steve Gravrock
873d1c2945 Use custom object formatters for any part of a diff, not just leaf nodes 2020-02-10 17:26:00 -08:00
Steve Gravrock
25816a6e77 Added support for custom object formatters
Custom object formatters allow users to customize how an object is
stringified in matcher failure messages. This can already be done by
adding a `jasmineToString` method to the objects in question. But
it's not always desirable or possible to do that, particularly when
objects of a given "type" do not inherit from a specific prototype.
For instance, suppose a web service returns a list of foos that are
deserialized from JSON, e.g.:

   { fooId: 42, /* more properties */ }

The only way to define `jasmineToString` on those is by writing code to
add it to each instance at runtime. But a custom object formatter can
recognize that the object it's looking at is a foo and format it
accordingly:

   jasmine.addCustomObjectFormatter(function(obj) {
      if (typeof obj.fooId !== 'number') {
            return undefined;
        }

        return '[Foo with ID ' + obj.fooId + ']';
    });

Unlike `jasmineToString`, custom object formatters are scoped to a
particular spec or suite and don't require any changes to the code
under test.
2020-02-10 17:26:00 -08:00
Steve Gravrock
1f23f1e4d2 Inject a per-runable pretty printer into MatchersUtil
This will allow us to add support for custom object formatters, which
will be a per-runable resource like custom matchers, by injecting them
into the pretty-printer.
2020-02-10 17:26:00 -08:00
Steve Gravrock
dec67bd535 Don't require matchers and asymmetric equality testers to pass custom object formatters back to Jasmine
This makes it easier to write high quality matchers and asymmetric equality
testers, and is also a step toward supporting custom object formatters.

Previously, Jasmine passed custom object formatters as the second argument
to matcher factories and as and the second argument to asymmetric equality
testers' `asymmetricMatch` method. Matchers and asymmetric equality testers
were responsible for passing the custom object formatters to methods like
`matchersUtil#equals`:

  function toEqual(util, customEqualityTesters) {
    return {
      compare: function(actual, expected) {
        // ...
        result.pass = util.equals(actual, expected, customEqualityTesters, diffBuilder);

And:

  ArrayContaining.prototype.asymmetricMatch = function(other, customTesters) {
    // ...
    for (var i = 0; i < this.sample.length; i++) {
      var item = this.sample[i];
      if (!j$.matchersUtil.contains(other, item, customTesters)) {
        return false;
      }
    }

With this change, that is no longer necessary. Matchers and asymmetric
equality testers can ignore the existence of custom equality testers and
still fully support them:

  function toEqual(util) {
    return {
      compare: function(actual, expected) {
        // ...
        result.pass = util.equals(actual, expected, diffBuilder);

And:

  ArrayContaining.prototype.asymmetricMatch = function(other, matchersUtil) {
    // ...
    for (var i = 0; i < this.sample.length; i++) {
      var item = this.sample[i];
      if (!matchersUtil.contains(other, item)) {
        return false;
      }
    }

The old interfaces are still supported, for now, but will be deprecated
in a future commit and removed in the next major release after that.

In addition to making matchers and custom equality testers simpler,
this change sets the stage for adding support for custom object
formatters. Those will be architecturally similar to custom equality
testers, and by injecting a `MatchersUtil` instance everywhere we can
add them without requiring user code to pass them around as used to be
the case with custom object formatters.
2020-02-10 17:25:50 -08:00
Steve Gravrock
83b336d9d1 Merge branch 'matcher-integration-tests' 2020-02-06 18:16:06 -08:00
Elliot Nelson
be3c8275d4 Tidy up SpyStrategy#exec 2020-02-06 10:34:55 -05:00
Elliot Nelson
bf4694333c Improve wrapper function and parameter naming 2020-02-06 10:29:02 -05:00
Elliot Nelson
9febe3159d Allow callThrough to call constructor functions without errors 2020-01-28 19:40:44 -05:00
Steve Gravrock
5e98ee951c Realign the browser testing matrix to match current reality
* Use Windows instead of Linux so we can get current browsers from Sauce.
* Test against the version of Firefox that corresponds to ESR as well as
  latest.
* Test the latest Edge rather than a specific older version.
* Test Safari 8 and 13 instead of 8, 9 and 10. What works in those versions
  is likely to work in the ones in between.
2020-01-20 12:08:01 -08:00
Steve Gravrock
fd5b9ce1ae Fixed spec failure in IE 2020-01-20 11:40:26 -08:00
Steve Gravrock
58c63e98bb Include stack traces in unhandled promise rejection messages 2020-01-20 10:50:42 -08:00
Steve Gravrock
7f392d188e Don't leak global error handlers between Jasmine's own tests 2020-01-20 10:18:29 -08:00
Steve Gravrock
6baf3a9270 Merge branch 'unhandledrejection' of https://github.com/johnjbarton/jasmine into browser-unhandled-rejections
* Merges #1778 from @johnjbarton
* Fixes #1777
2020-01-15 22:10:50 -08:00
johnjbarton
1545112744 feat(GlobalErrors): Route unhandledrejections to onerror
Fixes #1777
2020-01-14 09:38:59 -08:00
Steve Gravrock
8a5216401f Built distribution 2020-01-11 14:29:24 -08:00
Steve Gravrock
fffb8abb24 Moved property tests to the main suite
Property tests can only run in Node, so they were previously in another
directory that only gets run in Node. Now they're next to the related
non-property tests and marked pending in the browser. This makes it more
likely that a developer who normally only runs tests in the browser will
notice and run them.
2020-01-11 10:49:37 -08:00
Steve Gravrock
17e9088ac5 Merge branch 'add-it-naming' of https://github.com/johnlinp/jasmine
* Merges #1772 from @johnlinp
2020-01-11 09:17:45 -08:00
Steve Gravrock
d19ffcc231 Merge branch 'consider-all-error-messages' of https://github.com/vhermannitk/jasmine
* Merges #1776 from @vhermannitk
* Fixes #1771
2020-01-11 09:14:20 -08:00
Valentin Hermann
0b4a9edff8 Added some tests and modified the source code instead of the build product 2020-01-08 10:55:14 +01:00
Valentin Hermann
e02c24d151 Revert "Improves method messagePrefixLength. Now error messages like ReferenceError or TypeError are considered, too"
This reverts commit 913ad50a76.
2020-01-08 08:47:08 +01:00
Valentin Hermann
913ad50a76 Improves method messagePrefixLength. Now error messages like ReferenceError or TypeError are considered, too 2020-01-07 15:49:43 +01:00
Valentin Hermann
c395c525dc Revert "Improves method messagePrefixLength. Now error messages like ReferenceError or TypeError are considered as well"
This reverts commit 12fefa4b3d.
2020-01-07 15:41:02 +01:00
Valentin Hermann
12fefa4b3d Improves method messagePrefixLength. Now error messages like ReferenceError or TypeError are considered as well 2020-01-07 15:23:37 +01:00
Steve Gravrock
88b98277bc Fixed Travis build 2020-01-04 16:15:18 -08:00
Steve Gravrock
4eded6ab61 Added basic property tests for matchersUtil.equals
* See #1764 from @dubzzz
* Property tests are only run in Node, not browser.
* The Travis build sets JASMINE_LONG_PROPERTY_TESTS to enable much more
  thorough (but slow) testing.
2020-01-04 14:52:34 -08:00
John Lin
6c766b7785 Describe the naming for the function it()
When I first saw it(), I was wondering if the name "it" is
an abbreviation of anything. After some search, I finally
realized that the name is only a pronoun. Therefore, I
think it's worthwhile to include it in the documentation.
2019-12-16 12:50:18 +08:00
Adam Milligan
13ff1e037e Make changes in source files 2019-11-22 17:47:20 -05:00
Steve Gravrock
a00f995c68 Added integration tests for existing matcher interfaces 2019-11-17 15:11:58 -08:00
Steve Gravrock
795a80ec66 Added integration tests for asymmetric equality testers 2019-11-17 15:11:53 -08:00
Adam Milligan
3d1a96e020 Extend Jasmine env into correct global 2019-11-05 10:54:46 -05:00
Adam Milligan
076093c16c Properly import jasmineRequire object before using 2019-11-04 11:38:53 -05:00
Steve Gravrock
8d53f4d202 Fixed objectContaining to not match when the expected is the empty object and the actual is a non-object 2019-11-02 14:38:06 -07:00
Steve Gravrock
71631a6529 Test IE before other browsers on Travis
If the tests only fail on one browser, it's usually IE. So testing
IE first gives us faster feedback in cases where we're actively
watching the Travis build.
2019-11-02 13:14:49 -07:00
Steve Gravrock
bed56a76f8 Merge branch 'fix/number-compare-failure' of https://github.com/dubzzz/jasmine
* Merges #1764 from @dubzzz
2019-11-02 11:52:01 -07:00
Nicolas DUBIEN
97fe2e7c95 Fix: Jasmine reports toEqual(0, Number.MIN_VALUE) to be true 2019-10-31 00:31:27 +01:00
Steve Gravrock
ef3f127d27 Fixed comparison between ObjectContaining and non-objects on IE 2019-09-28 18:39:43 -07:00
Steve Gravrock
472f61ab37 Provide better diffs for object graphs that include objectContaining
Turns this output:
    Expected $[0].foo = Object({ a: 4, b: 5 }) to equal <jasmine.objectContaining(Object({ a: 1, c: 3 }))>.

into this:
    Expected $[0].foo.a = 4 to equal 1.
    Expected $[0].foo.c = undefined to equal 3.

And turns this output:
    Expected spy jasmineDone to have been called with:
       [ ... snipped very long expected call ]
    but actual calls were:
       [ ... snipped very long actual call ]

    Call 0:
      Expected $[0] = Object({ overallStatus: 'failed', totalTime: 1, incompleteReason: undefined, order: Order({ random: true, seed: '88732', sort: Function }), failedExpectations: [ Object({ matcherName: 'toBeResolved', passed: false, message: 'Suite "a suite" ran a "toBeResolved" expectation after it finished.
      Did you forget to return or await the result of expectAsync?', error: undefined, errorForStack: Error, actual: [object Promise], expected: [  ], globalErrorType: 'lateExpeztation' }) ], deprecationWarnings: [  ] }) to equal <jasmine.objectContaining(Object({ failedExpectations: [ <jasmine.objectContaining(Object({ passed: false, globalErrorType: 'lateExpectation', message: 'Suite "a suite" ran a "toBeResolved" expectation after it finished.
      Did you forget to return or await the result of expectAsync?', matcherName: 'toBeResolved' }))> ] }))>.

into this:
    Expected spy jasmineDone to have been called with:
       [ ... snipped very long expected call ]
    but actual calls were:
       [ ... snipped very long actual call ]

    Call 0:
      Expected $[0].failedExpectations[0].globalErrorType = 'lateExpeztation' to equal 'lateExpectation'.
2019-09-28 18:03:12 -07:00
Steve Gravrock
10dbf8be98 Indent multiline failure messages in the output of withContext
This makes it easier to see where each failure message begins and ends.

Before:
   Some context: a
   multiline
   message

After:
   Some context:
       a
       multiline
       message
2019-09-28 12:38:28 -07:00
Steve Gravrock
a497d0942a Report async expectations that complete after the runable completes
It's very easy to forget to `await` or `return` the promise returned
from `expectAsync`. When that happens, the expectation failure will
occur after the spec or suite's result has been reported to reporters,
and the failure will typically not be shown to the user. This change
adds a top-level suite failure in that case, similar to the way we
report unhandled exceptions or promise rejections that occur after the
runable completes. Adding the error at the top level gives us the best
chance of getting in before the set of failures we add it to is sent
to reporters.

See #1752.
2019-09-27 18:31:01 -07:00
Gregg Van Hove
9a41154e3b Merge branch 'apla-master'
- Merges #1678 from @apla
2019-09-23 16:48:22 -07:00
ivan baktsheev
fc3eb0fbd8 Handle node.js assert as an error in your specs 2019-09-23 16:47:07 -07:00
Steve Gravrock
223924a7a1 Fixed matchersUtil.contains test to fail correctly 2019-09-22 08:44:15 -07:00
Gregg Van Hove
99799f72b3 Still need some ruby stuff around to release the jasmine-core gem 2019-09-20 17:15:47 -07:00
Gregg Van Hove
e8263e38aa bump version to 3.5.0 2019-09-20 16:57:20 -07:00
Steve Gravrock
53561ae71f Show details of syntax (etc) errors when loading Jasmine's own specs 2019-09-11 13:31:01 -07:00
Steve Gravrock
68f25a758d Don't create env instances in beforeEach 2019-09-11 13:31:01 -07:00
Steve Gravrock
96ba66ad60 Built distribution 2019-09-10 11:23:27 -07:00
Steve Gravrock
ba4a8d1d00 Fixed jsdocs 2019-09-10 11:23:11 -07:00
Steve Gravrock
65d9e93a88 Removed broken & long-disabled JsApiReporter integration specs 2019-09-10 09:38:38 -07:00
Steve Gravrock
2d3ac38df8 toBeRejectedWithError can expect the error to be Error, not just a subtype 2019-09-06 14:17:52 -07:00
Steve Gravrock
5a219da848 Added basic integration tests for all built-in matchers 2019-09-06 14:10:16 -07:00
Steve Gravrock
f056f3b86c Fixed indentation 2019-09-06 13:43:30 -07:00
Steve Gravrock
aeb0b73008 Merge branch 'dtychshenko-1740-fail-on-no-expectations'
* Merges #1743 from @dtychshenko
* Fixes #1740
2019-09-05 09:50:12 -07:00
Dmitriy T
7263a38c3f Adds new configuration option to failSpecWithNoExpectations that will report specs without expectations as failures if enabled 2019-09-05 09:47:38 -07:00
Gregg Van Hove
e8870db8d3 Merge branch 'fix-missing-asynchronous-stacktrace' of https://github.com/prantlf/jasmine into prantlf-fix-missing-asynchronous-stacktrace
- Merges #1738 from @prantlf
- Fixes #1728
2019-09-04 17:42:07 -07:00
Steve Gravrock
35d15085e3 Show argument diffs in toHaveBeenCalledWith failure messages
* Fixes #1641
2019-09-03 17:18:07 -07:00
Steve Gravrock
19292e4ea4 Stop testing against PhantomJS
PhantomJS is at end of life, and the last version of Selenium that supported
it was 3.6.0, released almost three years ago. We can't test Jasmine against
PhantomJS without pinning key pieces of the project to increasingly outdated
versions of key libraries.
2019-09-03 15:40:53 -07:00
Steve Gravrock
ba71989d4b Fixed code formatting 2019-09-03 15:39:00 -07:00
Steve Gravrock
f8e5ea14bc Fail the CI build if the promise returned from jasmineBrowser.runSpecs is rejected 2019-09-03 15:34:56 -07:00
Steve Gravrock
92dfbdcdc9 Depend on acorn to work around broken deduping
See <https://github.com/eslint/espree/issues/393>.
2019-09-03 15:30:42 -07:00
Steve Gravrock
8ad1dd163b Merge branch 'arrayContaining-actuals-must-be-arrays' of https://github.com/divido/jasmine
* Merges #1746 from @divido
* Fixes #1745
2019-08-30 13:12:47 -07:00
Steve Gravrock
ded8b760aa Merge branch 'UziTech-patch-1'
* Merges #1732 from @UziTech
2019-08-30 10:27:53 -07:00
Tony Brix
07318fba37 docs change 2019-08-30 12:14:19 -05:00
Steve Gravrock
c42358c686 Fixed test failure on IE 2019-08-30 09:30:23 -07:00
Tony Brix
f77ee32c56 Add custom async matchers 2019-08-30 09:30:14 -07:00
David Diederich
0bd636b5d2 Updated arrayContaining to require actual values to be arrays
If the actual value of a test was a string, this was matching against arrays
that contained the strings. This was due to the use of the contains matcher,
which against string looks for substrings, when it was intended to look for
array elements.
2019-08-30 01:09:53 -04:00
Pivotal
008b80adc5 Merge branch 'enelson/default' of https://github.com/elliot-nelson/jasmine
* Merges #1716 from @elliot-nelson
2019-08-29 13:50:27 -07:00
Steve Gravrock
1a63ab4677 Accept configurations with Promise: undefined.
Fixes Karma and anything else that uses Env#configuration
as a starting point for a Jasmine config.
2019-08-26 15:45:13 -07:00
Ferdinand Prantl
3a7fc63879 Pick the error instance to pass to error handlers in QueueRunner
The first number is the error message in HTML5 browser, which does not include
the call stack. The error instance allows logging the complete call stack in
reporters.
2019-08-11 09:32:31 +02:00
Ferdinand Prantl
527619b0aa Restore the original global error hanler to pass all parameters along 2019-08-11 09:31:43 +02:00
Gregg Van Hove
0449b35f5a Merge branch 'tobe-tostring' of https://github.com/johnjbarton/jasmine into johnjbarton-tobe-tostring
- Merges #1718 from @johnjbarton
- Fixes #1726
2019-08-07 12:03:46 -07:00
Steve Gravrock
e50a7b6985 Merge branch 'add-map-set-matchers' of https://github.com/eventlistener/jasmine
* Merges #1741 from @eventlistener
2019-08-03 12:18:35 -07:00
Steve Gravrock
b2d9aab2b8 Use the same spec file pattern for both node and browser 2019-08-03 12:17:52 -07:00
Olga Kozlova
b01d86840a mapContaining and setContaining asymmetric matchers 2019-08-03 22:14:48 +03:00
sgravrock
385ad33f60 Merge pull request #1736 from olleolleolle/patch-1
Gemspec: Drop EOL'd property rubyforge_project
2019-08-03 08:58:01 -07:00
Steve Gravrock
18195a868c Updated async timeout message
There are now multiple ways to do async functions, and callbacks
are probably the least common in new code, so the message should
be more general rather than referring to callbacks.
2019-08-03 08:25:57 -07:00
Ferdinand Prantl
7c3434723e Use the documented interface to pick the error instance from the global error handler 2019-07-21 23:46:14 +02:00
Ferdinand Prantl
4858a62fdc Add a unit test for the global error handling including stacktrace 2019-07-16 12:00:09 +02:00
Ferdinand Prantl
df4b6e58e2 Pass the error including stacktrace to error handlers and reporters
The global window error handler is used to handle errors thrown from within asynchronous functions and tests. The first parameter is the error; the fifth parameter is the full error object including the stacktrace. Searching for the first occurrence of an error instance to work with browsers, which may not comply with the HTML5 standard.
2019-07-15 14:43:22 +02:00
Olle Jonsson
d68b47b76d Gemspec: Drop EOL'd property rubyforge_project 2019-07-14 10:38:36 +02:00
Steve Gravrock
c100bb6242 Made output of toHaveBeenCalledWith more readable
This breaks each call out onto its own line, so that it's much easier to
see where each call starts and how they differ. E.g. previously the output
would be:

    Expected spy foo to have been called with [ 'bar', 'baz', 'qux' ] but actual calls were [ [ 42, 'wibble' ], [ 'bar' 'qux' ], [ 'grault '] ]

Now it's:

    Expected spy foo to have been called with:
      [ 'bar', 'baz', 'qux' ]
    but actual calls were:
      [ 42, 'wibble' ],
      [ 'bar' 'qux' ],
      [ 'grault '].
2019-07-13 10:37:05 -07:00
Gregg Van Hove
c37e9b9db0 Add saucelabs badge to readme 2019-07-07 19:37:09 -07:00
Gregg Van Hove
5e87e1410d update to newer jasmine-browser-runner 2019-07-07 19:20:45 -07:00
Gregg Van Hove
0cd5d9339b Use node 10 for browser based builds 2019-07-07 19:01:36 -07:00
johnjbarton
6324fda065 PrettyPrinter survives if objects throw in toString 2019-06-27 10:35:59 -07:00
Gregg Van Hove
066162d6bc Merge branch 'enelson/spyobjproperty' of https://github.com/elliot-nelson/jasmine into elliot-nelson-enelson/spyobjproperty
- Merges #1722 from @elliot-nelson
- Closes #1569
- Fixes #1442
2019-06-25 16:26:43 -07:00
Gregg Van Hove
ab01fa1978 Merge pull request #1721 from elliot-nelson/enelson/gitattributes
Fix: don't attempt to normalize PNGs (gitattributes)
2019-06-24 16:16:37 -07:00
Elliot Nelson
65e6df55ee Linting fixes 2019-06-20 07:34:31 -04:00
Elliot Nelson
45475f6d1e Allow users to pass property names to createSpyObj 2019-06-20 07:33:10 -04:00
Elliot Nelson
a536ca19f2 Don't attempt to normalize PNGs 2019-06-20 06:46:51 -04:00
Gregg Van Hove
9a6262e3cd bump browser runner to new version 2019-06-14 16:42:10 -07:00
Gregg Van Hove
e7d0d742a8 only turn on sauce_connect for jobs that need it (I think) 2019-06-14 15:43:14 -07:00
Gregg Van Hove
031515db23 rejigger travis again to not run sauce jobs for PRs 2019-06-14 15:27:24 -07:00
Gregg Van Hove
49fd22ffe6 move everything we can into the env matrix for travis 2019-06-14 15:15:29 -07:00
Gregg Van Hove
5c058b5bc4 Don't include node 10 & 12 in matrix, we're explicit later 2019-06-14 15:11:41 -07:00
Gregg Van Hove
18dbbca436 Refactor travis matrix to compress a bit more 2019-06-14 15:10:16 -07:00
Gregg Van Hove
3e888105f0 Calculate total suite run time inside the env and report in jasmineDone 2019-06-14 14:59:33 -07:00
Gregg Van Hove
15f969bee7 Add @since to most JSDoc comments
- See jasmine/jasmine.github.io#117
2019-06-12 16:23:12 -07:00
Gregg Van Hove
984018bfdf Make no expectations in HTML Reporter message a warning
- Fixes #1704
2019-06-12 13:31:25 -07:00
Gregg Van Hove
0f4e53d0e6 Update ci script to pass linting 2019-06-12 12:15:34 -07:00
Gregg Van Hove
c73c5a9dbd WIP 2019-06-12 11:42:47 -07:00
Gregg Van Hove
243adfd4ce Use jasmine-browser-runner to execute browser tests 2019-06-12 11:33:14 -07:00
Elliot Nelson
e07da96354 Apply prettier 2019-06-07 23:33:06 -04:00
Elliot Nelson
96786c793f Allow users to set a default spy strategy 2019-06-07 23:32:13 -04:00
Gregg Van Hove
d610d0bdad Use browser-runner to start server in CI 2019-06-06 14:46:19 -07:00
Gregg Van Hove
0644731680 Switch to using new jasmine-browser-runner to server files for local testing 2019-06-06 14:07:30 -07:00
Gregg Van Hove
8da1fd1ed1 Merge branch 'master' of https://github.com/pixelpax/jasmine into pixelpax-master
- Merges #1713 from @pixelpax
2019-05-30 17:47:16 -07:00
Gregg Van Hove
8af669677a Cleanup spy promise strategies to be more consistent with Jasmine at large
- Rename `resolveWith` to `resolveTo` to match `toBeResolvedTo`
- No longer wrap non-Errors in `rejectWith`

- Fixes #1715
2019-05-23 17:29:12 -07:00
Gregg Van Hove
b4cbe9850f add prettier and eslint 2019-05-21 18:23:48 -07:00
Gregg Van Hove
cf2c5c9acc Merge branch 'enelson/src-cleanup-2' of https://github.com/elliot-nelson/jasmine into elliot-nelson-enelson/src-cleanup-2
- Merges #1708 from @elliot-nelson
2019-05-21 17:45:46 -07:00
Gabriel Elkind
4e10cf84d5 Adds in the source-- whoops! 2019-05-20 23:51:29 -05:00
Gregg Van Hove
9f875ce666 Older versions don't support const, use var 2019-05-20 17:56:27 -07:00
Gregg Van Hove
df6a71e37d Merge branch 'spy-to-string' of https://github.com/johnjbarton/jasmine into johnjbarton-spy-to-string
- Merges #1712 from @johnjbarton
2019-05-20 17:22:05 -07:00
Gregg Van Hove
32a3288c9d Merge branch 'elliot-nelson-enelson/pp' 2019-05-20 17:18:29 -07:00
Gregg Van Hove
b12981a3e7 build dist for rounding fix 2019-05-20 17:17:55 -07:00
Gregg Van Hove
cbbdd360f8 Merge branch 'enelson/pp' of https://github.com/elliot-nelson/jasmine into elliot-nelson-enelson/pp
- Merges #1711 from @elliot-nelson
- Closes #1700
- Closes #1575
2019-05-20 17:13:41 -07:00
Gregg Van Hove
3a89cc92fb Merge branch 'paulvanbrenk-fix-1695'
- Merges #1710 from @paulvanbrenk
- Fixes #1695
2019-05-20 17:10:39 -07:00
Gabriel Elkind
88c8c905ba Adds width to root level html-reporter class 2019-05-20 15:25:38 -05:00
johnjbarton
d1adbdc72b fix(PrettyPrint): jasmine.createSpyObj('obj', ['toString']);
The PrettyPrint handler for scalars uses toString() but if that method
has been spyed on, then the stringify fails with
TypeError: Cannot read property 'length' of undefined.

By hanlding this case earlier in format() we avoid the error.

Add unit test covering this case.
2019-05-20 09:33:47 -07:00
Elliot Nelson
8225bb935f Explicitly test pretty printing objects with nested invalid toString 2019-05-20 09:09:07 -04:00
Elliot Nelson
9f704b6f3a PrettyPrinter handles objects with invalid toString implementations 2019-05-20 09:01:10 -04:00
Paul van Brenk
69a7449e50 Fix toBeCloseTo matcher for Node.js 12 and Chrome 74 2019-05-19 12:46:32 -04:00
Elliot Nelson
b1da6e3960 Cleanup: unused vars, dangling commas, negation 2019-05-18 08:11:47 -04:00
Elliot Nelson
1e855aa9b8 Cleanup: whitespace 2019-05-18 08:10:11 -04:00
Gregg Van Hove
e04d3d8a62 Fix bad merge for spyOnProperty error message 2019-05-17 17:07:47 -07:00
Gregg Van Hove
06814769c6 Merge branch 'enelson/spyregerrors' of https://github.com/elliot-nelson/jasmine into elliot-nelson-enelson/spyregerrors
- Merges #1706 from @elliot-nelson
2019-05-17 16:44:26 -07:00
Gregg Van Hove
309e6df8fd Use Object.create to make an object with null prototype 2019-05-17 16:31:15 -07:00
Gregg Van Hove
ea1bac5b74 Merge branch 'enelson/spyonproperty' of https://github.com/elliot-nelson/jasmine into elliot-nelson-enelson/spyonproperty
- Merges #1705 from @elliot-nelson
2019-05-17 16:21:17 -07:00
Elliot Nelson
befb8995e6 spyOnProperty jasmine-style error messages with usage note 2019-05-17 12:02:44 -04:00
Elliot Nelson
1e13039478 spyOnProperty respects the allowRespy flag 2019-05-17 11:43:22 -04:00
Gregg Van Hove
11b0d95a7d Merge branch 'enelson/toBeInstanceOf' of https://github.com/elliot-nelson/jasmine into elliot-nelson-enelson/toBeInstanceOf
- Merges #1697 from @elliot-nelson
2019-05-16 17:35:09 -07:00
Gregg Van Hove
95f6ba5fa2 Merge branch 'elliot-nelson-enelson/ci-errors' 2019-05-15 17:54:50 -07:00
Gregg Van Hove
d331e9cc38 Merge branch 'enelson/ci-errors' of https://github.com/elliot-nelson/jasmine into elliot-nelson-enelson/ci-errors
- Merges #1701 from @elliot-nelson
2019-05-15 17:54:24 -07:00
Gregg Van Hove
0129a7d007 Update contributing doc based on some of the newer tooling
- Fixes #1702
2019-05-15 17:34:57 -07:00
Elliot Nelson
0fded24d35 Introduce matchers#toBeInstanceOf 2019-05-15 11:51:46 -04:00
Elliot Nelson
c88c772ffb Print global errors encountered during CI runs 2019-05-15 11:39:45 -04:00
Gregg Van Hove
3dde56bbd8 Merge branch 'enelson/spyonall' of https://github.com/elliot-nelson/jasmine into elliot-nelson-enelson/spyonall
- Merges #1699 from @elliot-nelson
- Fixes #1677
2019-05-14 18:01:27 -07:00
Gregg Van Hove
e377f1caae Merge branch 'elliot-nelson-enelson/ci'
- Merges #1598 from @elliot-nelson
2019-05-14 17:21:28 -07:00
Elliot Nelson
91fe87ca56 Simplify error checks in ci.js 2019-05-14 06:57:46 -04:00
Elliot Nelson
ee15309a8f Extend spyOnAllFunctions to include prototype and parent methods 2019-05-11 18:20:13 -04:00
Elliot Nelson
49c03d4a22 Improve error handling in CI test launcher 2019-05-10 06:18:35 -04:00
Gregg Van Hove
9a18fdca27 Merge branch 'enelson/spystrategies' of https://github.com/elliot-nelson/jasmine into elliot-nelson-enelson/spystrategies
- Merges #1688 from @enelson
- See #1590
2019-05-09 17:30:45 -07:00
Elliot Nelson
b2fb92eedd Promise-based strategies are now named resolveWith and rejectWith 2019-05-09 06:12:06 -04:00
Elliot Nelson
df818f3fbc rejectValue wraps non-Errors like throwError does 2019-05-08 09:36:12 -04:00
Elliot Nelson
4731b4ee4d Keep all Promise implementation details internal 2019-05-08 09:13:41 -04:00
Gregg Van Hove
eb30e8179a Update deprecation messages to indicate _future_ removal
- Fixes #1628
2019-05-07 17:10:04 -07:00
Elliot Nelson
95e1890e64 Improved resolveValue/rejectValue error messages 2019-05-07 16:30:48 -04:00
Elliot Nelson
72aa0bbe4d Add resolveValue and rejectValue spy strategies 2019-05-05 08:08:34 -04:00
Steve Gravrock
17a9a6417a Fixed test failure in Firefox 66.0.2 2019-05-04 10:51:34 -07:00
Gregg Van Hove
d856b0548a Merge branch 'megahertz-feature-to-be-rejected-with-error'
- Merges #1686 from @megahertz
- Fixes #1625
2019-05-03 16:36:37 -07:00
Alexey Prokhorov
8ab46566ac Fix failure messages for toBeRejectedWithError matcher 2019-05-03 09:37:11 +04:00
Alexey Prokhorov
35968e4a60 Add toBeRejectedWithError matcher 2019-04-26 01:46:56 +04:00
Gregg Van Hove
afb24d1050 Ignore internal ci.js from npm package
- See #1684
2019-04-22 18:10:43 -07:00
Gregg Van Hove
c6d637dcb3 Bump some dependencies 2019-04-22 18:03:37 -07:00
Gregg Van Hove
2fbeb201bc Fix failure messages for positive/negative infinity matchers
- Fixes #1674
2019-04-16 17:40:07 -07:00
Gregg Van Hove
fd60b5737c Merge pull request #1680 from acinader/patch-1
nit: fix typo
2019-04-15 17:56:23 -07:00
Gregg Van Hove
b994a17039 Merge branch 'FelixRilling-boolean-matcher'
- Merges #1679 from @FelixRilling
2019-04-15 17:48:49 -07:00
Arthur Cinader
74fa38bdfb nit: fix typo 2019-04-14 10:33:51 -05:00
Felix Rilling
369e810791 added #toBeTrue and #toBeFalse matchers 2019-04-14 10:17:59 +02:00
Gregg Van Hove
8fca3b4c11 Fix links in 3.4 release notes 2019-04-03 17:13:18 -07:00
Gregg Van Hove
e636f5f822 Bump version to 3.4 2019-04-03 17:03:07 -07:00
Gregg Van Hove
74fd0e08e7 No fit in the suite 2019-04-01 21:01:22 -07:00
Gregg Van Hove
618e24b2f8 Handle WebSocket events in IE when detecting Errors
- Fixes #1623
2019-04-01 18:52:27 -07:00
Gregg Van Hove
5c7e25e228 Allow excluded specs in CI without breaking the output 2019-04-01 18:52:01 -07:00
Gregg Van Hove
54af109d40 Merge branch 'wood1986-fix/npm-audit-dependencies-and-fast-glob-only-failed-tests'
- Merges #1672 from @wood1986
2019-03-26 17:12:53 -07:00
wood
873a237e3d Consolidate some dev dependencies and use more maintained versions 2019-03-26 17:12:21 -07:00
Gregg Van Hove
8ca4463e01 Make node execution default and override for browsers 2019-03-25 18:37:50 -07:00
Gregg Van Hove
449eb516cc Fix sauce status codes and try travis built-in node support 2019-03-25 18:33:39 -07:00
Gregg Van Hove
a5df5a6ee9 Use the correct env var from travis for tunnels 2019-03-25 18:12:15 -07:00
Gregg Van Hove
be583232b4 bump dependencies for security fixes 2019-03-25 18:01:13 -07:00
Gregg Van Hove
d389d3c002 Merge branch 'wood1986-features/no-ruby'
- Merges #1658 from @wood1986
- Fixes #883
2019-03-25 17:56:19 -07:00
Gregg Van Hove
994d11d4f3 update node CI script to work with SauceLabs 2019-03-25 17:56:06 -07:00
wood
828d14f48e Use node.js for browser-based CI 2019-03-25 17:55:53 -07:00
Gregg Van Hove
f5663a9076 Merge branch 'johnjbarton-duration'
- Merges #1660 from @johnjbarton
- Fixes #1646
2019-03-14 19:12:39 -07:00
johnjbarton
a8c2399dd8 feat(result.duration): report test duration in ms
Wrap spec start/complete in Timer start/elapsed.
configuration.timeSpecDuration = false will disable feature.

 * Add Suite result.duration, elapsed time in ms

 * Remove timeSpecDuration option.

 * Respond to review, use noopTimer
2019-03-14 09:13:57 -07:00
Gregg Van Hove
7c0f013003 Merge branch 'johnjbarton-noop-timer'
- Merges #1669 from @johnjbarton
2019-03-13 17:34:12 -07:00
johnjbarton
ca2b62b00e refactor(Timer): share htmlReporter noopTimer via Timer.js 2019-03-12 16:26:04 -07:00
Gregg Van Hove
4108deca02 Build distribution for various typo PRs 2019-03-11 17:39:03 -07:00
Gregg Van Hove
def278f90f Merge branch 'typo-suites' of https://github.com/FelixRilling/jasmine into FelixRilling-typo-suites
- Merges #1666 from @FelixRilling
2019-03-11 17:38:29 -07:00
Gregg Van Hove
6bd4a29360 Merge branch 'jsdoc-validation' of https://github.com/FelixRilling/jasmine into FelixRilling-jsdoc-validation
- Merges #1667 from @FelixRilling
2019-03-11 17:37:43 -07:00
Gregg Van Hove
fd037f53a3 Merge branch 'typo-comments' of https://github.com/FelixRilling/jasmine into FelixRilling-typo-comments
- Merges #1665 from @FelixRilling
2019-03-11 17:34:44 -07:00
Gregg Van Hove
348242b712 Merge branch 'FelixRilling-typo-received'
- Merges #1664 from @FelixRilling
- Fixes #1663
2019-03-11 17:32:32 -07:00
Felix Rilling
b74e0abee1 Fixed flipped JSDoc. 2019-03-10 11:17:50 +01:00
Felix Rilling
e33b12b17c Fixed typos in test suite descriptions. 2019-03-10 11:07:40 +01:00
Felix Rilling
dde93ade18 Fixed typos in comments. 2019-03-10 11:04:33 +01:00
Felix Rilling
63f900287c Fixed typo "receieved" to "received", Adapted test. 2019-03-10 10:59:56 +01:00
Gregg Van Hove
239a615770 No longer run Node.js v4 on Travis
- Jasmine should still work in Node.js v4, but the jshint task isn't
  working correctly
2019-02-11 13:38:00 -08:00
Gregg Van Hove
92d5957a59 Attempt to skip jshint for node.js v4 2019-02-11 09:46:36 -08:00
Gregg Van Hove
4991f2a713 Merge branch 'print_global_error_type' of https://github.com/jbunton-atlassian/jasmine into jbunton-atlassian-print_global_error_type
- Merges #1632 from @jbunton-atlassian
2019-02-11 09:02:16 -08:00
Gregg Van Hove
0d6db64eb1 Merge branch 'onerror' of https://github.com/johnjbarton/jasmine into johnjbarton-onerror
- Merges #1644 from @jognjbarton
2019-01-30 17:38:27 -08:00
Gregg Van Hove
489fb79d6e fall back to older jshint for older node 2019-01-09 11:08:32 -08:00
Gregg Van Hove
eba8c775f3 update npm dependencies 2019-01-08 17:47:53 -08:00
johnjbarton
c36a005893 Support Error.stack in globalErrors.
See https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
2019-01-03 16:14:23 -08:00
Gregg Van Hove
37dfe50d99 Stop treating objects with a nodeType as if they are DOM Nodes
- Fixes #1638
2018-12-17 17:10:53 -08:00
Gregg Van Hove
c67a5b830c Fix 3.0 breaking changes list to include note about Spy identity 2018-12-11 17:56:17 -08:00
James Bunton
d803bd12a6 When catching a global error in Node.js, print the type of error 2018-12-11 08:32:45 +11:00
Gregg Van Hove
a621d05fa7 Merge branch 'Havunen-fix-to-equal-ie'
- Merges #1621 from @Havunen
- Fixes #1618
2018-12-03 17:45:06 -08:00
Sampo Kivistö
473f5cd359 Re-use attr variable 2018-11-04 10:44:54 +02:00
Sampo Kivistö
a81e9626df Fixes issue where PhantomJS 2 and IE 10 - 11 crashed when reporting SVG element equality 2018-11-04 10:31:33 +02:00
Gregg Van Hove
b3ccd4312c Bump version to 3.3.0 2018-10-25 09:47:09 -07:00
Gregg Van Hove
5524207658 Add api docs for .not and .withContext 2018-10-24 16:49:31 -07:00
Gregg Van Hove
1b5e0c0c10 Merge branch 'expect-context'
- Fixes #641
2018-10-24 16:32:28 -07:00
Gregg Van Hove
2d303a6e46 Merge common async/sync expectation stuff 2018-10-24 16:17:30 -07:00
Gregg Van Hove
1e47dcf2cc Pull async matchers out to their own functions
- Makes AsyncExpectation closer to Expectation
2018-10-23 16:02:31 -07:00
Gregg Van Hove
ba1e8f8008 Implement withContext for async expectations too 2018-10-22 16:42:36 -07:00
Gregg Van Hove
a91db0dfc2 more rejected to -> rejected with 2018-10-22 16:08:57 -07:00
Gregg Van Hove
1d130036f4 Merge branch 'master' into expect-context 2018-10-22 14:55:20 -07:00
Gregg Van Hove
e6a60a7bef Merge branch 'codymikol-toBeRejectedWith'
- Merges #1615 from @codymikol
- Closes #1600
- Fixes #1595
2018-10-22 11:20:03 -07:00
Gregg Van Hove
fe042fdf82 Use toBeRejectedWith instead of toBeRejectedTo 2018-10-22 11:18:56 -07:00
Gregg Van Hove
06854fe435 Merge branch 'toBeRejectedWith' of https://github.com/codymikol/jasmine into codymikol-toBeRejectedWith 2018-10-22 11:15:05 -07:00
Gregg Van Hove
7b9fc80b8f Merge branch 'tdurtschi-master'
- Merges #1616 from @tdurtshi
- Fixes #1614
2018-10-22 10:59:03 -07:00
Gregg Van Hove
3c47e71619 Also show tip for .not cases 2018-10-22 10:57:16 -07:00
Teagan Durtschi
7cbedcdda7 Add custom message for toBe() matcher when object equality check fails 2018-10-21 12:46:49 -04:00
Cody Mikol
3aa0115ae4 feat(toBeRejectedTo): implement toBeRejectedTo functionality
add functionality to determine whether a promise has been rejected to a
specific value via expectAsync

Fixes: #1595
2018-10-19 23:23:42 -04:00
Gregg Van Hove
440b6934aa Merge branch 'codymikol-assertAsync-promiseLike-support'
- Merges #1613 from @codymikol
- Fixes #1612
2018-10-19 16:24:30 -07:00
Cody Mikol
591bf1144b bugfix(assertAsync): add promiseLike support for angularJS promises
implement a promiseLike method so libraries using non-browser promise
implementations can still utilize assertAsync functionality.

Fixes: #1612
2018-10-18 21:28:32 -04:00
Gregg Van Hove
3ae61b14ad Merge branch 'm1010j-m1010j-add-status-marks-to-standalone'
- Merges #1610 from @m1010j
- Fixes #1596
2018-10-01 12:25:23 -07:00
Matthias Jenny
705a6508d4 Add status marks to standalone 2018-09-26 21:10:20 -04:00
Gregg Van Hove
306882f636 Merge branch 'nitobuendia-patch-1' 2018-09-25 17:29:10 -07:00
Gregg Van Hove
16fef04629 Merge branch 'patch-1' of https://github.com/nitobuendia/jasmine into nitobuendia-patch-1
- Merges #1601 from @nitobuendia
- Fixes #1594
2018-09-25 17:28:57 -07:00
Gregg Van Hove
d180c2026e Merge branch 'master' of https://github.com/Havunen/jasmine into Havunen-master
- Merges #1599 from @Havunen
2018-09-25 17:14:49 -07:00
Gregg Van Hove
92d0882a32 Introduce a configuration object to Env deprecating old single use functions
[finishes #159158038]
2018-09-25 17:08:41 -07:00
Nito Buendia
04679622b0 Add tests for formatting empty content errors. 2018-09-13 20:02:30 +08:00
Nito Buendia
b4cd1ec1ae Format according to style. 2018-09-13 19:48:53 +08:00
Nito Buendia
963b1cca22 Add tests for new unnamed errors. 2018-09-13 19:48:10 +08:00
Nito Buendia
d4f9b41eda Print error message when available
With the current set up, error message is only printed out when error name is available.
There are situations where the ErrorEvent object does not have a `name` property, but the message is still relevant.

For more details see #1594
2018-09-11 23:25:28 +08:00
Sampo Kivistö
1019b045cd Optimized clearTimeout cpu usage 2018-09-06 21:11:05 +03:00
Gregg Van Hove
6b9ae2db7e Merge pull request #1597 from limonte/patch-1
chore(package.json): http -> https
2018-09-04 12:27:05 -07:00
Limon Monte
33d8d2d3f4 chore(package.json): http -> https 2018-09-01 10:16:30 +03:00
Steve Gravrock
ac07c9ea97 Simplified ExpectationFilterChain#modifyFailureMessage 2018-06-09 12:34:30 -07:00
Steve Gravrock
0842a80c68 Cleanup 2018-06-09 12:26:34 -07:00
Steve Gravrock
8a01e1f26c .withContext() works with .not 2018-06-02 22:06:53 -07:00
Steve Gravrock
321f161ce5 Made ExpectationFilterChain immutable 2018-06-02 13:57:29 -07:00
Steve Gravrock
202a677637 ExpectationFilterChain WIP 2018-06-02 13:57:07 -07:00
Steve Gravrock
e2897ce619 Added expect().withContext() to provide additional information in failure messages 2018-05-14 21:18:55 -07:00
Steve Gravrock
282c436463 Implemented matcher negation as a filter 2018-05-13 23:01:55 -07:00
Steve Gravrock
5cc22740c9 Test the public-ish interface 2018-05-13 22:48:58 -07:00
Steve Gravrock
533bda5d24 Split Expectation#wrapCompare into several smaller functions 2018-05-13 22:48:58 -07:00
Steve Gravrock
9fe9569b24 Additional tests for negated matcher failure messages 2018-05-13 22:48:20 -07:00
231 changed files with 18994 additions and 5957 deletions

2
.gitattributes vendored Normal file
View File

@@ -0,0 +1,2 @@
* text=auto eol=lf
*.png -text

View File

@@ -17,7 +17,7 @@ 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/master # Sync local master with upstream 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
@@ -30,7 +30,6 @@ Once you've pushed a feature branch to your forked repo, you're ready to open a
### Directory Structure
* `/src` contains all of the source files
* `/src/console` - Node.js-specific files
* `/src/core` - generic source files
* `/src/html` - browser-specific files
* `/spec` contains all of the tests
@@ -47,37 +46,33 @@ The tests should always use `jasmineUnderTest` to refer to the objects and funct
### `boot.js`
__This is new for Jasmine 2.0.__
This file does all of the setup necessary for Jasmine to work. It loads all of the code, creates an `Env`, attaches the global functions, and builds the reporter. It also sets up the execution of the `Env` - for browsers this is in `window.onload`. While the default in `lib` is appropriate for browsers, projects may wish to customize this file.
For example, for Jasmine development there is a different `dev_boot.js` for Jasmine development that does more work.
### Compatibility
* Browser Minimum
* IE8
* Firefox 3.x
* Chrome ??
* Safari 5
Jasmine supports the following environments:
* Browsers
* IE10+
* Edge Latest
* Firefox Latest
* Chrome Latest
* Safari 8+
* Node.js
* 8
* 10
* 12
## Development
All source code belongs in `src/`. The `core/` directory contains the bulk of Jasmine's functionality. This code should remain browser- and environment-agnostic. If your feature or fix cannot be, as mentioned above, please degrade gracefully. Any code that should only be in a non-browser environment should live in `src/console/`. Any code that depends on a browser (specifically, it expects `window` to be the global or `document` is present) should live in `src/html/`.
All source code belongs in `src/`. The `core/` directory contains the bulk of Jasmine's functionality. This code should remain browser- and environment-agnostic. If your feature or fix cannot be, as mentioned above, please degrade gracefully. Any code that depends on a browser (specifically, it expects `window` to be the global or `document` is present) should live in `src/html/`.
### Install Dependencies
Jasmine Core relies on Ruby and Node.js.
To install the Ruby dependencies, you will need Ruby, Rubygems, and Bundler available. Then:
$ bundle
...will install all of the Ruby dependencies. If the ffi gem fails to build its native extensions, you may need to manually install some system dependencies. On Ubuntu:
$ apt-get install gcc ruby ruby-dev libxml2 libxml2-dev libxslt1-dev
...should get you to the point that `bundle` can install everything.
Jasmine Core relies on Node.js.
To install the Node dependencies, you will need Node.js, Npm, and [Grunt](http://gruntjs.com/), the [grunt-cli](https://github.com/gruntjs/grunt-cli) and ensure that `grunt` is on your path.
@@ -85,9 +80,9 @@ To install the Node dependencies, you will need Node.js, Npm, and [Grunt](http:/
...will install all of the node modules locally. Now run
$ grunt
$ npm test
...if you see that JSHint runs, your system is ready.
...you should see tests run and eslint checking formatting.
### How to write new Jasmine code
@@ -98,23 +93,17 @@ Or, How to make a successful pull request
* _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
* _Ensure the *entire* test suite is green_ in all the big browsers, Node, and JSHint - your contribution shouldn't break Jasmine for other users
* _Ensure the *entire* test suite is green_ in all the big browsers, Node, and ESLint - 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
Jasmine uses the [Jasmine Ruby gem](http://github.com/jasmine/jasmine-gem) to test itself in browser.
Jasmine uses some internal tooling to test itself in browser on Travis. This tooling _should_ work locally as well.
$ bundle exec rake jasmine
$ node ci.js
...and then visit `http://localhost:8888` to run specs.
Jasmine uses the [Jasmine NPM package](http://github.com/jasmine/jasmine-npm) to test itself in a Node.js/npm environment.
$ grunt execSpecsInNode
...and then the results will print to the console. All specs run except those that expect a browser (the specs in `spec/html` are ignored).
You can also set the `JASMINE_BROWSER` environment variable to specify which browser should be used.
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.
@@ -123,16 +112,16 @@ The easiest way to run the tests in **Internet Explorer** is to run a VM that ha
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 `bundle exec rake jasmine` running on your host machine, navigate to `http://10.0.2.2:8888` in IE.
1. With `npm run serve` running on your host machine, navigate to `http://10.0.2.2:8888` in IE.
## Before Committing or Submitting a Pull Request
1. Ensure all specs are green in browser *and* node
1. Ensure JSHint is green with `grunt jshint`
1. Build `jasmine.js` with `grunt buildDistribution` and run all specs again - this ensures that your changes self-test well
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 master
* 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 Travis for Continuous Integration. We only accept green pull requests.

1
.gitignore vendored
View File

@@ -12,6 +12,7 @@ site/
tags
Gemfile.lock
package-lock.json
yarn.lock
pkg/*
.sass-cache/*
src/html/.sass-cache/*

View File

@@ -1,17 +0,0 @@
{
"bitwise": true,
"curly": true,
"globals": {
"clearTimeout": false,
"console": false,
"getJasmineRequireObj": true,
"jasmineRequire": true,
"setTimeout": false
},
"immed": true,
"newcap": true,
"trailing": true,
"loopfunc": true,
"quotmark": "single",
"undef": true
}

View File

@@ -26,3 +26,4 @@ lib/jasmine-core/spec
lib/jasmine-core/version.rb
lib/jasmine-core/*.py
sauce_connect.log
ci.js

View File

@@ -1,68 +1,52 @@
language: ruby
cache: bundler
sudo: false
language: node_js
node_js: 10
rvm: 2.5
before_install:
- gem update --system
- gem install bundler
script: $TEST_COMMAND
env:
global:
- USE_SAUCE=true
- NOKOGIRI_USE_SYSTEM_LIBRARIES=true
- TEST_COMMAND="bash travis-core-script.sh"
- secure: WSPWhlnC4mWSnSPquX+m1/BCu5ch5NygkaHuM2Nea7lD8oS3XLX8QncZZAsQ4lnNfqoDDuBOizG0AESiqNvE4y6x5qvLLTS6q+ce255ZEMZ71TBdZgDEEvGMEjOPPsVXiXyTQOP1lwOPlrbZvaPgWV7e11KIBab6DfFcQpnvDgo=
- secure: SW7CJhZnwaNT749Gdnhvqb5rbXlAOsygUAzh9qhtyvbqXKkmJdBIEsO01YF6pbju1X2twE9JvWCOxeZju43NgQChJlPsGbjY2j3k/TdQeTAJesQe2K7ytwghunI30gjEovtRH0T3w1EmcKPH8yj5eBIcB2OYoJHx8KEC7e68q1g=
addons:
sauce_connect: true
matrix:
include:
- env:
- USE_SAUCE=false
- TEST_COMMAND="bash travis-node-script.sh v4"
- env:
- USE_SAUCE=false
- TEST_COMMAND="bash travis-node-script.sh v8"
- env:
- USE_SAUCE=false
- TEST_COMMAND="bash travis-node-script.sh v9"
- env:
- JASMINE_BROWSER="firefox"
- SAUCE_OS="Linux"
- SAUCE_BROWSER_VERSION=''
- env:
- JASMINE_BROWSER="safari"
- SAUCE_OS="OS X 10.12"
- SAUCE_BROWSER_VERSION=10
- env:
- JASMINE_BROWSER="safari"
- SAUCE_OS="OS X 10.11"
- SAUCE_BROWSER_VERSION=9
- env:
- JASMINE_BROWSER="safari"
- SAUCE_OS="OS X 10.10"
- SAUCE_BROWSER_VERSION=8
- env:
- JASMINE_BROWSER="MicrosoftEdge"
- SAUCE_OS="Windows 10"
- SAUCE_BROWSER_VERSION="15"
- env:
- JASMINE_BROWSER="internet explorer"
- SAUCE_OS="Windows 8.1"
- SAUCE_BROWSER_VERSION=11
- env:
- JASMINE_BROWSER="internet explorer"
- SAUCE_OS="Windows 8"
- SAUCE_BROWSER_VERSION=10
- env:
- JASMINE_BROWSER="chrome"
- SAUCE_OS="Linux"
- SAUCE_BROWSER_VERSION=''
- env:
- JASMINE_BROWSER="phantomjs"
- USE_SAUCE=false
- node_js: "10"
env: JASMINE_LONG_PROPERTY_TESTS="y" TEST_COMMAND="npm test"
- node_js: "12"
env: TEST_COMMAND="npm test"
- node_js: "8"
env: TEST_COMMAND="npm test"
- env: JASMINE_BROWSER="internet explorer" SAUCE_BROWSER_VERSION=11 SAUCE_OS="Windows 8.1"
if: type != pull_request
addons:
sauce_connect: true
- env: JASMINE_BROWSER="internet explorer" SAUCE_BROWSER_VERSION=10 SAUCE_OS="Windows 8"
if: type != pull_request
addons:
sauce_connect: true
- env: JASMINE_BROWSER="firefox" SAUCE_BROWSER_VERSION='' SAUCE_OS="Windows 10"
if: type != pull_request
addons:
sauce_connect: true
- env: JASMINE_BROWSER="firefox" SAUCE_BROWSER_VERSION='68' SAUCE_OS="Windows 10"
if: type != pull_request
addons:
sauce_connect: true
- env: JASMINE_BROWSER="chrome" SAUCE_BROWSER_VERSION='' SAUCE_OS="Windows 10"
if: type != pull_request
addons:
sauce_connect: true
- env: JASMINE_BROWSER="safari" SAUCE_BROWSER_VERSION="13" SAUCE_OS="OS X 10.13"
if: type != pull_request
addons:
sauce_connect: true
- env: JASMINE_BROWSER="safari" SAUCE_BROWSER_VERSION="8" SAUCE_OS="OS X 10.10"
if: type != pull_request
addons:
sauce_connect: true
- env: JASMINE_BROWSER="MicrosoftEdge" SAUCE_BROWSER_VERSION="" SAUCE_OS="Windows 10"
if: type != pull_request
addons:
sauce_connect: true

View File

@@ -1,9 +1,2 @@
source 'https://rubygems.org'
gem "jasmine", :git => 'https://github.com/jasmine/jasmine-gem.git'
# gem "jasmine", path: "../jasmine-gem"
gemspec
gem "jasmine_selenium_runner", :github => 'jasmine/jasmine_selenium_runner'
gem "anchorman"

View File

@@ -4,17 +4,17 @@ module.exports = function(grunt) {
grunt.initConfig({
pkg: pkg,
jshint: require('./grunt/config/jshint.js'),
concat: require('./grunt/config/concat.js'),
compass: require('./grunt/config/compass.js'),
compress: require('./grunt/config/compress.js')
sass: require('./grunt/config/sass.js'),
compress: require('./grunt/config/compress.js'),
cssUrlEmbed: require('./grunt/config/cssUrlEmbed.js')
});
require('load-grunt-tasks')(grunt);
grunt.loadTasks('grunt/tasks');
grunt.registerTask('default', ['jshint:all']);
grunt.registerTask('default', ['sass:dist', "cssUrlEmbed"]);
var version = require('./grunt/tasks/version.js');
@@ -25,11 +25,9 @@ module.exports = function(grunt) {
grunt.registerTask('buildDistribution',
'Builds and lints jasmine.js, jasmine-html.js, jasmine.css',
[
'compass',
'jshint:beforeConcat',
'concat',
'jshint:afterConcat',
'build:copyVersionToGem'
'sass:dist',
"cssUrlEmbed",
'concat'
]
);

View File

@@ -1,4 +1,4 @@
Copyright (c) 2008-2017 Pivotal Labs
Copyright (c) 2008-2019 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

View File

@@ -1,6 +1,6 @@
<a name="README">[<img src="https://rawgithub.com/jasmine/jasmine/master/images/jasmine-horizontal.svg" width="400px" />](http://jasmine.github.io)</a>
<a name="README">[<img src="https://rawgithub.com/jasmine/jasmine/main/images/jasmine-horizontal.svg" width="400px" />](http://jasmine.github.io)</a>
[![Build Status](https://travis-ci.org/jasmine/jasmine.svg?branch=master)](https://travis-ci.org/jasmine/jasmine)
[![Build Status](https://travis-ci.org/jasmine/jasmine.svg?branch=main)](https://travis-ci.org/jasmine/jasmine)
[![Open Source Helpers](https://www.codetriage.com/jasmine/jasmine/badges/users.svg)](https://www.codetriage.com/jasmine/jasmine)
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjasmine%2Fjasmine.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjasmine%2Fjasmine?ref=badge_shield)
@@ -9,35 +9,35 @@
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.
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)
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 2.x? Check out the [3.0 release notes](https://github.com/jasmine/jasmine/blob/v3.0.0/release_notes/3.0.md) for a list of what's new (including breaking changes).
## Contributing
Please read the [contributors' guide](https://github.com/jasmine/jasmine/blob/master/.github/CONTRIBUTING.md)
Please read the [contributors' guide](https://github.com/jasmine/jasmine/blob/main/.github/CONTRIBUTING.md).
## Installation
For the Jasmine NPM module:<br>
[https://github.com/jasmine/jasmine-npm](https://github.com/jasmine/jasmine-npm)
[https://github.com/jasmine/jasmine-npm](https://github.com/jasmine/jasmine-npm).
For the Jasmine Ruby Gem:<br>
[https://github.com/jasmine/jasmine-gem](https://github.com/jasmine/jasmine-gem)
[https://github.com/jasmine/jasmine-gem](https://github.com/jasmine/jasmine-gem).
For the Jasmine Python Egg:<br>
[https://github.com/jasmine/jasmine-py](https://github.com/jasmine/jasmine-py)
[https://github.com/jasmine/jasmine-py](https://github.com/jasmine/jasmine-py).
For the Jasmine headless browser gulp plugin:<br>
[https://github.com/jasmine/gulp-jasmine-browser](https://github.com/jasmine/gulp-jasmine-browser)
[https://github.com/jasmine/gulp-jasmine-browser](https://github.com/jasmine/gulp-jasmine-browser).
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)
* Create a Jasmine directory in your project - `mkdir my-project/jasmine`
* Move the dist to your project directory - `mv jasmine/dist/jasmine-standalone-{#.#.#}.zip my-project/jasmine`
* Change directory - `cd my-project/jasmine`
* Unzip the dist - `unzip jasmine-standalone-{#.#.#}.zip`
* Download the standalone distribution for your desired release from the [releases page](https://github.com/jasmine/jasmine/releases).
* Create a Jasmine directory in your project. - `mkdir my-project/jasmine`
* Move the dist to your project directory. - `mv jasmine/dist/jasmine-standalone-{#.#.#}.zip my-project/jasmine`
* Change directory. - `cd my-project/jasmine`
* Unzip the dist. - `unzip jasmine-standalone-{#.#.#}.zip`
Add the following to your HTML file:
@@ -52,15 +52,27 @@ Add the following to your HTML file:
## Supported environments
Jasmine tests itself across many browsers (Safari, Chrome, Firefox, PhantomJS, Microsoft Edge, and new Internet Explorer) as well as nodejs. To see the exact version tests are run against look at our [.travis.yml](https://github.com/jasmine/jasmine/blob/master/.travis.yml)
Jasmine tests itself across many browsers (Safari, Chrome, Firefox, Microsoft Edge, and Internet Explorer) as well as nodejs.
| Environment | Supported versions |
|-------------------|--------------------|
| Node | 8, 10, 12 |
| Safari | 8-13 |
| Chrome | Evergreen |
| Firefox | Evergreen, 68 |
| 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.
## Support
* Search past discussions: [http://groups.google.com/group/jasmine-js](http://groups.google.com/group/jasmine-js)
* Send an email to the list: [jasmine-js@googlegroups.com](mailto:jasmine-js@googlegroups.com)
* View the project backlog at Pivotal Tracker: [http://www.pivotaltracker.com/projects/10606](http://www.pivotaltracker.com/projects/10606)
* Follow us on Twitter: [@JasmineBDD](http://twitter.com/JasmineBDD)
* Search past discussions: [http://groups.google.com/group/jasmine-js](http://groups.google.com/group/jasmine-js).
* Send an email to the list: [jasmine-js@googlegroups.com](mailto:jasmine-js@googlegroups.com).
* View the project backlog at Pivotal Tracker: [http://www.pivotaltracker.com/projects/10606](http://www.pivotaltracker.com/projects/10606).
* Follow us on Twitter: [@JasmineBDD](http://twitter.com/JasmineBDD).
## Maintainers
@@ -79,4 +91,4 @@ Copyright (c) 2008-2018 Pivotal Labs. This software is licensed under the MIT Li
## License
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjasmine%2Fjasmine.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjasmine%2Fjasmine?ref=badge_large)
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjasmine%2Fjasmine.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjasmine%2Fjasmine?ref=badge_large)

View File

@@ -7,7 +7,7 @@ Follow the instructions in `CONTRIBUTING.md` during development.
### Git Rules
Please attempt to keep commits to `master` small, but cohesive. If a feature is contained in a bunch of small commits (e.g., it has several wip commits or small work), please squash them when pushing to `master`.
Please attempt to keep commits to `main` small, but cohesive. If a feature is contained in a bunch of small commits (e.g., it has several wip commits or small work), please squash them when pushing to `main`.
### Version

View File

@@ -1,18 +1,2 @@
require "bundler"
Bundler::GemHelper.install_tasks
require "json"
require "jasmine"
unless ENV["JASMINE_BROWSER"] == 'phantomjs'
require "jasmine_selenium_runner"
end
load "jasmine/tasks/jasmine.rake"
namespace :jasmine do
task :set_env do
ENV['JASMINE_CONFIG_PATH'] ||= 'spec/support/jasmine.yml'
end
end
task "jasmine:configure" => "jasmine:set_env"
task :default => "jasmine:ci"

View File

@@ -1,11 +0,0 @@
module.exports = {
jasmine: {
options: {
cssDir: 'lib/jasmine-core/',
sassDir: 'src/html',
outputStyle: 'compact',
noLineComments: true,
bundleExec: true
}
}
};

View File

@@ -0,0 +1,7 @@
module.exports = {
encodeWithBaseDir: {
files: {
"lib/jasmine-core/jasmine.css": ["lib/jasmine-core/jasmine.css"]
}
}
};

View File

@@ -1,11 +0,0 @@
module.exports = {
beforeConcat: ['src/**/*.js'],
afterConcat: [
'lib/jasmine-core/jasmine-html.js',
'lib/jasmine-core/jasmine.js'
],
options: {
jshintrc: '.jshintrc'
},
all: ['src/**/*.js']
};

14
grunt/config/sass.js Normal file
View File

@@ -0,0 +1,14 @@
const sass = require('node-sass');
module.exports = {
options: {
implementation: sass,
outputStyle: 'compact',
sourceComments: false
},
dist: {
files: {
"lib/jasmine-core/jasmine.css": "src/html/jasmine.scss"
}
}
};

View File

@@ -11,13 +11,9 @@ Gem::Specification.new do |s|
s.description = %q{Test your JavaScript without any framework dependencies, in any environment, and with a nice descriptive syntax.}
s.email = %q{jasmine-js@googlegroups.com}
s.homepage = "http://jasmine.github.io"
s.rubyforge_project = "jasmine-core"
s.license = "MIT"
s.files = Dir.glob("./lib/**/*")
s.require_paths = ["lib"]
s.add_development_dependency "rake"
s.add_development_dependency "sauce-connect"
s.add_development_dependency "compass"
s.add_development_dependency "jasmine_selenium_runner", ">= 0.2.0"
end

View File

@@ -1,5 +1,5 @@
/*
Copyright (c) 2008-2018 Pivotal Labs
Copyright (c) 2008-2020 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -31,13 +31,16 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function() {
var jasmineRequire = window.jasmineRequire || require('./jasmine.js');
/**
* ## Require &amp; Instantiate
*
* Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
*/
window.jasmine = jasmineRequire.core(jasmineRequire);
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.
@@ -59,7 +62,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/**
* 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(window, jasmineInterface);
extend(global, jasmineInterface);
/**
* ## Runner Parameters
@@ -73,24 +76,21 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
var filterSpecs = !!queryString.getParam("spec");
var stoppingOnSpecFailure = queryString.getParam("failFast");
env.stopOnSpecFailure(stoppingOnSpecFailure);
var throwingExpectationFailures = queryString.getParam("throwFailures");
env.throwOnExpectationFailure(throwingExpectationFailures);
var hideDisabled = queryString.getParam("hideDisabled");
env.hideDisabled(hideDisabled);
var config = {
failFast: queryString.getParam("failFast"),
oneFailurePerSpec: queryString.getParam("oneFailurePerSpec"),
hideDisabled: queryString.getParam("hideDisabled")
};
var random = queryString.getParam("random");
if (random !== undefined && random !== "") {
env.randomizeTests(random);
config.random = random;
}
var seed = queryString.getParam("seed");
if (seed) {
env.seed(seed);
config.seed = seed;
}
/**
@@ -121,10 +121,12 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
filterString: function() { return queryString.getParam("spec"); }
});
env.specFilter = function(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.
*/

View File

@@ -9,13 +9,16 @@
*/
(function() {
var jasmineRequire = window.jasmineRequire || require('./jasmine.js');
/**
* ## Require &amp; Instantiate
*
* Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
*/
window.jasmine = jasmineRequire.core(jasmineRequire);
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.
@@ -37,7 +40,7 @@
/**
* 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(window, jasmineInterface);
extend(global, jasmineInterface);
/**
* ## Runner Parameters
@@ -51,24 +54,21 @@
var filterSpecs = !!queryString.getParam("spec");
var stoppingOnSpecFailure = queryString.getParam("failFast");
env.stopOnSpecFailure(stoppingOnSpecFailure);
var throwingExpectationFailures = queryString.getParam("throwFailures");
env.throwOnExpectationFailure(throwingExpectationFailures);
var hideDisabled = queryString.getParam("hideDisabled");
env.hideDisabled(hideDisabled);
var config = {
failFast: queryString.getParam("failFast"),
oneFailurePerSpec: queryString.getParam("oneFailurePerSpec"),
hideDisabled: queryString.getParam("hideDisabled")
};
var random = queryString.getParam("random");
if (random !== undefined && random !== "") {
env.randomizeTests(random);
config.random = random;
}
var seed = queryString.getParam("seed");
if (seed) {
env.seed(seed);
config.seed = seed;
}
/**
@@ -99,10 +99,12 @@
filterString: function() { return queryString.getParam("spec"); }
});
env.specFilter = function(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.
*/

View File

@@ -19,4 +19,4 @@ Player.prototype.resume = function() {
Player.prototype.makeFavorite = function() {
this.currentlyPlayingSong.persistFavoriteStatus(true);
};
};

View File

@@ -4,4 +4,4 @@ function Song() {
Song.prototype.persistFavoriteStatus = function(value) {
// something complicated
throw new Error("not yet implemented");
};
};

View File

@@ -1,5 +1,5 @@
/*
Copyright (c) 2008-2018 Pivotal Labs
Copyright (c) 2008-2020 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -20,6 +20,8 @@ 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.
*/
var jasmineRequire = window.jasmineRequire || require('./jasmine.js');
jasmineRequire.html = function(j$) {
j$.ResultsNode = jasmineRequire.ResultsNode();
j$.HtmlReporter = jasmineRequire.HtmlReporter(j$);
@@ -28,12 +30,6 @@ jasmineRequire.html = function(j$) {
};
jasmineRequire.HtmlReporter = function(j$) {
var noopTimer = {
start: function() {},
elapsed: function() { return 0; }
};
function ResultsStateBuilder() {
this.topResults = new j$.ResultsNode({}, '', null);
this.currentParent = this.topResults;
@@ -58,8 +54,7 @@ jasmineRequire.HtmlReporter = function(j$) {
}
};
ResultsStateBuilder.prototype.specStarted = function(result) {
};
ResultsStateBuilder.prototype.specStarted = function(result) {};
ResultsStateBuilder.prototype.specDone = function(result) {
this.currentParent.addChild(result, 'spec');
@@ -77,32 +72,42 @@ jasmineRequire.HtmlReporter = function(j$) {
}
};
function HtmlReporter(options) {
var env = options.env || {},
var config = function() {
return (options.env && options.env.configuration()) || {};
},
getContainer = options.getContainer,
createElement = options.createElement,
createTextNode = options.createTextNode,
navigateWithNewParam = options.navigateWithNewParam || function() {},
addToExistingQueryString = options.addToExistingQueryString || defaultQueryString,
addToExistingQueryString =
options.addToExistingQueryString || defaultQueryString,
filterSpecs = options.filterSpecs,
timer = options.timer || noopTimer,
htmlReporterMain,
symbols,
deprecationWarnings = [];
this.initialize = function() {
clearPrior();
htmlReporterMain = createDom('div', {className: 'jasmine_html-reporter'},
createDom('div', {className: 'jasmine-banner'},
createDom('a', {className: 'jasmine-title', href: 'http://jasmine.github.io/', target: '_blank'}),
createDom('span', {className: 'jasmine-version'}, j$.version)
htmlReporterMain = createDom(
'div',
{ className: 'jasmine_html-reporter' },
createDom(
'div',
{ className: 'jasmine-banner' },
createDom('a', {
className: 'jasmine-title',
href: 'http://jasmine.github.io/',
target: '_blank'
}),
createDom('span', { className: 'jasmine-version' }, j$.version)
),
createDom('ul', {className: 'jasmine-symbol-summary'}),
createDom('div', {className: 'jasmine-alert'}),
createDom('div', {className: 'jasmine-results'},
createDom('div', {className: 'jasmine-failures'})
createDom('ul', { className: 'jasmine-symbol-summary' }),
createDom('div', { className: 'jasmine-alert' }),
createDom(
'div',
{ className: 'jasmine-results' },
createDom('div', { className: 'jasmine-failures' })
)
);
getContainer().appendChild(htmlReporterMain);
@@ -111,10 +116,9 @@ jasmineRequire.HtmlReporter = function(j$) {
var totalSpecsDefined;
this.jasmineStarted = function(options) {
totalSpecsDefined = options.totalSpecsDefined || 0;
timer.start();
};
var summary = createDom('div', {className: 'jasmine-summary'});
var summary = createDom('div', { className: 'jasmine-summary' });
var stateBuilder = new ResultsStateBuilder();
@@ -139,20 +143,26 @@ jasmineRequire.HtmlReporter = function(j$) {
this.specDone = function(result) {
stateBuilder.specDone(result);
if(noExpectations(result) && typeof console !== 'undefined' && typeof console.error !== 'undefined') {
console.error('Spec \'' + result.fullName + '\' has no expectations.');
if (noExpectations(result)) {
var noSpecMsg = "Spec '" + result.fullName + "' has no expectations.";
if (result.status === 'failed') {
console.error(noSpecMsg);
} else {
console.warn(noSpecMsg);
}
}
if (!symbols){
if (!symbols) {
symbols = find('.jasmine-symbol-summary');
}
symbols.appendChild(createDom('li', {
symbols.appendChild(
createDom('li', {
className: this.displaySpecInCorrectFormat(result),
id: 'spec_' + result.id,
title: result.fullName
}
));
})
);
if (result.status === 'failed') {
failures.push(failureDom(result));
@@ -162,14 +172,18 @@ jasmineRequire.HtmlReporter = function(j$) {
};
this.displaySpecInCorrectFormat = function(result) {
return noExpectations(result) ? 'jasmine-empty' : this.resultStatus(result.status);
return noExpectations(result) && result.status === 'passed'
? 'jasmine-empty'
: this.resultStatus(result.status);
};
this.resultStatus = function(status) {
if(status === 'excluded') {
return env.hidingDisabled() ? 'jasmine-excluded-no-display' : 'jasmine-excluded';
}
return 'jasmine-' + status;
if (status === 'excluded') {
return config().hideDisabled
? 'jasmine-excluded-no-display'
: 'jasmine-excluded';
}
return 'jasmine-' + status;
};
this.jasmineDone = function(doneResult) {
@@ -177,16 +191,33 @@ jasmineRequire.HtmlReporter = function(j$) {
var alert = find('.jasmine-alert');
var order = doneResult && doneResult.order;
var i;
alert.appendChild(createDom('span', {className: 'jasmine-duration'}, 'finished in ' + timer.elapsed() / 1000 + 's'));
alert.appendChild(
createDom(
'span',
{ className: 'jasmine-duration' },
'finished in ' + doneResult.totalTime / 1000 + 's'
)
);
banner.appendChild(optionsMenu(env));
banner.appendChild(optionsMenu(config()));
if (stateBuilder.specsExecuted < totalSpecsDefined) {
var skippedMessage = 'Ran ' + stateBuilder.specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all';
var skippedMessage =
'Ran ' +
stateBuilder.specsExecuted +
' of ' +
totalSpecsDefined +
' specs - run all';
var skippedLink = addToExistingQueryString('spec', '');
alert.appendChild(
createDom('span', {className: 'jasmine-bar jasmine-skipped'},
createDom('a', {href: skippedLink, title: 'Run all specs'}, skippedMessage)
createDom(
'span',
{ className: 'jasmine-bar jasmine-skipped' },
createDom(
'a',
{ href: skippedLink, title: 'Run all specs' },
skippedMessage
)
)
);
}
@@ -196,34 +227,66 @@ jasmineRequire.HtmlReporter = function(j$) {
var failed = stateBuilder.failureCount + globalFailures.length > 0;
if (totalSpecsDefined > 0 || failed) {
statusBarMessage += pluralize('spec', stateBuilder.specsExecuted) + ', ' + pluralize('failure', stateBuilder.failureCount);
if (stateBuilder.pendingSpecCount) { statusBarMessage += ', ' + pluralize('pending spec', stateBuilder.pendingSpecCount); }
statusBarMessage +=
pluralize('spec', stateBuilder.specsExecuted) +
', ' +
pluralize('failure', stateBuilder.failureCount);
if (stateBuilder.pendingSpecCount) {
statusBarMessage +=
', ' + pluralize('pending spec', stateBuilder.pendingSpecCount);
}
}
if (doneResult.overallStatus === 'passed') {
statusBarClassName += ' jasmine-passed ';
} else if (doneResult.overallStatus === 'incomplete') {
statusBarClassName += ' jasmine-incomplete ';
statusBarMessage = 'Incomplete: ' + doneResult.incompleteReason + ', ' + statusBarMessage;
statusBarMessage =
'Incomplete: ' +
doneResult.incompleteReason +
', ' +
statusBarMessage;
} else {
statusBarClassName += ' jasmine-failed ';
}
var seedBar;
if (order && order.random) {
seedBar = createDom('span', {className: 'jasmine-seed-bar'},
seedBar = createDom(
'span',
{ className: 'jasmine-seed-bar' },
', randomized with seed ',
createDom('a', {title: 'randomized with seed ' + order.seed, href: seedHref(order.seed)}, order.seed)
createDom(
'a',
{
title: 'randomized with seed ' + order.seed,
href: seedHref(order.seed)
},
order.seed
)
);
}
alert.appendChild(createDom('span', {className: statusBarClassName}, statusBarMessage, seedBar));
alert.appendChild(
createDom(
'span',
{ className: statusBarClassName },
statusBarMessage,
seedBar
)
);
var errorBarClassName = 'jasmine-bar jasmine-errored';
var afterAllMessagePrefix = 'AfterAll ';
for(i = 0; i < globalFailures.length; i++) {
alert.appendChild(createDom('span', {className: errorBarClassName}, globalFailureMessage(globalFailures[i])));
for (i = 0; i < globalFailures.length; i++) {
alert.appendChild(
createDom(
'span',
{ className: errorBarClassName },
globalFailureMessage(globalFailures[i])
)
);
}
function globalFailureMessage(failure) {
@@ -231,7 +294,9 @@ jasmineRequire.HtmlReporter = function(j$) {
var prefix = 'Error during loading: ' + failure.message;
if (failure.filename) {
return prefix + ' in ' + failure.filename + ' line ' + failure.lineno;
return (
prefix + ' in ' + failure.filename + ' line ' + failure.lineno
);
} else {
return prefix;
}
@@ -243,9 +308,15 @@ jasmineRequire.HtmlReporter = function(j$) {
addDeprecationWarnings(doneResult);
var warningBarClassName = 'jasmine-bar jasmine-warning';
for(i = 0; i < deprecationWarnings.length; i++) {
for (i = 0; i < deprecationWarnings.length; i++) {
var warning = deprecationWarnings[i];
alert.appendChild(createDom('span', {className: warningBarClassName}, 'DEPRECATION: ' + warning));
alert.appendChild(
createDom(
'span',
{ className: warningBarClassName },
'DEPRECATION: ' + warning
)
);
}
var results = find('.jasmine-results');
@@ -255,19 +326,37 @@ jasmineRequire.HtmlReporter = function(j$) {
if (failures.length) {
alert.appendChild(
createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-spec-list'},
createDom(
'span',
{ className: 'jasmine-menu jasmine-bar jasmine-spec-list' },
createDom('span', {}, 'Spec List | '),
createDom('a', {className: 'jasmine-failures-menu', href: '#'}, 'Failures')));
createDom(
'a',
{ className: 'jasmine-failures-menu', href: '#' },
'Failures'
)
)
);
alert.appendChild(
createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-failure-list'},
createDom('a', {className: 'jasmine-spec-list-menu', href: '#'}, 'Spec List'),
createDom('span', {}, ' | Failures ')));
createDom(
'span',
{ className: 'jasmine-menu jasmine-bar jasmine-failure-list' },
createDom(
'a',
{ className: 'jasmine-spec-list-menu', href: '#' },
'Spec List'
),
createDom('span', {}, ' | Failures ')
)
);
find('.jasmine-failures-menu').onclick = function() {
setMenuModeTo('jasmine-failure-list');
return false;
};
find('.jasmine-spec-list-menu').onclick = function() {
setMenuModeTo('jasmine-spec-list');
return false;
};
setMenuModeTo('jasmine-failure-list');
@@ -282,17 +371,40 @@ jasmineRequire.HtmlReporter = function(j$) {
return this;
function failureDom(result) {
var failure =
createDom('div', {className: 'jasmine-spec-detail jasmine-failed'},
failureDescription(result, stateBuilder.currentParent),
createDom('div', {className: 'jasmine-messages'})
);
var failure = createDom(
'div',
{ className: 'jasmine-spec-detail jasmine-failed' },
failureDescription(result, stateBuilder.currentParent),
createDom('div', { className: 'jasmine-messages' })
);
var messages = failure.childNodes[1];
for (var i = 0; i < result.failedExpectations.length; i++) {
var expectation = result.failedExpectations[i];
messages.appendChild(createDom('div', {className: 'jasmine-result-message'}, expectation.message));
messages.appendChild(createDom('div', {className: 'jasmine-stack-trace'}, expectation.stack));
messages.appendChild(
createDom(
'div',
{ className: 'jasmine-result-message' },
expectation.message
)
);
messages.appendChild(
createDom(
'div',
{ className: 'jasmine-stack-trace' },
expectation.stack
)
);
}
if (result.failedExpectations.length === 0) {
messages.appendChild(
createDom(
'div',
{ className: 'jasmine-result-message' },
'Spec has no expectations'
)
);
}
return failure;
@@ -306,9 +418,20 @@ jasmineRequire.HtmlReporter = function(j$) {
continue;
}
if (resultNode.type === 'suite') {
var suiteListNode = createDom('ul', {className: 'jasmine-suite', id: 'suite-' + resultNode.result.id},
createDom('li', {className: 'jasmine-suite-detail jasmine-' + resultNode.result.status},
createDom('a', {href: specHref(resultNode.result)}, resultNode.result.description)
var suiteListNode = createDom(
'ul',
{ className: 'jasmine-suite', id: 'suite-' + resultNode.result.id },
createDom(
'li',
{
className:
'jasmine-suite-detail jasmine-' + resultNode.result.status
},
createDom(
'a',
{ href: specHref(resultNode.result) },
resultNode.result.description
)
)
);
@@ -317,85 +440,133 @@ jasmineRequire.HtmlReporter = function(j$) {
}
if (resultNode.type === 'spec') {
if (domParent.getAttribute('class') !== 'jasmine-specs') {
specListNode = createDom('ul', {className: 'jasmine-specs'});
specListNode = createDom('ul', { className: 'jasmine-specs' });
domParent.appendChild(specListNode);
}
var specDescription = resultNode.result.description;
if(noExpectations(resultNode.result)) {
if (noExpectations(resultNode.result)) {
specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription;
}
if(resultNode.result.status === 'pending' && resultNode.result.pendingReason !== '') {
specDescription = specDescription + ' PENDING WITH MESSAGE: ' + resultNode.result.pendingReason;
if (
resultNode.result.status === 'pending' &&
resultNode.result.pendingReason !== ''
) {
specDescription =
specDescription +
' PENDING WITH MESSAGE: ' +
resultNode.result.pendingReason;
}
specListNode.appendChild(
createDom('li', {
createDom(
'li',
{
className: 'jasmine-' + resultNode.result.status,
id: 'spec-' + resultNode.result.id
},
createDom('a', {href: specHref(resultNode.result)}, specDescription)
createDom(
'a',
{ href: specHref(resultNode.result) },
specDescription
)
)
);
}
}
}
function optionsMenu(env) {
var optionsMenuDom = createDom('div', { className: 'jasmine-run-options' },
function optionsMenu(config) {
var optionsMenuDom = createDom(
'div',
{ className: 'jasmine-run-options' },
createDom('span', { className: 'jasmine-trigger' }, 'Options'),
createDom('div', { className: 'jasmine-payload' },
createDom('div', { className: 'jasmine-stop-on-failure' },
createDom(
'div',
{ className: 'jasmine-payload' },
createDom(
'div',
{ className: 'jasmine-stop-on-failure' },
createDom('input', {
className: 'jasmine-fail-fast',
id: 'jasmine-fail-fast',
type: 'checkbox'
}),
createDom('label', { className: 'jasmine-label', 'for': 'jasmine-fail-fast' }, 'stop execution on spec failure')),
createDom('div', { className: 'jasmine-throw-failures' },
createDom(
'label',
{ className: 'jasmine-label', for: 'jasmine-fail-fast' },
'stop execution on spec failure'
)
),
createDom(
'div',
{ className: 'jasmine-throw-failures' },
createDom('input', {
className: 'jasmine-throw',
id: 'jasmine-throw-failures',
type: 'checkbox'
}),
createDom('label', { className: 'jasmine-label', 'for': 'jasmine-throw-failures' }, 'stop spec on expectation failure')),
createDom('div', { className: 'jasmine-random-order' },
createDom(
'label',
{ className: 'jasmine-label', for: 'jasmine-throw-failures' },
'stop spec on expectation failure'
)
),
createDom(
'div',
{ className: 'jasmine-random-order' },
createDom('input', {
className: 'jasmine-random',
id: 'jasmine-random-order',
type: 'checkbox'
}),
createDom('label', { className: 'jasmine-label', 'for': 'jasmine-random-order' }, 'run tests in random order')),
createDom('div', { className: 'jasmine-hide-disabled' },
createDom(
'label',
{ className: 'jasmine-label', for: 'jasmine-random-order' },
'run tests in random order'
)
),
createDom(
'div',
{ className: 'jasmine-hide-disabled' },
createDom('input', {
className: 'jasmine-disabled',
id: 'jasmine-hide-disabled',
type: 'checkbox'
}),
createDom('label', { className: 'jasmine-label', 'for': 'jasmine-hide-disabled' }, 'hide disabled tests'))
createDom(
'label',
{ className: 'jasmine-label', for: 'jasmine-hide-disabled' },
'hide disabled tests'
)
)
)
);
var failFastCheckbox = optionsMenuDom.querySelector('#jasmine-fail-fast');
failFastCheckbox.checked = env.stoppingOnSpecFailure();
failFastCheckbox.checked = config.failFast;
failFastCheckbox.onclick = function() {
navigateWithNewParam('failFast', !env.stoppingOnSpecFailure());
navigateWithNewParam('failFast', !config.failFast);
};
var throwCheckbox = optionsMenuDom.querySelector('#jasmine-throw-failures');
throwCheckbox.checked = env.throwingExpectationFailures();
var throwCheckbox = optionsMenuDom.querySelector(
'#jasmine-throw-failures'
);
throwCheckbox.checked = config.oneFailurePerSpec;
throwCheckbox.onclick = function() {
navigateWithNewParam('throwFailures', !env.throwingExpectationFailures());
navigateWithNewParam('throwFailures', !config.oneFailurePerSpec);
};
var randomCheckbox = optionsMenuDom.querySelector('#jasmine-random-order');
randomCheckbox.checked = env.randomTests();
var randomCheckbox = optionsMenuDom.querySelector(
'#jasmine-random-order'
);
randomCheckbox.checked = config.random;
randomCheckbox.onclick = function() {
navigateWithNewParam('random', !env.randomTests());
navigateWithNewParam('random', !config.random);
};
var hideDisabled = optionsMenuDom.querySelector('#jasmine-hide-disabled');
hideDisabled.checked = env.hidingDisabled();
hideDisabled.checked = config.hideDisabled;
hideDisabled.onclick = function() {
navigateWithNewParam('hideDisabled', !env.hidingDisabled());
navigateWithNewParam('hideDisabled', !config.hideDisabled);
};
var optionsTrigger = optionsMenuDom.querySelector('.jasmine-trigger'),
@@ -404,7 +575,10 @@ jasmineRequire.HtmlReporter = function(j$) {
optionsTrigger.onclick = function() {
if (isOpen.test(optionsPayload.className)) {
optionsPayload.className = optionsPayload.className.replace(isOpen, '');
optionsPayload.className = optionsPayload.className.replace(
isOpen,
''
);
} else {
optionsPayload.className += ' jasmine-open';
}
@@ -414,14 +588,24 @@ jasmineRequire.HtmlReporter = function(j$) {
}
function failureDescription(result, suite) {
var wrapper = createDom('div', {className: 'jasmine-description'},
createDom('a', {title: result.description, href: specHref(result)}, result.description)
var wrapper = createDom(
'div',
{ className: 'jasmine-description' },
createDom(
'a',
{ title: result.description, href: specHref(result) },
result.description
)
);
var suiteLink;
while (suite && suite.parent) {
wrapper.insertBefore(createTextNode(' > '), wrapper.firstChild);
suiteLink = createDom('a', {href: suiteHref(suite)}, suite.result.description);
suiteLink = createDom(
'a',
{ href: suiteHref(suite) },
suite.result.description
);
wrapper.insertBefore(suiteLink, wrapper.firstChild);
suite = suite.parent;
@@ -443,7 +627,7 @@ jasmineRequire.HtmlReporter = function(j$) {
function addDeprecationWarnings(result) {
if (result && result.deprecationWarnings) {
for(var i = 0; i < result.deprecationWarnings.length; i++) {
for (var i = 0; i < result.deprecationWarnings.length; i++) {
var warning = result.deprecationWarnings[i].message;
if (!j$.util.arrayContains(warning)) {
deprecationWarnings.push(warning);
@@ -460,7 +644,7 @@ jasmineRequire.HtmlReporter = function(j$) {
// return the reporter
var oldReporter = find('');
if(oldReporter) {
if (oldReporter) {
getContainer().removeChild(oldReporter);
}
}
@@ -492,7 +676,7 @@ jasmineRequire.HtmlReporter = function(j$) {
}
function pluralize(singular, count) {
var word = (count == 1 ? singular : singular + 's');
var word = count == 1 ? singular : singular + 's';
return '' + count + ' ' + word;
}
@@ -514,8 +698,13 @@ jasmineRequire.HtmlReporter = function(j$) {
}
function noExpectations(result) {
return (result.failedExpectations.length + result.passedExpectations.length) === 0 &&
result.status === 'passed';
var allExpectations =
result.failedExpectations.length + result.passedExpectations.length;
return (
allExpectations === 0 &&
(result.status === 'passed' || result.status === 'failed')
);
}
function hasActiveSpec(resultNode) {
@@ -538,7 +727,10 @@ jasmineRequire.HtmlReporter = function(j$) {
jasmineRequire.HtmlSpecFilter = function() {
function HtmlSpecFilter(options) {
var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
var filterString =
options &&
options.filterString() &&
options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
var filterPattern = new RegExp(filterString);
this.matches = function(specName) {
@@ -575,9 +767,11 @@ jasmineRequire.ResultsNode = function() {
jasmineRequire.QueryString = function() {
function QueryString(options) {
this.navigateWithNewParam = function(key, value) {
options.getWindowLocation().search = this.fullStringWithNewParam(key, value);
options.getWindowLocation().search = this.fullStringWithNewParam(
key,
value
);
};
this.fullStringWithNewParam = function(key, value) {
@@ -595,7 +789,9 @@ jasmineRequire.QueryString = function() {
function toQueryString(paramMap) {
var qStrPairs = [];
for (var prop in paramMap) {
qStrPairs.push(encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop]));
qStrPairs.push(
encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop])
);
}
return '?' + qStrPairs.join('&');
}
@@ -619,7 +815,6 @@ jasmineRequire.QueryString = function() {
return paramMap;
}
}
return QueryString;

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
/*
Copyright (c) 2008-2018 Pivotal Labs
Copyright (c) 2008-2020 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

View File

@@ -4,6 +4,6 @@
#
module Jasmine
module Core
VERSION = "3.2.1"
VERSION = "3.6.0"
end
end

View File

@@ -1,7 +1,7 @@
{
"name": "jasmine-core",
"license": "MIT",
"version": "3.2.1",
"version": "3.6.0",
"repository": {
"type": "git",
"url": "https://github.com/jasmine/jasmine.git"
@@ -13,23 +13,88 @@
"bdd"
],
"scripts": {
"test": "grunt jshint execSpecsInNode"
"posttest": "eslint \"src/**/*.js\" \"spec/**/*.js\" && prettier --check src/**/*.js spec/**/*.js",
"test": "grunt --stack execSpecsInNode",
"cleanup": "prettier --write src/**/*.js spec/**/*.js",
"build": "grunt buildDistribution",
"serve": "node spec/support/localJasmineBrowser.js",
"serve:performance": "node spec/support/localJasmineBrowser.js jasmine-browser-performance.json",
"ci": "node spec/support/ci.js",
"ci:performance": "node spec/support/ci.js jasmine-browser-performance.json"
},
"description": "Official packaging of Jasmine's core files for use by Node.js projects.",
"homepage": "http://jasmine.github.io",
"homepage": "https://jasmine.github.io",
"main": "./lib/jasmine-core.js",
"devDependencies": {
"glob": "~7.1.2",
"grunt": "^1.0.1",
"grunt-cli": "^1.2.0",
"grunt-contrib-compass": "^1.1.1",
"acorn": "^6.0.0",
"ejs": "^2.5.5",
"eslint": "^6.8.0",
"eslint-plugin-compat": "^3.8.0",
"express": "^4.16.4",
"fast-check": "^1.21.0",
"fast-glob": "^2.2.6",
"grunt": "^1.0.4",
"grunt-cli": "^1.3.2",
"grunt-contrib-compress": "^1.3.0",
"grunt-contrib-concat": "^1.0.1",
"grunt-contrib-jshint": "^1.0.0",
"jasmine": "^3.0.0",
"jsdom": "^9.12.0",
"load-grunt-tasks": "^0.4.0",
"shelljs": "^0.7.0",
"temp": "~0.8.1"
}
"grunt-css-url-embed": "^1.11.1",
"grunt-sass": "^3.0.2",
"jasmine": "^3.4.0",
"jasmine-browser-runner": "github:jasmine/jasmine-browser",
"jsdom": "^15.0.0",
"load-grunt-tasks": "^4.0.0",
"node-sass": "^4.11.0",
"prettier": "1.17.1",
"selenium-webdriver": "^3.6.0",
"shelljs": "^0.8.3",
"temp": "^0.9.0"
},
"prettier": {
"singleQuote": true
},
"eslintConfig": {
"extends": [
"plugin:compat/recommended"
],
"parserOptions": {
"ecmaVersion": 5
},
"rules": {
"quotes": [
"error",
"single",
{
"avoidEscape": true
}
],
"no-unused-vars": [
"error",
{
"args": "none"
}
],
"block-spacing": "error",
"func-call-spacing": [
"error",
"never"
],
"key-spacing": "error",
"no-tabs": "error",
"no-trailing-spaces": "error",
"no-whitespace-before-property": "error",
"semi": [
"error",
"always"
],
"space-before-blocks": "error"
}
},
"browserslist": [
"Safari >= 8",
"last 2 Chrome versions",
"last 2 Firefox versions",
"Firefox 68",
"last 2 Edge versions",
"IE >= 10"
]
}

View File

@@ -29,6 +29,8 @@ There is also a 2.99 release of Jasmine that will present deprecation warnings f
* Default to running tests in random order
* The `identity` of a Jasmnine Spy is now a property and no longer a method
* Additionally, Jasmine 3.0 drops support for older browsers and environments. Notably:
- Internet Explorer 8 and 9
- Ruby 1.x (for the Ruby gem)

47
release_notes/3.3.0.md Normal file
View File

@@ -0,0 +1,47 @@
# Jasmine Core 3.3 Release Notes
## Summary
This release includes a new way to configure Jasmine, the ability to provide additional
context with your expectations, and other things
## Changes
* Added expect().withContext() to provide additional information in failure messages
* Implement `withContext` for async expectations too
- Fixes [#641](https://github.com/jasmine/jasmine/issues/641)
* New asynchronous matcher `toBeRejectedWith`
- Merges [#1615](https://github.com/jasmine/jasmine/issues/1615) from @codymikol
- Closes [#1600](https://github.com/jasmine/jasmine/issues/1600)
- Fixes [#1595](https://github.com/jasmine/jasmine/issues/1595)
* Show a tip for `toBe` failures for how to get deep equality
- Merges [#1616](https://github.com/jasmine/jasmine/issues/1616) from @tdurtshi
- Fixes [#1614](https://github.com/jasmine/jasmine/issues/1614)
* `expectAsync` now works with non-native promises
- Merges [#1613](https://github.com/jasmine/jasmine/issues/1613) from @codymikol
- Fixes [#1612](https://github.com/jasmine/jasmine/issues/1612)
* Show status marks next to spec description in HTML reporter
- Merges [#1610](https://github.com/jasmine/jasmine/issues/1610) from @m1010j
- Fixes [#1596](https://github.com/jasmine/jasmine/issues/1596)
* Show error messages for `Error`s without a name
- Merges [#1601](https://github.com/jasmine/jasmine/issues/1601) from @nitobuendia
- Fixes [#1594](https://github.com/jasmine/jasmine/issues/1594)
* Optimized clearTimeout cpu usage
- Merges [#1599](https://github.com/jasmine/jasmine/issues/1599) from @Havunen
* Introduce a configuration object to `Env` deprecating old single use functions
- [finishes #159158038](http://www.pivotaltracker.com/story/159158038)
* Specify https for github urls in package.json
- Merges [#1597](https://github.com/jasmine/jasmine/issues/1597) @limonte
------
_Release Notes generated with _[Anchorman](http://github.com/infews/anchorman)_

49
release_notes/3.4.0.md Normal file
View File

@@ -0,0 +1,49 @@
# Jasmine Core 3.4 Release Notes
## Summary
This is a maintenance release of Jasmine with a number of new features and fixes
## Changes
* Handle WebSocket events in IE when detecting Errors
- Fixes [#1623](https://github.com/jasmine/jasmine/issues/1623)
* bump dependencies for security fixes
- Merges [#1672](https://github.com/jasmine/jasmine/issues/1672) from @wood1986
* Make node execution default and override for browsers
- Merges [#1658](https://github.com/jasmine/jasmine/issues/1658) from @wood1986
- Fixes [#883](https://github.com/jasmine/jasmine/issues/883)
* feat(result.duration): report test duration in ms
- Merges [#1660](https://github.com/jasmine/jasmine/issues/1660) from @johnjbarton
- Fixes [#1646](https://github.com/jasmine/jasmine/issues/1646)
* refactor(Timer): share htmlReporter noopTimer via Timer.js
- Merges [#1669](https://github.com/jasmine/jasmine/issues/1669) from @johnjbarton
* Fix various typos
- Merges [#1666](https://github.com/jasmine/jasmine/issues/1666) from @FelixRilling
- Merges [#1667](https://github.com/jasmine/jasmine/issues/1667) from @FelixRilling
- Merges [#1665](https://github.com/jasmine/jasmine/issues/1665) from @FelixRilling
- Merges [#1664](https://github.com/jasmine/jasmine/issues/1664) from @FelixRilling
- Fixes [#1663](https://github.com/jasmine/jasmine/issues/1663)
* When catching a global error in Node.js, print the type of error
- Merges [#1632](https://github.com/jasmine/jasmine/issues/1632) from @jbunton-atlassian
* Support Error.stack in globalErrors.
- Merges [#1644](https://github.com/jasmine/jasmine/issues/1644) from @johnjbarton
* Stop treating objects with a `nodeType` as if they are DOM Nodes
- Fixes [#1638](https://github.com/jasmine/jasmine/issues/1638)
* Fixes issue where PhantomJS 2 and IE 10 - 11 crashed when reporting SVG element equality
- Merges [#1621](https://github.com/jasmine/jasmine/issues/1621) from @Havunen
- Fixes [#1618](https://github.com/jasmine/jasmine/issues/1618)
------
_Release Notes generated with _[Anchorman](http://github.com/infews/anchorman)_

199
release_notes/3.5.0.md Normal file
View File

@@ -0,0 +1,199 @@
# Jasmine Core 3.5 Release Notes
## Summary
This is a maintenance release of Jasmine with a number of new features and fixes
### Highlights
* The output of toHaveBeenCalledWith should now be more readable
This breaks each call out onto its own line, so that it's much easier to
see where each call starts and how they differ. E.g. previously the output
would be:
Expected spy foo to have been called with [ 'bar', 'baz', 'qux' ] but actual calls were [ [ 42, 'wibble' ], [ 'bar' 'qux' ], [ 'grault '] ]
Now it's:
Expected spy foo to have been called with:
[ 'bar', 'baz', 'qux' ]
but actual calls were:
[ 42, 'wibble' ],
[ 'bar' 'qux' ],
[ 'grault '].
* Add new spy strategies to resolve and reject Promises `resolveTo` and `rejectWith`
* Add the ability to have custom async matchers
### Internal notes
* Stop testing against PhantomJS
* PhantomJS is at end of life, and the last version of Selenium that supported it was 3.6.0, released almost three years ago. We can't test Jasmine against PhantomJS without pinning key pieces of the project to increasingly outdated versions of key libraries.
* Fail Jasmine's CI build if the promise returned from `jasmineBrowser.runSpecs` is rejected
* A bunch of other rejiggering of the Travis-CI builds to make them easier to work with
* Also released a new browser runner that is being used by Jasmine
* See [jasmine-browser-runner](https://github.com/jasmine/jasmine-browser)
* This is a first pass at getting this to work for other projects as well. Please try it out and let us know what isn't working for you.
* add prettier and eslint
## All Changes
* Adds new configuration option to failSpecWithNoExpectations that will report specs without expectations as failures if enabled
* Merges [#1743](https://github.com/jasmine/jasmine/issues/1743) from @dtychshenko
* Fixes [#1740](https://github.com/jasmine/jasmine/issues/1740)
* Correctly propagate the `Error` object caught by the global error handler to reporters, etc.
- Merges [#1738](https://github.com/jasmine/jasmine/issues/1738) from @prantlf
- Fixes [#1728](https://github.com/jasmine/jasmine/issues/1728)
* Show argument diffs in toHaveBeenCalledWith failure messages
* Fixes [#1641](https://github.com/jasmine/jasmine/issues/1641)
* Updated arrayContaining to require actual values to be arrays
* Merges [#1746](https://github.com/jasmine/jasmine/issues/1746) from @divido
* Fixes [#1745](https://github.com/jasmine/jasmine/issues/1745)
* Add the ability to have custom async matchers
* Merges [#1732](https://github.com/jasmine/jasmine/issues/1732) from @UziTech
* Allow users to set a default spy strategy
- Merges [#1716](https://github.com/jasmine/jasmine/issues/1716) from @elliot-nelson
* Accept configurations with `Promise: undefined`.
* PrettyPrinter survives if objects throw in toString
- Merges [#1718](https://github.com/jasmine/jasmine/issues/1718) from @johnjbarton
- Fixes [#1726](https://github.com/jasmine/jasmine/issues/1726)
* Add `mapContaining` and `setContaining` asymmetric matchers
* Merges [#1741](https://github.com/jasmine/jasmine/issues/1741) from @eventlistener
* Use the same spec file pattern for both node and browser
* Gemspec: Drop EOL'd property rubyforge_project
* Merges [#1736](https://github.com/jasmine/jasmine/issues/1736) from @olleolleolle
* Updated async timeout message to include all of the ways that async code can be run in Jasmine
* Allow users to pass property names to createSpyObj
- Merges [#1722](https://github.com/jasmine/jasmine/issues/1722) from @elliot-nelson
- Closes [#1569](https://github.com/jasmine/jasmine/issues/1569)
- Fixes [#1442](https://github.com/jasmine/jasmine/issues/1442)
* don't attempt to normalize PNGs (gitattributes)
- Merges [#1721](https://github.com/jasmine/jasmine/issues/1721) from @elliot-nelson
* Add `@since` to most JSDoc comments
- See [jasmine/jasmine.github.io#117](https://github.com/jasmine/jasmine.github.io/issues/117)
* Make no expectations in HTML Reporter message a console warning
- Fixes [#1704](https://github.com/jasmine/jasmine/issues/1704)
* Prevent page overflow in HTML reporter under some situations by setting an explicit width
- Merges [#1713](https://github.com/jasmine/jasmine/issues/1713) from @pixelpax
* Cleanup: minor dead code removal and style fixes
- Merges [#1708](https://github.com/jasmine/jasmine/issues/1708) from @elliot-nelson
* Pretty Printer can now handle printing an object whose `toString` function has been spied upon
- Merges [#1712](https://github.com/jasmine/jasmine/issues/1712) from @johnjbarton
* PrettyPrinter handles objects with invalid toString implementations
- Merges [#1711](https://github.com/jasmine/jasmine/issues/1711) from @elliot-nelson
- Closes [#1700](https://github.com/jasmine/jasmine/issues/1700)
- Closes [#1575](https://github.com/jasmine/jasmine/issues/1575)
* Fix toBeCloseTo matcher for Node.js 12 and Chrome 74
- Merges [#1710](https://github.com/jasmine/jasmine/issues/1710) from @paulvanbrenk
- Fixes [#1695](https://github.com/jasmine/jasmine/issues/1695)
* spyOnProperty jasmine-style error messages with usage note
- Merges [#1706](https://github.com/jasmine/jasmine/issues/1706) from @elliot-nelson
* spyOnProperty respects the allowRespy flag
- Merges [#1705](https://github.com/jasmine/jasmine/issues/1705) from @elliot-nelson
* Introduce matchers#toBeInstanceOf
- Merges [#1697](https://github.com/jasmine/jasmine/issues/1697) from @elliot-nelson
* Print global errors encountered during CI runs
- Merges [#1701](https://github.com/jasmine/jasmine/issues/1701) from @elliot-nelson
* Update contributing doc based on some of the newer tooling
- Fixes [#1702](https://github.com/jasmine/jasmine/issues/1702)
* Extend spyOnAllFunctions to include prototype and parent methods
- Merges [#1699](https://github.com/jasmine/jasmine/issues/1699) from @elliot-nelson
- Fixes [#1677](https://github.com/jasmine/jasmine/issues/1677)
* Improve error handling in CI test launcher
- Merges [#1598](https://github.com/jasmine/jasmine/issues/1598) from @elliot-nelson
* Add new spy strategies to resolve and reject Promises `resolveTo` and `rejectWith`
- Merges [#1688](https://github.com/jasmine/jasmine/issues/1688) from @enelson
- See [#1590](https://github.com/jasmine/jasmine/issues/1590)
- Fixes [#1715](https://github.com/jasmine/jasmine/issues/1715)
* Update deprecation messages to indicate _future_ removal
- Fixes [#1628](https://github.com/jasmine/jasmine/issues/1628)
* Add toBeRejectedWithError matcher
- Merges [#1686](https://github.com/jasmine/jasmine/issues/1686) from @megahertz
- Fixes [#1625](https://github.com/jasmine/jasmine/issues/1625)
* Ignore internal ci.js from npm package
- See [#1684](https://github.com/jasmine/jasmine/issues/1684)
* Fix failure messages for positive/negative infinity matchers
- Fixes [#1674](https://github.com/jasmine/jasmine/issues/1674)
* nit: fix typo
- Merges [#1680](https://github.com/jasmine/jasmine/issues/1680) from @acinader
* added #toBeTrue and #toBeFalse matchers
- Merges [#1679](https://github.com/jasmine/jasmine/issues/1679) from @FelixRilling
------
_Release Notes generated with _[Anchorman](http://github.com/infews/anchorman)_

146
release_notes/3.6.0.md Normal file
View File

@@ -0,0 +1,146 @@
# Jasmine Core 3.6 Release Notes
## Summary
This is a maintenance release of Jasmine with a number of new features and fixes.
## Highlights
* Added support for custom object formatters
* Allows customizing how an object is stringified in matcher failure messages
* [Tutorial](https://jasmine.github.io/tutorials/custom_object_formatter)
* [API reference](https://jasmine.github.io/api/3.6/jasmine.html#.addCustomObjectFormatter)
* Don't require matchers and asymmetric equality testers to pass custom object formatters back to Jasmine
- Supports custom object formatters.
- Makes it easier to write high quality matchers and asymmetric equality testers.
- The old API will still work until 4.0.
* Properly import jasmineRequire object before using
- Improves compatibility with Webpack
- Merges [#1766](https://github.com/jasmine/jasmine/pull/1766) from @amilligan
* Added a toHaveBeenCalledOnceWith matcher
- Merges [#1801](https://github.com/jasmine/jasmine/pull/1801) from @Maximaximum
- Fixes [#1717](https://github.com/jasmine/jasmine/issues/1717)
* Added a toHaveSize matcher
- Merges [#1796](https://github.com/jasmine/jasmine/pull/1796) from @wokier
* Added a toBePending async matcher
- Merges [#1808](https://github.com/jasmine/jasmine/pull/1808) from @DCtheTall
- Fixes [#1803](https://github.com/jasmine/jasmine/issues/1803)
* Added support for user-defined spec/suite properties
- Allows specs/suites to pass data to custom reporters
- Merges [#1763](https://github.com/jasmine/jasmine/pull/1763) from @johnjbarton
* Route unhandled promise rejections to onerror
- Merges [#1778](https://github.com/jasmine/jasmine/pull/1778) from @johnjbarton
- Fixes [#1777](https://github.com/jasmine/jasmine/issues/1777)
## Internal notes
* Use a version of eslint that works on Node 8
* Check for syntax and standard library objects that don't work in IE
* Run eslint against all files
* Add Additional Test for equals Matcher
- Merges [#1829](https://github.com/jasmine/jasmine/pull/1829) from @tobiasschweizer
- Fixes [#1821](https://github.com/jasmine/jasmine/issues/1821)
* Depend on head of jasmine-browser to fix IE failures in CI
* Fixed test failure in Firefox 74
* Added test for resolveTo/rejectWith with empty parameters
- Merges [#1802](https://github.com/jasmine/jasmine/pull/1802) from @chivesrs
* Removed unnecessary uses of new in tests
* Realigned the browser testing matrix to match current reality
- Use Windows instead of Linux so we can get current browsers from Sauce.
- Test against the version of Firefox that corresponds to ESR as well as
latest.
- Test the latest Edge rather than a specific older version.
- Test Safari 8 and 13 instead of 8, 9 and 10. What works in those versions
is likely to work in the ones in between.
* Don't leak global error handlers between Jasmine's own tests
* Added basic property tests for matchersUtil.equals
* Added integration tests for existing matcher interfaces
* Added integration tests for asymmetric equality testers
* Test IE before other browsers on Travis
## Other Changes
* Show diffs involving root-level asymmetric equality testers
- Fixes [#1831](https://github.com/jasmine/jasmine/issues/1831)
* Fixed references to master in docs
* Allow spy throwError to throw an Object
- Merges [#1822](https://github.com/jasmine/jasmine/pull/1822) from @terencehonles
* Added missing periods to README
- Merges [#1828](https://github.com/jasmine/jasmine/pull/1828) from @dirkpuge
* Expose setSpec/SuiteProperty on interface
- Merges [#1820](https://github.com/jasmine/jasmine/pull/1820) from @johnjbarton
* Prevent undesired reloads when karma-jasmine-html-reporter is used
- Merges [#1807](https://github.com/jasmine/jasmine/pull/1807) from @parloti
- Fixes [#1775](https://github.com/jasmine/jasmine/issues/1775)
* Correctly report spec and suite duration
- Fixes [#1676](https://github.com/jasmine/jasmine/issues/1676).
* Added jsdocs for MatchersUtil
* Allow the .callThrough spy strategy to call constructor functions without errors
- Merges [#1782](https://github.com/jasmine/jasmine/pull/1782) from @enelson
- Fixes [#1760](https://github.com/jasmine/jasmine/issues/1760)
* Inject a per-runable pretty printer into MatchersUtil
- Supports custom object formatters
* Include stack traces in unhandled promise rejection messages
* Describe the naming for the function it
- Merges [#1772](https://github.com/jasmine/jasmine/pull/1772) from @johnlinp
* Correctly extract error messages from stack traces that don't start with `Error`
- Merges [#1776](https://github.com/jasmine/jasmine/pull/1776) from @vhermannitk
- Fixes [#1771](https://github.com/jasmine/jasmine/issues/1771)
* Fixed objectContaining to not match when the expected is the empty object and the actual is a non-object
* Fixed toEqual(0, Number.MIN_VALUE) to fail instead of passing
- Merges [#1764](https://github.com/jasmine/jasmine/pull/1764) from @dubzzz
* Fixed comparison between ObjectContaining and non-objects on IE
* Provide better diffs for object graphs that include `objectContaining`
* Indent multiline failure messages in the output of `withContext`
* This makes it easier to see where each failure message begins and ends.
* Report async expectations that complete after the runable completes
- See [#1752](https://github.com/jasmine/jasmine/issues/1752).
* Treat NodeJS assertion failures as expectation failures
- Merges [#1678](https://github.com/jasmine/jasmine/pull/1678) from @apla
------
_Release Notes generated with _[Anchorman](http://github.com/infews/anchorman)_

17
spec/.eslintrc.js Normal file
View File

@@ -0,0 +1,17 @@
module.exports = {
"ignorePatterns": [
"support/ci.js",
"support/jasmine-browser.js"
],
rules: {
// Relax rules for now to allow for the quirks of the test suite
// TODO: We should probably remove these & fix the resulting errors
"quotes": "off",
"semi": "off",
"key-spacing": "off",
"space-before-blocks": "off",
"no-unused-vars": "off",
"no-trailing-spaces": "off",
"block-spacing": "off",
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
describe("CallTracker", function() {
it("tracks that it was called when executed", function() {
describe('CallTracker', function() {
it('tracks that it was called when executed', function() {
var callTracker = new jasmineUnderTest.CallTracker();
expect(callTracker.any()).toBe(false);
@@ -9,7 +9,7 @@ describe("CallTracker", function() {
expect(callTracker.any()).toBe(true);
});
it("tracks that number of times that it is executed", function() {
it('tracks that number of times that it is executed', function() {
var callTracker = new jasmineUnderTest.CallTracker();
expect(callTracker.count()).toEqual(0);
@@ -19,52 +19,52 @@ describe("CallTracker", function() {
expect(callTracker.count()).toEqual(1);
});
it("tracks the params from each execution", function() {
it('tracks the params from each execution', function() {
var callTracker = new jasmineUnderTest.CallTracker();
callTracker.track({object: void 0, args: []});
callTracker.track({object: {}, args: [0, "foo"]});
callTracker.track({ object: void 0, args: [] });
callTracker.track({ object: {}, args: [0, 'foo'] });
expect(callTracker.argsFor(0)).toEqual([]);
expect(callTracker.argsFor(1)).toEqual([0, "foo"]);
expect(callTracker.argsFor(1)).toEqual([0, 'foo']);
});
it("returns any empty array when there was no call", function() {
it('returns any empty array when there was no call', function() {
var callTracker = new jasmineUnderTest.CallTracker();
expect(callTracker.argsFor(0)).toEqual([]);
});
it("allows access for the arguments for all calls", function() {
it('allows access for the arguments for all calls', function() {
var callTracker = new jasmineUnderTest.CallTracker();
callTracker.track({object: {}, args: []});
callTracker.track({object: {}, args: [0, "foo"]});
callTracker.track({ object: {}, args: [] });
callTracker.track({ object: {}, args: [0, 'foo'] });
expect(callTracker.allArgs()).toEqual([[], [0, "foo"]]);
expect(callTracker.allArgs()).toEqual([[], [0, 'foo']]);
});
it("tracks the context and arguments for each call", function() {
it('tracks the context and arguments for each call', function() {
var callTracker = new jasmineUnderTest.CallTracker();
callTracker.track({object: {}, args: []});
callTracker.track({object: {}, args: [0, "foo"]});
callTracker.track({ object: {}, args: [] });
callTracker.track({ object: {}, args: [0, 'foo'] });
expect(callTracker.all()[0]).toEqual({object: {}, args: []});
expect(callTracker.all()[0]).toEqual({ object: {}, args: [] });
expect(callTracker.all()[1]).toEqual({object: {}, args: [0, "foo"]});
expect(callTracker.all()[1]).toEqual({ object: {}, args: [0, 'foo'] });
});
it("simplifies access to the arguments for the last (most recent) call", function() {
it('simplifies access to the arguments for the last (most recent) call', function() {
var callTracker = new jasmineUnderTest.CallTracker();
callTracker.track();
callTracker.track({object: {}, args: [0, "foo"]});
callTracker.track({ object: {}, args: [0, 'foo'] });
expect(callTracker.mostRecent()).toEqual({
object: {},
args: [0, "foo"]
args: [0, 'foo']
});
});
@@ -74,12 +74,12 @@ describe("CallTracker", function() {
expect(callTracker.mostRecent()).toBeFalsy();
});
it("simplifies access to the arguments for the first (oldest) call", function() {
it('simplifies access to the arguments for the first (oldest) call', function() {
var callTracker = new jasmineUnderTest.CallTracker();
callTracker.track({object: {}, args: [0, "foo"]});
callTracker.track({ object: {}, args: [0, 'foo'] });
expect(callTracker.first()).toEqual({object: {}, args: [0, "foo"]})
expect(callTracker.first()).toEqual({ object: {}, args: [0, 'foo'] });
});
it("returns a useful falsy value when there isn't a first (oldest) call", function() {
@@ -88,12 +88,11 @@ describe("CallTracker", function() {
expect(callTracker.first()).toBeFalsy();
});
it("allows the tracking to be reset", function() {
it('allows the tracking to be reset', function() {
var callTracker = new jasmineUnderTest.CallTracker();
callTracker.track();
callTracker.track({object: {}, args: [0, "foo"]});
callTracker.track({ object: {}, args: [0, 'foo'] });
callTracker.reset();
expect(callTracker.any()).toBe(false);
@@ -103,14 +102,17 @@ describe("CallTracker", function() {
expect(callTracker.mostRecent()).toBeFalsy();
});
it("allows object arguments to be shallow cloned", function() {
it('allows object arguments to be shallow cloned', function() {
var callTracker = new jasmineUnderTest.CallTracker();
callTracker.saveArgumentsByValue();
var objectArg = {"foo": "bar"},
arrayArg = ["foo", "bar"];
var objectArg = { foo: 'bar' },
arrayArg = ['foo', 'bar'];
callTracker.track({object: {}, args: [objectArg, arrayArg, false, undefined, null, NaN, "", 0, 1.0]});
callTracker.track({
object: {},
args: [objectArg, arrayArg, false, undefined, null, NaN, '', 0, 1.0]
});
expect(callTracker.mostRecent().args[0]).not.toBe(objectArg);
expect(callTracker.mostRecent().args[0]).toEqual(objectArg);

View File

@@ -1,17 +1,23 @@
describe("ClearStack", function() {
it("works in an integrationy way", function(done) {
var clearStack = jasmineUnderTest.getClearStack(jasmineUnderTest.getGlobal());
describe('ClearStack', function() {
it('works in an integrationy way', function(done) {
var clearStack = jasmineUnderTest.getClearStack(
jasmineUnderTest.getGlobal()
);
clearStack(function() {
done();
});
});
it("uses setImmediate when available", function() {
var setImmediate = jasmine.createSpy('setImmediate').and.callFake(function(fn) { fn() }),
global = { setImmediate: setImmediate },
clearStack = jasmineUnderTest.getClearStack(global),
called = false;
it('uses setImmediate when available', function() {
var setImmediate = jasmine
.createSpy('setImmediate')
.and.callFake(function(fn) {
fn();
}),
global = { setImmediate: setImmediate },
clearStack = jasmineUnderTest.getClearStack(global),
called = false;
clearStack(function() {
called = true;
@@ -21,42 +27,50 @@ describe("ClearStack", function() {
expect(setImmediate).toHaveBeenCalled();
});
it("uses setTimeout instead of setImmediate every 10 calls to make sure we release the CPU", function() {
it('uses setTimeout instead of setImmediate every 10 calls to make sure we release the CPU', function() {
var setImmediate = jasmine.createSpy('setImmediate'),
setTimeout = jasmine.createSpy('setTimeout'),
global = { setImmediate: setImmediate, setTimeout: setTimeout },
clearStack = jasmineUnderTest.getClearStack(global);
setTimeout = jasmine.createSpy('setTimeout'),
global = { setImmediate: setImmediate, setTimeout: setTimeout },
clearStack = jasmineUnderTest.getClearStack(global);
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
expect(setImmediate).toHaveBeenCalled();
expect(setTimeout).not.toHaveBeenCalled();
clearStack(function() { });
clearStack(function() {});
expect(setImmediate.calls.count()).toEqual(9);
expect(setTimeout.calls.count()).toEqual(1);
clearStack(function() { });
clearStack(function() {});
expect(setImmediate.calls.count()).toEqual(10);
expect(setTimeout.calls.count()).toEqual(1);
});
it("uses MessageChannels when available", function() {
it('uses MessageChannels when available', function() {
var fakeChannel = {
port1: {},
port2: { postMessage: function() { fakeChannel.port1.onmessage(); } }
},
global = { MessageChannel: function() { return fakeChannel; } },
clearStack = jasmineUnderTest.getClearStack(global),
called = false;
port1: {},
port2: {
postMessage: function() {
fakeChannel.port1.onmessage();
}
}
},
global = {
MessageChannel: function() {
return fakeChannel;
}
},
clearStack = jasmineUnderTest.getClearStack(global),
called = false;
clearStack(function() {
called = true;
@@ -65,53 +79,66 @@ describe("ClearStack", function() {
expect(called).toBe(true);
});
it("uses setTimeout instead of MessageChannel every 10 calls to make sure we release the CPU", function() {
it('uses setTimeout instead of MessageChannel every 10 calls to make sure we release the CPU', function() {
var fakeChannel = {
port1: {},
port2: {
postMessage: jasmine.createSpy('postMessage').and.callFake(function() {
port1: {},
port2: {
postMessage: jasmine
.createSpy('postMessage')
.and.callFake(function() {
fakeChannel.port1.onmessage();
})
}
}
},
setTimeout = jasmine.createSpy('setTimeout'),
global = {
MessageChannel: function() {
return fakeChannel;
},
setTimeout = jasmine.createSpy('setTimeout'),
global = { MessageChannel: function() { return fakeChannel; }, setTimeout: setTimeout },
clearStack = jasmineUnderTest.getClearStack(global);
setTimeout: setTimeout
},
clearStack = jasmineUnderTest.getClearStack(global);
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() { });
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
clearStack(function() {});
expect(fakeChannel.port2.postMessage).toHaveBeenCalled();
expect(setTimeout).not.toHaveBeenCalled();
clearStack(function() { });
clearStack(function() {});
expect(fakeChannel.port2.postMessage.calls.count()).toEqual(9);
expect(setTimeout.calls.count()).toEqual(1);
clearStack(function() { });
clearStack(function() {});
expect(fakeChannel.port2.postMessage.calls.count()).toEqual(10);
expect(setTimeout.calls.count()).toEqual(1);
});
it("calls setTimeout when onmessage is called recursively", function() {
it('calls setTimeout when onmessage is called recursively', function() {
var fakeChannel = {
port1: {},
port2: { postMessage: function() { fakeChannel.port1.onmessage(); } }
port1: {},
port2: {
postMessage: function() {
fakeChannel.port1.onmessage();
}
}
},
setTimeout = jasmine.createSpy('setTimeout'),
global = {
MessageChannel: function() {
return fakeChannel;
},
setTimeout = jasmine.createSpy('setTimeout'),
global = {
MessageChannel: function() { return fakeChannel; },
setTimeout: setTimeout,
},
clearStack = jasmineUnderTest.getClearStack(global),
fn = jasmine.createSpy("second clearStack function");
setTimeout: setTimeout
},
clearStack = jasmineUnderTest.getClearStack(global),
fn = jasmine.createSpy('second clearStack function');
clearStack(function() {
clearStack(fn);
@@ -121,11 +148,13 @@ describe("ClearStack", function() {
expect(setTimeout).toHaveBeenCalledWith(fn, 0);
});
it("falls back to setTimeout", function() {
var setTimeout = jasmine.createSpy('setTimeout').and.callFake(function(fn) { fn() }),
global = { setTimeout: setTimeout },
clearStack = jasmineUnderTest.getClearStack(global),
called = false;
it('falls back to setTimeout', function() {
var setTimeout = jasmine.createSpy('setTimeout').and.callFake(function(fn) {
fn();
}),
global = { setTimeout: setTimeout },
clearStack = jasmineUnderTest.getClearStack(global),
called = false;
clearStack(function() {
called = true;

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
describe("DelayedFunctionScheduler", function() {
it("schedules a function for later execution", function() {
describe('DelayedFunctionScheduler', function() {
it('schedules a function for later execution', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn');
@@ -12,9 +12,9 @@ describe("DelayedFunctionScheduler", function() {
expect(fn).toHaveBeenCalled();
});
it("schedules a string for later execution", function() {
it('schedules a string for later execution', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
strfn = "horrible = true;";
strfn = 'horrible = true;';
scheduler.scheduleFunction(strfn, 0);
@@ -23,7 +23,7 @@ describe("DelayedFunctionScheduler", function() {
expect(horrible).toEqual(true);
});
it("#tick defaults to 0", function() {
it('#tick defaults to 0', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn');
@@ -36,7 +36,7 @@ describe("DelayedFunctionScheduler", function() {
expect(fn).toHaveBeenCalled();
});
it("defaults delay to 0", function() {
it('defaults delay to 0', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn');
@@ -49,7 +49,7 @@ describe("DelayedFunctionScheduler", function() {
expect(fn).toHaveBeenCalled();
});
it("optionally passes params to scheduled functions", function() {
it('optionally passes params to scheduled functions', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn');
@@ -62,7 +62,7 @@ describe("DelayedFunctionScheduler", function() {
expect(fn).toHaveBeenCalledWith('foo', 'bar');
});
it("scheduled fns can optionally reoccur", function() {
it('scheduled fns can optionally reoccur', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn');
@@ -81,23 +81,20 @@ describe("DelayedFunctionScheduler", function() {
scheduler.tick(21);
expect(fn.calls.count()).toBe(4);
});
it("increments scheduled fns ids unless one is passed", function() {
it('increments scheduled fns ids unless one is passed', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler();
expect(scheduler.scheduleFunction(function() {
}, 0)).toBe(1);
expect(scheduler.scheduleFunction(function() {
}, 0)).toBe(2);
expect(scheduler.scheduleFunction(function() {
}, 0, [], false, 123)).toBe(123);
expect(scheduler.scheduleFunction(function() {
}, 0)).toBe(3);
expect(scheduler.scheduleFunction(function() {}, 0)).toBe(1);
expect(scheduler.scheduleFunction(function() {}, 0)).toBe(2);
expect(scheduler.scheduleFunction(function() {}, 0, [], false, 123)).toBe(
123
);
expect(scheduler.scheduleFunction(function() {}, 0)).toBe(3);
});
it("#removeFunctionWithId removes a previously scheduled function with a given id", function() {
it('#removeFunctionWithId removes a previously scheduled function with a given id', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'),
timeoutKey;
@@ -113,7 +110,7 @@ describe("DelayedFunctionScheduler", function() {
expect(fn).not.toHaveBeenCalled();
});
it("executes recurring functions interleaved with regular functions in the correct order", function() {
it('executes recurring functions interleaved with regular functions in the correct order', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'),
recurringCallCount = 0,
@@ -134,12 +131,12 @@ describe("DelayedFunctionScheduler", function() {
expect(fn).toHaveBeenCalled();
});
it("schedules a function for later execution during a tick", function () {
it('schedules a function for later execution during a tick', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'),
fnDelay = 10;
scheduler.scheduleFunction(function () {
scheduler.scheduleFunction(function() {
scheduler.scheduleFunction(fn, fnDelay);
}, 0);
@@ -150,13 +147,13 @@ describe("DelayedFunctionScheduler", function() {
expect(fn).toHaveBeenCalled();
});
it("#removeFunctionWithId removes a previously scheduled function with a given id during a tick", function () {
it('#removeFunctionWithId removes a previously scheduled function with a given id during a tick', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'),
fnDelay = 10,
timeoutKey;
scheduler.scheduleFunction(function () {
scheduler.scheduleFunction(function() {
scheduler.removeFunctionWithId(timeoutKey);
}, 0);
timeoutKey = scheduler.scheduleFunction(fn, fnDelay);
@@ -168,7 +165,7 @@ describe("DelayedFunctionScheduler", function() {
expect(fn).not.toHaveBeenCalled();
});
it("executes recurring functions interleaved with regular functions and functions scheduled during a tick in the correct order", function () {
it('executes recurring functions interleaved with regular functions and functions scheduled during a tick in the correct order', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'),
recurringCallCount = 0,
@@ -185,7 +182,7 @@ describe("DelayedFunctionScheduler", function() {
scheduling = jasmine.createSpy('scheduling').and.callFake(function() {
expect(recurring.calls.count()).toBe(3);
expect(fn).not.toHaveBeenCalled();
scheduler.scheduleFunction(innerFn, 10); // 41ms absolute
scheduler.scheduleFunction(innerFn, 10); // 41ms absolute
});
scheduler.scheduleFunction(recurring, 10, [], true);
@@ -201,7 +198,7 @@ describe("DelayedFunctionScheduler", function() {
expect(innerFn).toHaveBeenCalled();
});
it("executes recurring functions after rescheduling them", function () {
it('executes recurring functions after rescheduling them', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
recurring = function() {
expect(scheduler.scheduleFunction).toHaveBeenCalled();
@@ -209,12 +206,12 @@ describe("DelayedFunctionScheduler", function() {
scheduler.scheduleFunction(recurring, 10, [], true);
spyOn(scheduler, "scheduleFunction");
spyOn(scheduler, 'scheduleFunction');
scheduler.tick(10);
});
it("removes functions during a tick that runs the function", function() {
it('removes functions during a tick that runs the function', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
spy = jasmine.createSpy('fn'),
spyAndRemove = jasmine.createSpy('fn'),
@@ -235,14 +232,14 @@ describe("DelayedFunctionScheduler", function() {
expect(spyAndRemove).toHaveBeenCalled();
});
it("removes functions during the first tick that runs the function", function() {
it('removes functions during the first tick that runs the function', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'),
fnDelay = 10,
timeoutKey;
timeoutKey = scheduler.scheduleFunction(fn, fnDelay, [], true);
scheduler.scheduleFunction(function () {
scheduler.scheduleFunction(function() {
scheduler.removeFunctionWithId(timeoutKey);
}, fnDelay);
@@ -257,8 +254,7 @@ describe("DelayedFunctionScheduler", function() {
it("does not remove a function that hasn't been added yet", function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
fn = jasmine.createSpy('fn'),
fnDelay = 10,
timeoutKey;
fnDelay = 10;
scheduler.removeFunctionWithId('foo');
scheduler.scheduleFunction(fn, fnDelay, [], false, 'foo');
@@ -270,17 +266,16 @@ describe("DelayedFunctionScheduler", function() {
expect(fn).toHaveBeenCalled();
});
it("updates the mockDate per scheduled time", function () {
it('updates the mockDate per scheduled time', function() {
var scheduler = new jasmineUnderTest.DelayedFunctionScheduler(),
tickDate = jasmine.createSpy('tickDate');
scheduler.scheduleFunction(function() {});
scheduler.scheduleFunction(function() {}, 1);
scheduler.scheduleFunction(function() {});
scheduler.scheduleFunction(function() {}, 1);
scheduler.tick(1, tickDate);
scheduler.tick(1, tickDate);
expect(tickDate).toHaveBeenCalledWith(0);
expect(tickDate).toHaveBeenCalledWith(1);
})
expect(tickDate).toHaveBeenCalledWith(0);
expect(tickDate).toHaveBeenCalledWith(1);
});
});

View File

@@ -1,53 +1,112 @@
// TODO: Fix these unit tests!
describe("Env", function() {
describe('Env', function() {
var env;
beforeEach(function() {
env = new jasmineUnderTest.Env();
});
describe("#pending", function() {
it("throws the Pending Spec exception", function() {
afterEach(function() {
env.cleanup_();
});
describe('#pending', function() {
it('throws the Pending Spec exception', function() {
expect(function() {
env.pending();
}).toThrow(jasmineUnderTest.Spec.pendingSpecExceptionMessage);
});
it("throws the Pending Spec exception with a custom message", function() {
it('throws the Pending Spec exception with a custom message', function() {
expect(function() {
env.pending('custom message');
}).toThrow(jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'custom message');
}).toThrow(
jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'custom message'
);
});
});
describe("#topSuite", function() {
it("returns the Jasmine top suite for users to traverse the spec tree", function() {
describe('#topSuite', function() {
it('returns the Jasmine top suite for users to traverse the spec tree', function() {
var suite = env.topSuite();
expect(suite.description).toEqual('Jasmine__TopLevel__Suite');
});
});
it('accepts its own current configureation', function() {
env.configure(env.configuration());
});
it('can configure specs to throw errors on expectation failures', function() {
env.throwOnExpectationFailure(true);
env.configure({ oneFailurePerSpec: true });
spyOn(jasmineUnderTest, 'Spec');
env.it('foo', function() {});
expect(jasmineUnderTest.Spec).toHaveBeenCalledWith(jasmine.objectContaining({
throwOnExpectationFailure: true
}));
expect(jasmineUnderTest.Spec).toHaveBeenCalledWith(
jasmine.objectContaining({
throwOnExpectationFailure: true
})
);
});
it('can configure suites to throw errors on expectation failures', function() {
env.throwOnExpectationFailure(true);
env.configure({ oneFailurePerSpec: true });
spyOn(jasmineUnderTest, 'Suite');
env.describe('foo', function() {});
expect(jasmineUnderTest.Suite).toHaveBeenCalledWith(jasmine.objectContaining({
throwOnExpectationFailure: true
}));
expect(jasmineUnderTest.Suite).toHaveBeenCalledWith(
jasmine.objectContaining({
throwOnExpectationFailure: true
})
);
});
describe('#describe', function () {
it("throws an error when given arguments", function() {
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() {
var myLibrary = {
resolve: jasmine.createSpy(),
reject: jasmine.createSpy()
};
env.configure({ Promise: myLibrary });
});
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');
env.it('bar', function() {});
expect(jasmineUnderTest.Spec).toHaveBeenCalledWith(
jasmine.objectContaining({
throwOnExpectationFailure: false
})
);
});
it('defaults to multiple failures for suites', function() {
spyOn(jasmineUnderTest, 'Suite');
env.describe('foo', function() {});
expect(jasmineUnderTest.Suite).toHaveBeenCalledWith(
jasmine.objectContaining({
throwOnExpectationFailure: false
})
);
});
describe('#describe', function() {
it('throws an error when given arguments', function() {
expect(function() {
env.describe('done method', function(done) {});
}).toThrowError('describe does not expect any arguments');
@@ -61,29 +120,41 @@ describe("Env", function() {
// anything other than a function throws an error.
expect(function() {
env.describe('undefined arg', undefined);
}).toThrowError(/describe expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/);
}).toThrowError(
/describe expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/
);
expect(function() {
env.describe('null arg', null);
}).toThrowError(/describe expects a function argument; received \[object (Null|DOMWindow|Object)\]/);
}).toThrowError(
/describe expects a function argument; received \[object (Null|DOMWindow|Object)\]/
);
expect(function() {
env.describe('array arg', []);
}).toThrowError('describe expects a function argument; received [object Array]');
}).toThrowError(
'describe expects a function argument; received [object Array]'
);
expect(function() {
env.describe('object arg', {});
}).toThrowError('describe expects a function argument; received [object Object]');
}).toThrowError(
'describe expects a function argument; received [object Object]'
);
expect(function() {
env.describe('fn arg', function() {});
}).not.toThrowError('describe expects a function argument; received [object Function]');
}).not.toThrowError(
'describe expects a function argument; received [object Function]'
);
});
});
describe('#it', function () {
describe('#it', function() {
it('throws an error when it receives a non-fn argument', function() {
expect(function() {
env.it('undefined arg', null);
}).toThrowError(/it expects a function argument; received \[object (Null|DOMWindow|Object)\]/);
}).toThrowError(
/it expects a function argument; received \[object (Null|DOMWindow|Object)\]/
);
});
it('does not throw when it is not given a fn argument', function() {
@@ -113,7 +184,9 @@ describe("Env", function() {
it('throws an error when it receives a non-fn argument', function() {
expect(function() {
env.xit('undefined arg', null);
}).toThrowError(/xit expects a function argument; received \[object (Null|DOMWindow|Object)\]/);
}).toThrowError(
/xit expects a function argument; received \[object (Null|DOMWindow|Object)\]/
);
});
it('does not throw when it is not given a fn argument', function() {
@@ -130,19 +203,23 @@ describe("Env", function() {
});
});
describe('#fit', function () {
describe('#fit', function() {
it('throws an error when it receives a non-fn argument', function() {
expect(function() {
env.fit('undefined arg', undefined);
}).toThrowError(/fit expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/);
}).toThrowError(
/fit expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/
);
});
});
describe('#beforeEach', function () {
describe('#beforeEach', function() {
it('throws an error when it receives a non-fn argument', function() {
expect(function() {
env.beforeEach(undefined);
}).toThrowError(/beforeEach expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/);
}).toThrowError(
/beforeEach expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/
);
});
it('accepts an async function', function() {
@@ -153,11 +230,13 @@ describe("Env", function() {
});
});
describe('#beforeAll', function () {
describe('#beforeAll', function() {
it('throws an error when it receives a non-fn argument', function() {
expect(function() {
env.beforeAll(undefined);
}).toThrowError(/beforeAll expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/);
}).toThrowError(
/beforeAll expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/
);
});
it('accepts an async function', function() {
@@ -168,11 +247,13 @@ describe("Env", function() {
});
});
describe('#afterEach', function () {
describe('#afterEach', function() {
it('throws an error when it receives a non-fn argument', function() {
expect(function() {
env.afterEach(undefined);
}).toThrowError(/afterEach expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/);
}).toThrowError(
/afterEach expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/
);
});
it('accepts an async function', function() {
@@ -183,11 +264,13 @@ describe("Env", function() {
});
});
describe('#afterAll', function () {
describe('#afterAll', function() {
it('throws an error when it receives a non-fn argument', function() {
expect(function() {
env.afterAll(undefined);
}).toThrowError(/afterAll expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/);
}).toThrowError(
/afterAll expects a function argument; received \[object (Undefined|DOMWindow|Object)\]/
);
});
it('accepts an async function', function() {
@@ -200,21 +283,107 @@ describe("Env", function() {
describe('when not constructed with suppressLoadErrors: true', function() {
it('installs a global error handler on construction', function() {
var globalErrors = jasmine.createSpyObj('globalErrors', ['install', 'pushListener', 'popListener']);
var globalErrors = jasmine.createSpyObj('globalErrors', [
'install',
'uninstall',
'pushListener',
'popListener'
]);
spyOn(jasmineUnderTest, 'GlobalErrors').and.returnValue(globalErrors);
new jasmineUnderTest.Env();
env.cleanup_();
env = new jasmineUnderTest.Env();
expect(globalErrors.install).toHaveBeenCalled();
});
});
describe('when constructed with suppressLoadErrors: true', function() {
it('does not install a global error handler until execute is called', function() {
var globalErrors = jasmine.createSpyObj('globalErrors', ['install', 'pushListener', 'popListener']);
var globalErrors = jasmine.createSpyObj('globalErrors', [
'install',
'uninstall',
'pushListener',
'popListener'
]);
spyOn(jasmineUnderTest, 'GlobalErrors').and.returnValue(globalErrors);
env = new jasmineUnderTest.Env({suppressLoadErrors: true});
env.cleanup_();
env = new jasmineUnderTest.Env({ suppressLoadErrors: true });
expect(globalErrors.install).not.toHaveBeenCalled();
env.execute();
expect(globalErrors.install).toHaveBeenCalled();
});
});
it('creates an expectationFactory that uses the current custom equality testers and object formatters', function(done) {
function customEqualityTester() {}
function customObjectFormatter() {}
function prettyPrinter() {}
var RealSpec = jasmineUnderTest.Spec,
specInstance,
expectationFactory;
spyOn(jasmineUnderTest, 'MatchersUtil');
spyOn(jasmineUnderTest, 'makePrettyPrinter').and.returnValue(prettyPrinter);
spyOn(jasmineUnderTest, 'Spec').and.callFake(function(options) {
expectationFactory = options.expectationFactory;
specInstance = new RealSpec(options);
return specInstance;
});
env.it('spec', function() {
env.addCustomEqualityTester(customEqualityTester);
env.addCustomObjectFormatter(customObjectFormatter);
expectationFactory('actual', specInstance);
});
env.addReporter({
jasmineDone: function() {
expect(jasmineUnderTest.makePrettyPrinter).toHaveBeenCalledWith([
customObjectFormatter
]);
expect(jasmineUnderTest.MatchersUtil).toHaveBeenCalledWith({
customTesters: [customEqualityTester],
pp: prettyPrinter
});
done();
}
});
env.execute();
});
it('creates an asyncExpectationFactory that uses the current custom equality testers and object formatters', function(done) {
function customEqualityTester() {}
function customObjectFormatter() {}
function prettyPrinter() {}
var RealSpec = jasmineUnderTest.Spec,
specInstance,
asyncExpectationFactory;
spyOn(jasmineUnderTest, 'MatchersUtil');
spyOn(jasmineUnderTest, 'makePrettyPrinter').and.returnValue(prettyPrinter);
spyOn(jasmineUnderTest, 'Spec').and.callFake(function(options) {
asyncExpectationFactory = options.asyncExpectationFactory;
specInstance = new RealSpec(options);
return specInstance;
});
env.it('spec', function() {
env.addCustomEqualityTester(customEqualityTester);
env.addCustomObjectFormatter(customObjectFormatter);
asyncExpectationFactory('actual', specInstance);
});
env.addReporter({
jasmineDone: function() {
expect(jasmineUnderTest.makePrettyPrinter).toHaveBeenCalledWith([
customObjectFormatter
]);
expect(jasmineUnderTest.MatchersUtil).toHaveBeenCalledWith({
customTesters: [customEqualityTester],
pp: prettyPrinter
});
done();
}
});
env.execute();
});
});

View File

@@ -1,5 +1,5 @@
describe("ExceptionFormatter", function() {
describe("#message", function() {
describe('ExceptionFormatter', function() {
describe('#message', function() {
it('formats Firefox exception messages', function() {
var sampleFirefoxException = {
fileName: 'foo.js',
@@ -10,7 +10,9 @@ describe("ExceptionFormatter", function() {
exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(sampleFirefoxException);
expect(message).toEqual('A Classic Mistake: you got your foo in my bar in foo.js (line 1978)');
expect(message).toEqual(
'A Classic Mistake: you got your foo in my bar in foo.js (line 1978)'
);
});
it('formats Webkit exception messages', function() {
@@ -23,7 +25,9 @@ describe("ExceptionFormatter", function() {
exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(sampleWebkitException);
expect(message).toEqual('A Classic Mistake: you got your foo in my bar in foo.js (line 1978)');
expect(message).toEqual(
'A Classic Mistake: you got your foo in my bar in foo.js (line 1978)'
);
});
it('formats V8 exception messages', function() {
@@ -37,27 +41,56 @@ describe("ExceptionFormatter", function() {
expect(message).toEqual('A Classic Mistake: you got your foo in my bar');
});
it("formats thrown exceptions that aren't errors", function() {
var thrown = "crazy error",
exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(thrown);
it('formats unnamed exceptions with message', function() {
var unnamedError = { message: 'This is an unnamed error message.' };
expect(message).toEqual("crazy error thrown");
var exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(unnamedError);
expect(message).toEqual('This is an unnamed error message.');
});
it('formats empty exceptions with toString format', function() {
var EmptyError = function() {};
EmptyError.prototype.toString = function() {
return '[EmptyError]';
};
var emptyError = new EmptyError();
var exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(emptyError);
expect(message).toEqual('[EmptyError] thrown');
});
it("formats thrown exceptions that aren't errors", function() {
var thrown = 'crazy error',
exceptionFormatter = new jasmineUnderTest.ExceptionFormatter(),
message = exceptionFormatter.message(thrown);
expect(message).toEqual('crazy error thrown');
});
});
describe("#stack", function() {
it("formats stack traces", function() {
describe('#stack', function() {
it('formats stack traces', function() {
var error;
try { throw new Error("an error") } catch(e) { error = e; }
try {
throw new Error('an error');
} catch (e) {
error = e;
}
expect(new jasmineUnderTest.ExceptionFormatter().stack(error)).toMatch(/ExceptionFormatterSpec\.js.*\d+/)
expect(new jasmineUnderTest.ExceptionFormatter().stack(error)).toMatch(
/ExceptionFormatterSpec\.js.*\d+/
);
});
it("filters Jasmine stack frames from V8 style traces", function() {
it('filters Jasmine stack frames from V8 style traces', function() {
var error = {
message: 'nope',
stack: 'Error: nope\n' +
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' +
@@ -67,16 +100,18 @@ describe("ExceptionFormatter", function() {
jasmineFile: 'http://localhost:8888/__jasmine__/jasmine.js'
});
var result = subject.stack(error);
expect(result).toEqual('Error: nope\n' +
expect(result).toEqual(
'Error: nope\n' +
' at fn1 (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n' +
' at <Jasmine>\n' +
' at fn4 (http://localhost:8888/__spec__/core/UtilSpec.js:110:19)'
);
});
it("filters Jamine stack frames from Webkit style traces", function() {
it('filters Jasmine stack frames from Webkit style traces', function() {
var error = {
stack: 'http://localhost:8888/__spec__/core/UtilSpec.js:115:28\n' +
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'
@@ -92,9 +127,13 @@ describe("ExceptionFormatter", function() {
);
});
it("filters Jasmine stack frames in this environment", function() {
it('filters Jasmine stack frames in this environment', function() {
var error, i;
try { throw new Error("an error"); } catch(e) { error = e; }
try {
throw new Error('an error');
} catch (e) {
error = e;
}
var subject = new jasmineUnderTest.ExceptionFormatter({
jasmineFile: jasmine.util.jasmineFile()
});
@@ -114,9 +153,14 @@ describe("ExceptionFormatter", function() {
}
});
it("handles multiline error messages in this environment", function() {
var error, i, msg = "an error\nwith two lines";
try { throw new Error(msg); } catch(e) { error = e; }
it('handles multiline error messages in this environment', function() {
var error,
msg = 'an error\nwith two lines';
try {
throw new Error(msg);
} catch (e) {
error = e;
}
if (error.stack.indexOf(msg) === -1) {
pending("Stack traces don't have messages in this environment");
@@ -133,19 +177,22 @@ describe("ExceptionFormatter", function() {
expect(lines[3]).toMatch(/<Jasmine>/);
});
it("returns null if no Error provided", function() {
it('returns null if no Error provided', function() {
expect(new jasmineUnderTest.ExceptionFormatter().stack()).toBeNull();
});
it("includes error properties in stack", function() {
it('includes error properties in stack', function() {
var error;
try { throw new Error("an error") } catch(e) { error = e; }
try {
throw new Error('an error');
} catch (e) {
error = e;
}
error.someProperty = 'hello there';
var result = new jasmineUnderTest.ExceptionFormatter().stack(error);
expect(result).toMatch(/error properties:.*someProperty.*hello there/);
});
});
});

View File

@@ -5,13 +5,23 @@ describe('Exceptions:', function() {
env = new jasmineUnderTest.Env();
});
afterEach(function() {
env.cleanup_();
});
it('should handle exceptions thrown, but continue', function(done) {
var secondTest = jasmine.createSpy('second test');
env.describe('Suite for handles exceptions', function () {
env.it('should be a test that fails because it throws an exception', function() {
throw new Error();
});
env.it('should be a passing test that runs after exceptions are thrown from a async test', secondTest);
env.describe('Suite for handles exceptions', function() {
env.it(
'should be a test that fails because it throws an exception',
function() {
throw new Error();
}
);
env.it(
'should be a passing test that runs after exceptions are thrown from a async test',
secondTest
);
});
var expectations = function() {
@@ -23,14 +33,14 @@ describe('Exceptions:', function() {
env.execute();
});
it("should handle exceptions thrown directly in top-level describe blocks and continue", function(done) {
var secondDescribe = jasmine.createSpy("second describe");
env.describe("a suite that throws an exception", function () {
env.it("is a test that should pass", function () {
it('should handle exceptions thrown directly in top-level describe blocks and continue', function(done) {
var secondDescribe = jasmine.createSpy('second describe');
env.describe('a suite that throws an exception', function() {
env.it('is a test that should pass', function() {
this.expect(true).toEqual(true);
});
throw new Error("top level error");
throw new Error('top level error');
});
env.describe("a suite that doesn't throw an exception", secondDescribe);
@@ -43,4 +53,3 @@ describe('Exceptions:', function() {
env.execute();
});
});

View File

@@ -0,0 +1,123 @@
describe('ExpectationFilterChain', function() {
describe('#addFilter', function() {
it('returns a new filter chain with the added filter', function() {
var first = jasmine.createSpy('first'),
second = jasmine.createSpy('second'),
orig = new jasmineUnderTest.ExpectationFilterChain({
modifyFailureMessage: first
}),
added = orig.addFilter({ selectComparisonFunc: second });
added.modifyFailureMessage();
expect(first).toHaveBeenCalled();
added.selectComparisonFunc();
expect(second).toHaveBeenCalled();
});
it('does not modify the original filter chain', function() {
var orig = new jasmineUnderTest.ExpectationFilterChain({}),
f = jasmine.createSpy('f');
orig.addFilter({ selectComparisonFunc: f });
orig.selectComparisonFunc();
expect(f).not.toHaveBeenCalled();
});
});
describe('#selectComparisonFunc', function() {
describe('When no filters have #selectComparisonFunc', function() {
it('returns undefined', function() {
var chain = new jasmineUnderTest.ExpectationFilterChain();
chain.addFilter({});
expect(chain.selectComparisonFunc()).toBeUndefined();
});
});
describe('When some filters have #selectComparisonFunc', function() {
it('calls the first filter that has #selectComparisonFunc', function() {
var first = jasmine.createSpy('first').and.returnValue('first'),
second = jasmine.createSpy('second').and.returnValue('second'),
chain = new jasmineUnderTest.ExpectationFilterChain()
.addFilter({ selectComparisonFunc: first })
.addFilter({ selectComparisonFunc: second }),
matcher = {},
result;
result = chain.selectComparisonFunc(matcher);
expect(first).toHaveBeenCalledWith(matcher);
expect(second).not.toHaveBeenCalled();
expect(result).toEqual('first');
});
});
});
describe('#buildFailureMessage', function() {
describe('When no filters have #buildFailureMessage', function() {
it('returns undefined', function() {
var chain = new jasmineUnderTest.ExpectationFilterChain();
chain.addFilter({});
expect(chain.buildFailureMessage()).toBeUndefined();
});
});
describe('When some filters have #buildFailureMessage', function() {
it('calls the first filter that has #buildFailureMessage', function() {
var first = jasmine.createSpy('first').and.returnValue('first'),
second = jasmine.createSpy('second').and.returnValue('second'),
chain = new jasmineUnderTest.ExpectationFilterChain()
.addFilter({ buildFailureMessage: first })
.addFilter({ buildFailureMessage: second }),
matcherResult = { pass: false },
matcherName = 'foo',
args = [],
matchersUtil = {},
result;
result = chain.buildFailureMessage(
matcherResult,
matcherName,
args,
matchersUtil
);
expect(first).toHaveBeenCalledWith(
matcherResult,
matcherName,
args,
matchersUtil
);
expect(second).not.toHaveBeenCalled();
expect(result).toEqual('first');
});
});
});
describe('#modifyFailureMessage', function() {
describe('When no filters have #modifyFailureMessage', function() {
it('returns the original message', function() {
var chain = new jasmineUnderTest.ExpectationFilterChain();
chain.addFilter({});
expect(chain.modifyFailureMessage('msg')).toEqual('msg');
});
});
describe('When some filters have #modifyFailureMessage', function() {
it('calls the first filter that has #modifyFailureMessage', function() {
var first = jasmine.createSpy('first').and.returnValue('first'),
second = jasmine.createSpy('second').and.returnValue('second'),
chain = new jasmineUnderTest.ExpectationFilterChain()
.addFilter({ modifyFailureMessage: first })
.addFilter({ modifyFailureMessage: second }),
result;
result = chain.modifyFailureMessage('original');
expect(first).toHaveBeenCalledWith('original');
expect(second).not.toHaveBeenCalled();
expect(result).toEqual('first');
});
});
});
});

View File

@@ -1,76 +1,126 @@
describe("buildExpectationResult", function() {
it("defaults to passed", function() {
var result = jasmineUnderTest.buildExpectationResult({passed: 'some-value'});
describe('buildExpectationResult', function() {
it('defaults to passed', function() {
var result = jasmineUnderTest.buildExpectationResult({
passed: 'some-value'
});
expect(result.passed).toBe('some-value');
});
it("message defaults to Passed for passing specs", function() {
var result = jasmineUnderTest.buildExpectationResult({passed: true, message: 'some-value'});
it('message defaults to Passed for passing specs', function() {
var result = jasmineUnderTest.buildExpectationResult({
passed: true,
message: 'some-value'
});
expect(result.message).toBe('Passed.');
});
it("message returns the message for failing expectations", function() {
var result = jasmineUnderTest.buildExpectationResult({passed: false, message: 'some-value'});
it('message returns the message for failing expectations', function() {
var result = jasmineUnderTest.buildExpectationResult({
passed: false,
message: 'some-value'
});
expect(result.message).toBe('some-value');
});
it("delegates message formatting to the provided formatter if there was an Error", function() {
var fakeError = {message: 'foo'},
messageFormatter = jasmine.createSpy("exception message formatter").and.returnValue(fakeError.message);
it('delegates message formatting to the provided formatter if there was an Error', function() {
var fakeError = { message: 'foo' },
messageFormatter = jasmine
.createSpy('exception message formatter')
.and.returnValue(fakeError.message);
var result = jasmineUnderTest.buildExpectationResult(
{
passed: false,
error: fakeError,
messageFormatter: messageFormatter
});
var result = jasmineUnderTest.buildExpectationResult({
passed: false,
error: fakeError,
messageFormatter: messageFormatter
});
expect(messageFormatter).toHaveBeenCalledWith(fakeError);
expect(result.message).toEqual('foo');
});
it("delegates stack formatting to the provided formatter if there was an Error", function() {
var fakeError = {stack: 'foo'},
stackFormatter = jasmine.createSpy("stack formatter").and.returnValue(fakeError.stack);
it('delegates stack formatting to the provided formatter if there was an Error', function() {
var fakeError = { stack: 'foo' },
stackFormatter = jasmine
.createSpy('stack formatter')
.and.returnValue(fakeError.stack);
var result = jasmineUnderTest.buildExpectationResult(
{
passed: false,
error: fakeError,
stackFormatter: stackFormatter
});
var result = jasmineUnderTest.buildExpectationResult({
passed: false,
error: fakeError,
stackFormatter: stackFormatter
});
expect(stackFormatter).toHaveBeenCalledWith(fakeError);
expect(result.stack).toEqual('foo');
});
it("delegates stack formatting to the provided formatter if there was a provided errorForStack", function() {
var fakeError = {stack: 'foo'},
stackFormatter = jasmine.createSpy("stack formatter").and.returnValue(fakeError.stack);
it('delegates stack formatting to the provided formatter if there was a provided errorForStack', function() {
var fakeError = { stack: 'foo' },
stackFormatter = jasmine
.createSpy('stack formatter')
.and.returnValue(fakeError.stack);
var result = jasmineUnderTest.buildExpectationResult(
{
passed: false,
errorForStack: fakeError,
stackFormatter: stackFormatter
});
var result = jasmineUnderTest.buildExpectationResult({
passed: false,
errorForStack: fakeError,
stackFormatter: stackFormatter
});
expect(stackFormatter).toHaveBeenCalledWith(fakeError);
expect(result.stack).toEqual('foo');
});
it("matcherName returns passed matcherName", function() {
var result = jasmineUnderTest.buildExpectationResult({matcherName: 'some-value'});
it('matcherName returns passed matcherName', function() {
var result = jasmineUnderTest.buildExpectationResult({
matcherName: 'some-value'
});
expect(result.matcherName).toBe('some-value');
});
it("expected returns passed expected", function() {
var result = jasmineUnderTest.buildExpectationResult({expected: 'some-value'});
it('expected returns passed expected', function() {
var result = jasmineUnderTest.buildExpectationResult({
expected: 'some-value'
});
expect(result.expected).toBe('some-value');
});
it("actual returns passed actual", function() {
var result = jasmineUnderTest.buildExpectationResult({actual: 'some-value'});
it('actual returns passed actual', function() {
var result = jasmineUnderTest.buildExpectationResult({
actual: 'some-value'
});
expect(result.actual).toBe('some-value');
});
it('handles nodejs assertions', function() {
if (typeof require === 'undefined') {
return;
}
var assert = require('assert');
var error;
var value = 8421;
var expectedValue = 'JasmineExpectationTestValue';
try {
assert.equal(value, expectedValue);
} catch (e) {
error = e;
}
expect(error.code).toEqual('ERR_ASSERTION');
expect(error.actual).toEqual(value);
expect(error.expected).toEqual(expectedValue);
expect(error.operator).toEqual('==');
var result = jasmineUnderTest.buildExpectationResult({
passed: false,
matcherName: '',
expected: '',
actual: '',
error: error
});
expect(result.code).toEqual('ERR_ASSERTION');
expect(result.actual).toEqual(value);
expect(result.expected).toEqual(expectedValue);
expect(result.matcherName).toEqual('assert ==');
});
});

View File

@@ -1,12 +1,12 @@
describe("Expectation", function() {
it("makes custom matchers available to this expectation", function() {
describe('Expectation', function() {
it('makes custom matchers available to this expectation', function() {
var matchers = {
toFoo: function() {},
toBar: function() {}
},
expectation;
expectation = new jasmineUnderTest.Expectation({
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers
});
@@ -14,7 +14,7 @@ describe("Expectation", function() {
expect(expectation.toBar).toBeDefined();
});
it(".addCoreMatchers makes matchers available to any expectation", function() {
it('.addCoreMatchers makes matchers available to any expectation', function() {
var coreMatchers = {
toQuux: function() {}
},
@@ -22,45 +22,48 @@ describe("Expectation", function() {
jasmineUnderTest.Expectation.addCoreMatchers(coreMatchers);
expectation = new jasmineUnderTest.Expectation({});
expectation = jasmineUnderTest.Expectation.factory({});
expect(expectation.toQuux).toBeDefined();
});
it("Factory builds an expectation/negative expectation", function() {
var builtExpectation = jasmineUnderTest.Expectation.Factory();
expect(builtExpectation instanceof jasmineUnderTest.Expectation).toBe(true);
expect(builtExpectation.not instanceof jasmineUnderTest.Expectation).toBe(true);
expect(builtExpectation.not.isNot).toBe(true);
});
it("wraps matchers's compare functions, passing in matcher dependencies", function() {
var fakeCompare = function() { return { pass: true }; },
matcherFactory = jasmine.createSpy("matcher").and.returnValue({ compare: fakeCompare }),
var fakeCompare = function() {
return { pass: true };
},
matcherFactory = jasmine
.createSpy('matcher')
.and.returnValue({ compare: fakeCompare }),
matchers = {
toFoo: matcherFactory
},
util = {},
matchersUtil = {
buildFailureMessage: jasmine.createSpy('buildFailureMessage')
},
customEqualityTesters = ['a'],
addExpectationResult = jasmine.createSpy("addExpectationResult"),
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation;
expectation = new jasmineUnderTest.Expectation({
util: util,
expectation = jasmineUnderTest.Expectation.factory({
matchersUtil: matchersUtil,
customMatchers: matchers,
customEqualityTesters: customEqualityTesters,
actual: "an actual",
actual: 'an actual',
addExpectationResult: addExpectationResult
});
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(matcherFactory).toHaveBeenCalledWith(util, customEqualityTesters)
expect(matcherFactory).toHaveBeenCalledWith(
matchersUtil,
customEqualityTesters
);
});
it("wraps matchers's compare functions, passing the actual and expected", function() {
var fakeCompare = jasmine.createSpy('fake-compare').and.returnValue({pass: true}),
var fakeCompare = jasmine
.createSpy('fake-compare')
.and.returnValue({ pass: true }),
matchers = {
toFoo: function() {
return {
@@ -68,260 +71,275 @@ describe("Expectation", function() {
};
}
},
util = {
matchersUtil = {
buildFailureMessage: jasmine.createSpy('buildFailureMessage')
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation;
expectation = new jasmineUnderTest.Expectation({
util: util,
expectation = jasmineUnderTest.Expectation.factory({
matchersUtil: matchersUtil,
customMatchers: matchers,
actual: "an actual",
actual: 'an actual',
addExpectationResult: addExpectationResult
});
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(fakeCompare).toHaveBeenCalledWith("an actual", "hello");
expect(fakeCompare).toHaveBeenCalledWith('an actual', 'hello');
});
it("reports a passing result to the spec when the comparison passes", function() {
it('reports a passing result to the spec when the comparison passes', function() {
var matchers = {
toFoo: function() {
return {
compare: function() { return { pass: true }; }
compare: function() {
return { pass: true };
}
};
}
},
util = {
matchersUtil = {
buildFailureMessage: jasmine.createSpy('buildFailureMessage')
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation;
expectation = new jasmineUnderTest.Expectation({
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
util: util,
actual: "an actual",
matchersUtil: matchersUtil,
actual: 'an actual',
addExpectationResult: addExpectationResult
});
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(true, {
matcherName: "toFoo",
matcherName: 'toFoo',
passed: true,
message: "",
message: '',
error: undefined,
expected: "hello",
actual: "an actual"
expected: 'hello',
actual: 'an actual',
errorForStack: undefined
});
});
it("reports a failing result to the spec when the comparison fails", function() {
it('reports a failing result to the spec when the comparison fails', function() {
var matchers = {
toFoo: function() {
return {
compare: function() { return { pass: false }; }
compare: function() {
return { pass: false };
}
};
}
},
util = {
buildFailureMessage: function() { return ""; }
matchersUtil = {
buildFailureMessage: function() {
return '';
}
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation;
expectation = new jasmineUnderTest.Expectation({
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
util: util,
actual: "an actual",
matchersUtil: matchersUtil,
actual: 'an actual',
addExpectationResult: addExpectationResult
});
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: "toFoo",
matcherName: 'toFoo',
passed: false,
expected: "hello",
actual: "an actual",
message: "",
error: undefined
expected: 'hello',
actual: 'an actual',
message: '',
error: undefined,
errorForStack: undefined
});
});
it("reports a failing result and a custom fail message to the spec when the comparison fails", function() {
it('reports a failing result and a custom fail message to the spec when the comparison fails', function() {
var matchers = {
toFoo: function() {
return {
compare: function() {
return {
pass: false,
message: "I am a custom message"
message: 'I am a custom message'
};
}
};
}
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation;
expectation = new jasmineUnderTest.Expectation({
actual: "an actual",
expectation = jasmineUnderTest.Expectation.factory({
actual: 'an actual',
customMatchers: matchers,
addExpectationResult: addExpectationResult
});
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: "toFoo",
matcherName: 'toFoo',
passed: false,
expected: "hello",
actual: "an actual",
message: "I am a custom message",
error: undefined
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message',
error: undefined,
errorForStack: undefined
});
});
it("reports a failing result with a custom fail message function to the spec when the comparison fails", function() {
it('reports a failing result with a custom fail message function to the spec when the comparison fails', function() {
var matchers = {
toFoo: function() {
return {
compare: function() {
return {
pass: false,
message: function() { return "I am a custom message"; }
message: function() {
return 'I am a custom message';
}
};
}
};
}
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation;
expectation = new jasmineUnderTest.Expectation({
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
actual: "an actual",
actual: 'an actual',
addExpectationResult: addExpectationResult
});
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: "toFoo",
matcherName: 'toFoo',
passed: false,
expected: "hello",
actual: "an actual",
message: "I am a custom message",
error: undefined
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message',
error: undefined,
errorForStack: undefined
});
});
it("reports a passing result to the spec when the comparison fails for a negative expectation", function() {
it('reports a passing result to the spec when the comparison fails for a negative expectation', function() {
var matchers = {
toFoo: function() {
return {
compare: function() { return { pass: false }; }
compare: function() {
return { pass: false };
}
};
}
},
util = {
buildFailureMessage: function() { return ""; }
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
actual = "an actual",
addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = 'an actual',
expectation;
expectation = new jasmineUnderTest.Expectation({
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
actual: "an actual",
addExpectationResult: addExpectationResult,
isNot: true
});
actual: 'an actual',
addExpectationResult: addExpectationResult
}).not;
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(true, {
matcherName: "toFoo",
matcherName: 'toFoo',
passed: true,
message: "",
message: '',
error: undefined,
expected: "hello",
actual: actual
});
});
it("reports a failing result to the spec when the comparison passes for a negative expectation", function() {
var matchers = {
toFoo: function() {
return {
compare: function() { return { pass: true }; }
};
}
},
util = {
buildFailureMessage: function() { return "default message"; }
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
actual = "an actual",
expectation;
expectation = new jasmineUnderTest.Expectation({
customMatchers: matchers,
actual: "an actual",
util: util,
addExpectationResult: addExpectationResult,
isNot: true
});
expectation.toFoo("hello");
expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: "toFoo",
passed: false,
expected: "hello",
expected: 'hello',
actual: actual,
message: "default message",
error: undefined
errorForStack: undefined
});
});
it("reports a failing result and a custom fail message to the spec when the comparison passes for a negative expectation", function() {
it('reports a failing result to the spec when the comparison passes for a negative expectation', function() {
var matchers = {
toFoo: function() {
return {
compare: function() {
return { pass: true };
}
};
}
},
matchersUtil = {
buildFailureMessage: function() {
return 'default message';
}
},
addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = 'an actual',
expectation;
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
actual: 'an actual',
matchersUtil: matchersUtil,
addExpectationResult: addExpectationResult
}).not;
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo',
passed: false,
expected: 'hello',
actual: actual,
message: 'default message',
error: undefined,
errorForStack: undefined
});
});
it('reports a failing result and a custom fail message to the spec when the comparison passes for a negative expectation', function() {
var matchers = {
toFoo: function() {
return {
compare: function() {
return {
pass: true,
message: "I am a custom message"
message: 'I am a custom message'
};
}
};
}
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
actual = "an actual",
addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = 'an actual',
expectation;
expectation = new jasmineUnderTest.Expectation({
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
actual: "an actual",
addExpectationResult: addExpectationResult,
isNot: true
});
actual: 'an actual',
addExpectationResult: addExpectationResult
}).not;
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: "toFoo",
matcherName: 'toFoo',
passed: false,
expected: "hello",
expected: 'hello',
actual: actual,
message: "I am a custom message",
error: undefined
message: 'I am a custom message',
error: undefined,
errorForStack: undefined
});
});
@@ -329,31 +347,35 @@ describe("Expectation", function() {
var matchers = {
toFoo: function() {
return {
compare: function() { return { pass: true }; },
negativeCompare: function() { return { pass: true }; }
compare: function() {
return { pass: true };
},
negativeCompare: function() {
return { pass: true };
}
};
}
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
actual = "an actual",
addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = 'an actual',
expectation;
expectation = new jasmineUnderTest.Expectation({
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
actual: "an actual",
addExpectationResult: addExpectationResult,
isNot: true
});
actual: 'an actual',
addExpectationResult: addExpectationResult
}).not;
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(true, {
matcherName: "toFoo",
matcherName: 'toFoo',
passed: true,
expected: "hello",
expected: 'hello',
actual: actual,
message: "",
error: undefined
message: '',
error: undefined,
errorForStack: undefined
});
});
@@ -361,7 +383,9 @@ describe("Expectation", function() {
var matchers = {
toFoo: function() {
return {
compare: function() { return { pass: true }; },
compare: function() {
return { pass: true };
},
negativeCompare: function() {
return {
pass: false,
@@ -371,64 +395,322 @@ describe("Expectation", function() {
};
}
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
actual = "an actual",
addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = 'an actual',
expectation;
expectation = new jasmineUnderTest.Expectation({
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
actual: "an actual",
addExpectationResult: addExpectationResult,
isNot: true
});
actual: 'an actual',
addExpectationResult: addExpectationResult
}).not;
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: "toFoo",
matcherName: 'toFoo',
passed: false,
expected: "hello",
expected: 'hello',
actual: actual,
message: "I'm a custom message",
error: undefined
error: undefined,
errorForStack: undefined
});
});
it("reports a custom error message to the spec", function() {
var customError = new Error("I am a custom error");
it('reports a custom error message to the spec', function() {
var customError = new Error('I am a custom error');
var matchers = {
toFoo: function() {
return {
compare: function() {
return {
pass: false,
message: "I am a custom message",
message: 'I am a custom message',
error: customError
};
}
};
}
},
addExpectationResult = jasmine.createSpy("addExpectationResult"),
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation;
expectation = new jasmineUnderTest.Expectation({
actual: "an actual",
expectation = jasmineUnderTest.Expectation.factory({
actual: 'an actual',
customMatchers: matchers,
addExpectationResult: addExpectationResult
});
expectation.toFoo("hello");
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: "toFoo",
matcherName: 'toFoo',
passed: false,
expected: "hello",
actual: "an actual",
message: "I am a custom message",
error: customError
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message',
error: customError,
errorForStack: undefined
});
});
});
it("reports a custom message to the spec when a 'not' comparison fails", function() {
var customError = new Error('I am a custom error');
var matchers = {
toFoo: function() {
return {
compare: function() {
return {
pass: true,
message: 'I am a custom message',
error: customError
};
}
};
}
},
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation;
expectation = jasmineUnderTest.Expectation.factory({
actual: 'an actual',
customMatchers: matchers,
addExpectationResult: addExpectationResult
}).not;
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo',
passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message',
error: customError,
errorForStack: undefined
});
});
it("reports a custom message func to the spec when a 'not' comparison fails", function() {
var customError = new Error('I am a custom error');
var matchers = {
toFoo: function() {
return {
compare: function() {
return {
pass: true,
message: function() {
return 'I am a custom message';
},
error: customError
};
}
};
}
},
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation;
expectation = jasmineUnderTest.Expectation.factory({
actual: 'an actual',
customMatchers: matchers,
addExpectationResult: addExpectationResult
}).not;
expectation.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(false, {
matcherName: 'toFoo',
passed: false,
expected: 'hello',
actual: 'an actual',
message: 'I am a custom message',
error: customError,
errorForStack: undefined
});
});
describe('#withContext', function() {
it('prepends the context to the generated failure message', function() {
var matchers = {
toFoo: function() {
return {
compare: function() {
return { pass: false };
}
};
}
},
matchersUtil = {
buildFailureMessage: function() {
return 'failure message';
}
},
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
matchersUtil: matchersUtil,
actual: 'an actual',
addExpectationResult: addExpectationResult
});
expectation.withContext('Some context').toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(
false,
jasmine.objectContaining({
message: 'Some context: failure message'
})
);
});
it('prepends the context to a custom failure message', function() {
var matchers = {
toFoo: function() {
return {
compare: function() {
return { pass: false, message: 'msg' };
}
};
}
},
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
actual: 'an actual',
addExpectationResult: addExpectationResult
});
expectation.withContext('Some context').toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(
false,
jasmine.objectContaining({
message: 'Some context: msg'
})
);
});
it('indents a multiline failure message', function() {
var matchers = {
toFoo: function() {
return {
compare: function() {
return { pass: false, message: 'a\nmultiline\nmessage' };
}
};
}
},
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
actual: 'an actual',
addExpectationResult: addExpectationResult
}),
actualMessage;
expectation.withContext('Some context').toFoo('hello');
actualMessage = addExpectationResult.calls.argsFor(0)[1].message;
expect(actualMessage).toEqual(
'Some context:\n a\n multiline\n message'
);
});
it('prepends the context to a custom failure message from a function', function() {
var matchers = {
toFoo: function() {
return {
compare: function() {
return {
pass: false,
message: function() {
return 'msg';
}
};
}
};
}
},
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
actual: 'an actual',
addExpectationResult: addExpectationResult
});
expectation.withContext('Some context').toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(
false,
jasmine.objectContaining({
message: 'Some context: msg'
})
);
});
it('works with #not', function() {
var matchers = {
toFoo: function() {
return {
compare: function() {
return { pass: true };
}
};
}
},
addExpectationResult = jasmine.createSpy('addExpectationResult'),
pp = jasmineUnderTest.makePrettyPrinter(),
expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers,
matchersUtil: new jasmineUnderTest.MatchersUtil({ pp: pp }),
actual: 'an actual',
addExpectationResult: addExpectationResult
});
expectation.withContext('Some context').not.toFoo();
expect(addExpectationResult).toHaveBeenCalledWith(
false,
jasmine.objectContaining({
message: "Some context: Expected 'an actual' not to foo."
})
);
});
it('works with #not and a custom message', function() {
var customError = new Error('I am a custom error');
var matchers = {
toFoo: function() {
return {
compare: function() {
return {
pass: true,
message: function() {
return 'I am a custom message';
},
error: customError
};
}
};
}
},
addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = jasmineUnderTest.Expectation.factory({
actual: 'an actual',
customMatchers: matchers,
addExpectationResult: addExpectationResult
});
expectation.withContext('Some context').not.toFoo('hello');
expect(addExpectationResult).toHaveBeenCalledWith(
false,
jasmine.objectContaining({
message: 'Some context: I am a custom message'
})
);
});
});
});

View File

@@ -1,8 +1,8 @@
describe("GlobalErrors", function() {
it("calls the added handler on error", function() {
describe('GlobalErrors', function() {
it('calls the added handler on error', function() {
var fakeGlobal = { onerror: null },
handler = jasmine.createSpy('errorHandler'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
handler = jasmine.createSpy('errorHandler'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
errors.install();
errors.pushListener(handler);
@@ -12,11 +12,31 @@ describe("GlobalErrors", function() {
expect(handler).toHaveBeenCalledWith('foo');
});
it("only calls the most recent handler", function() {
it('calls the global error handler with all parameters', function() {
var fakeGlobal = { onerror: null },
handler1 = jasmine.createSpy('errorHandler1'),
handler2 = jasmine.createSpy('errorHandler2'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
handler = jasmine.createSpy('errorHandler'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal),
fooError = new Error('foo');
errors.install();
errors.pushListener(handler);
fakeGlobal.onerror(fooError.message, 'foo.js', 1, 1, fooError);
expect(handler).toHaveBeenCalledWith(
fooError.message,
'foo.js',
1,
1,
fooError
);
});
it('only calls the most recent handler', function() {
var fakeGlobal = { onerror: null },
handler1 = jasmine.createSpy('errorHandler1'),
handler2 = jasmine.createSpy('errorHandler2'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
errors.install();
errors.pushListener(handler1);
@@ -28,11 +48,11 @@ describe("GlobalErrors", function() {
expect(handler2).toHaveBeenCalledWith('foo');
});
it("calls previous handlers when one is removed", function() {
it('calls previous handlers when one is removed', function() {
var fakeGlobal = { onerror: null },
handler1 = jasmine.createSpy('errorHandler1'),
handler2 = jasmine.createSpy('errorHandler2'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
handler1 = jasmine.createSpy('errorHandler1'),
handler2 = jasmine.createSpy('errorHandler2'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
errors.install();
errors.pushListener(handler1);
@@ -46,10 +66,10 @@ describe("GlobalErrors", function() {
expect(handler2).not.toHaveBeenCalled();
});
it("uninstalls itself, putting back a previous callback", function() {
it('uninstalls itself, putting back a previous callback', function() {
var originalCallback = jasmine.createSpy('error'),
fakeGlobal = { onerror: originalCallback },
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
fakeGlobal = { onerror: originalCallback },
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
expect(fakeGlobal.onerror).toBe(originalCallback);
@@ -62,10 +82,10 @@ describe("GlobalErrors", function() {
expect(fakeGlobal.onerror).toBe(originalCallback);
});
it("rethrows the original error when there is no handler", function() {
var fakeGlobal = { },
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal),
originalError = new Error('nope');
it('rethrows the original error when there is no handler', function() {
var fakeGlobal = {},
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal),
originalError = new Error('nope');
errors.install();
@@ -78,22 +98,31 @@ describe("GlobalErrors", function() {
errors.uninstall();
});
it("reports uncaughtException in node.js", function() {
it('reports uncaughtException in node.js', function() {
var fakeGlobal = {
process: {
on: jasmine.createSpy('process.on'),
removeListener: jasmine.createSpy('process.removeListener'),
listeners: jasmine.createSpy('process.listeners').and.returnValue(['foo']),
removeAllListeners: jasmine.createSpy('process.removeAllListeners')
}
},
handler = jasmine.createSpy('errorHandler'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
process: {
on: jasmine.createSpy('process.on'),
removeListener: jasmine.createSpy('process.removeListener'),
listeners: jasmine
.createSpy('process.listeners')
.and.returnValue(['foo']),
removeAllListeners: jasmine.createSpy('process.removeAllListeners')
}
},
handler = jasmine.createSpy('errorHandler'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
errors.install();
expect(fakeGlobal.process.on).toHaveBeenCalledWith('uncaughtException', jasmine.any(Function));
expect(fakeGlobal.process.listeners).toHaveBeenCalledWith('uncaughtException');
expect(fakeGlobal.process.removeAllListeners).toHaveBeenCalledWith('uncaughtException');
expect(fakeGlobal.process.on).toHaveBeenCalledWith(
'uncaughtException',
jasmine.any(Function)
);
expect(fakeGlobal.process.listeners).toHaveBeenCalledWith(
'uncaughtException'
);
expect(fakeGlobal.process.removeAllListeners).toHaveBeenCalledWith(
'uncaughtException'
);
errors.pushListener(handler);
@@ -101,40 +130,143 @@ describe("GlobalErrors", function() {
addedListener(new Error('bar'));
expect(handler).toHaveBeenCalledWith(new Error('bar'));
expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe(
'Uncaught exception: Error: bar'
);
errors.uninstall();
expect(fakeGlobal.process.removeListener).toHaveBeenCalledWith('uncaughtException', addedListener);
expect(fakeGlobal.process.on).toHaveBeenCalledWith('uncaughtException', 'foo');
expect(fakeGlobal.process.removeListener).toHaveBeenCalledWith(
'uncaughtException',
addedListener
);
expect(fakeGlobal.process.on).toHaveBeenCalledWith(
'uncaughtException',
'foo'
);
});
it("reports unhandledRejection in node.js", function() {
it('reports unhandledRejection in node.js', function() {
var fakeGlobal = {
process: {
on: jasmine.createSpy('process.on'),
removeListener: jasmine.createSpy('process.removeListener'),
listeners: jasmine.createSpy('process.listeners').and.returnValue(['foo']),
removeAllListeners: jasmine.createSpy('process.removeAllListeners')
}
},
handler = jasmine.createSpy('errorHandler'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
process: {
on: jasmine.createSpy('process.on'),
removeListener: jasmine.createSpy('process.removeListener'),
listeners: jasmine
.createSpy('process.listeners')
.and.returnValue(['foo']),
removeAllListeners: jasmine.createSpy('process.removeAllListeners')
}
},
handler = jasmine.createSpy('errorHandler'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
errors.install();
expect(fakeGlobal.process.on).toHaveBeenCalledWith('unhandledRejection', jasmine.any(Function));
expect(fakeGlobal.process.listeners).toHaveBeenCalledWith('unhandledRejection');
expect(fakeGlobal.process.removeAllListeners).toHaveBeenCalledWith('unhandledRejection');
expect(fakeGlobal.process.on).toHaveBeenCalledWith(
'unhandledRejection',
jasmine.any(Function)
);
expect(fakeGlobal.process.listeners).toHaveBeenCalledWith(
'unhandledRejection'
);
expect(fakeGlobal.process.removeAllListeners).toHaveBeenCalledWith(
'unhandledRejection'
);
errors.pushListener(handler);
var addedListener = fakeGlobal.process.on.calls.argsFor(0)[1];
var addedListener = fakeGlobal.process.on.calls.argsFor(1)[1];
addedListener(new Error('bar'));
expect(handler).toHaveBeenCalledWith(new Error('bar'));
expect(handler.calls.argsFor(0)[0].jasmineMessage).toBe(
'Unhandled promise rejection: Error: bar'
);
errors.uninstall();
expect(fakeGlobal.process.removeListener).toHaveBeenCalledWith('unhandledRejection', addedListener);
expect(fakeGlobal.process.on).toHaveBeenCalledWith('unhandledRejection', 'foo');
expect(fakeGlobal.process.removeListener).toHaveBeenCalledWith(
'unhandledRejection',
addedListener
);
expect(fakeGlobal.process.on).toHaveBeenCalledWith(
'unhandledRejection',
'foo'
);
});
describe('Reporting unhandled promise rejections in the browser', function() {
it('subscribes and unsubscribes from the unhandledrejection event', function() {
var fakeGlobal = jasmine.createSpyObj('globalErrors', [
'addEventListener',
'removeEventListener',
'onerror'
]),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
errors.install();
expect(fakeGlobal.addEventListener).toHaveBeenCalledWith(
'unhandledrejection',
jasmine.any(Function)
);
var addedListener = fakeGlobal.addEventListener.calls.argsFor(0)[1];
errors.uninstall();
expect(fakeGlobal.removeEventListener).toHaveBeenCalledWith(
'unhandledrejection',
addedListener
);
});
it('reports rejections whose reason is a string', function() {
var fakeGlobal = jasmine.createSpyObj('globalErrors', [
'addEventListener',
'removeEventListener',
'onerror'
]),
handler = jasmine.createSpy('errorHandler'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
errors.install();
errors.pushListener(handler);
var addedListener = fakeGlobal.addEventListener.calls.argsFor(0)[1];
addedListener({ reason: 'nope' });
expect(handler).toHaveBeenCalledWith('Unhandled promise rejection: nope');
});
it('reports rejections whose reason is an Error', function() {
var fakeGlobal = jasmine.createSpyObj('globalErrors', [
'addEventListener',
'removeEventListener',
'onerror'
]),
handler = jasmine.createSpy('errorHandler'),
errors = new jasmineUnderTest.GlobalErrors(fakeGlobal);
errors.install();
errors.pushListener(handler);
var addedListener = fakeGlobal.addEventListener.calls.argsFor(0)[1];
var reason;
try {
// Throwing ensures that we get a stack property in all browsers
throw new Error('bar');
} catch (e) {
reason = e;
}
addedListener({ reason: reason });
expect(handler).toHaveBeenCalledWith(
jasmine.objectContaining({
jasmineMessage: 'Unhandled promise rejection: Error: bar',
message: reason.message,
stack: reason.stack
})
);
});
});
});

View File

@@ -1,87 +1,5 @@
xdescribe('JsApiReporter (integration specs)', function() {
describe('results', function() {
var reporter, spec1, spec2;
var env;
var suite, nestedSuite, nestedSpec;
beforeEach(function() {
env = new jasmineUnderTest.Env();
suite = env.describe("top-level suite", function() {
spec1 = env.it("spec 1", function() {
this.expect(true).toEqual(true);
});
spec2 = env.it("spec 2", function() {
this.expect(true).toEqual(false);
});
nestedSuite = env.describe("nested suite", function() {
nestedSpec = env.it("nested spec", function() {
expect(true).toEqual(true);
});
});
});
reporter = new jasmineUnderTest.JsApiReporter({});
env.addReporter(reporter);
env.execute();
});
it('results() should return a hash of all results, indexed by spec id', function() {
var expectedSpec1Results = {
result: "passed"
},
expectedSpec2Results = {
result: "failed"
};
expect(reporter.results()[spec1.id].result).toEqual('passed');
expect(reporter.results()[spec2.id].result).toEqual('failed');
});
it("should return nested suites as children of their parents", function() {
expect(reporter.suites()).toEqual([
{ id: 0, name: 'top-level suite', type: 'suite',
children: [
{ id: 0, name: 'spec 1', type: 'spec', children: [ ] },
{ id: 1, name: 'spec 2', type: 'spec', children: [ ] },
{ id: 1, name: 'nested suite', type: 'suite',
children: [
{ id: 2, name: 'nested spec', type: 'spec', children: [ ] }
]
},
]
}
]);
});
describe("#summarizeResult_", function() {
it("should summarize a passing result", function() {
var result = reporter.results()[spec1.id];
var summarizedResult = reporter.summarizeResult_(result);
expect(summarizedResult.result).toEqual('passed');
expect(summarizedResult.messages.length).toEqual(0);
});
it("should have a stack trace for failing specs", function() {
var result = reporter.results()[spec2.id];
var summarizedResult = reporter.summarizeResult_(result);
expect(summarizedResult.result).toEqual('failed');
expect(summarizedResult.messages[0].trace.stack).toEqual(result.messages[0].trace.stack);
});
});
});
});
describe("JsApiReporter", function() {
it("knows when a full environment is started", function() {
describe('JsApiReporter', function() {
it('knows when a full environment is started', function() {
var reporter = new jasmineUnderTest.JsApiReporter({});
expect(reporter.started).toBe(false);
@@ -93,7 +11,7 @@ describe("JsApiReporter", function() {
expect(reporter.finished).toBe(false);
});
it("knows when a full environment is done", function() {
it('knows when a full environment is done', function() {
var reporter = new jasmineUnderTest.JsApiReporter({});
expect(reporter.started).toBe(false);
@@ -127,58 +45,60 @@ describe("JsApiReporter", function() {
expect(reporter.status()).toEqual('done');
});
it("tracks a suite", function() {
it('tracks a suite', function() {
var reporter = new jasmineUnderTest.JsApiReporter({});
reporter.suiteStarted({
id: 123,
description: "A suite"
description: 'A suite'
});
var suites = reporter.suites();
expect(suites).toEqual({123: {id: 123, description: "A suite"}});
expect(suites).toEqual({ 123: { id: 123, description: 'A suite' } });
reporter.suiteDone({
id: 123,
description: "A suite",
description: 'A suite',
status: 'passed'
});
expect(suites).toEqual({123: {id: 123, description: "A suite", status: 'passed'}});
expect(suites).toEqual({
123: { id: 123, description: 'A suite', status: 'passed' }
});
});
describe("#specResults", function() {
describe('#specResults', function() {
var reporter, specResult1, specResult2;
beforeEach(function() {
reporter = new jasmineUnderTest.JsApiReporter({});
specResult1 = {
id: 1,
description: "A spec"
description: 'A spec'
};
specResult2 = {
id: 2,
description: "Another spec"
description: 'Another spec'
};
reporter.specDone(specResult1);
reporter.specDone(specResult2);
});
it("should return a slice of results", function() {
it('should return a slice of results', function() {
expect(reporter.specResults(0, 1)).toEqual([specResult1]);
expect(reporter.specResults(1, 1)).toEqual([specResult2]);
});
describe("when the results do not exist", function() {
it("should return a slice of shorter length", function() {
describe('when the results do not exist', function() {
it('should return a slice of shorter length', function() {
expect(reporter.specResults(0, 3)).toEqual([specResult1, specResult2]);
expect(reporter.specResults(2, 3)).toEqual([]);
});
});
});
describe("#suiteResults", function(){
describe('#suiteResults', function() {
var reporter, suiteResult1, suiteResult2;
beforeEach(function() {
reporter = new jasmineUnderTest.JsApiReporter({});
@@ -200,37 +120,37 @@ describe("JsApiReporter", function() {
reporter.suiteDone(suiteResult2);
});
it('should not include suite starts', function(){
expect(reporter.suiteResults(0,3).length).toEqual(2);
it('should not include suite starts', function() {
expect(reporter.suiteResults(0, 3).length).toEqual(2);
});
it("should return a slice of results", function() {
it('should return a slice of results', function() {
expect(reporter.suiteResults(0, 1)).toEqual([suiteResult1]);
expect(reporter.suiteResults(1, 1)).toEqual([suiteResult2]);
});
it("returns nothing for out of bounds indicies", function() {
it('returns nothing for out of bounds indices', function() {
expect(reporter.suiteResults(0, 3)).toEqual([suiteResult1, suiteResult2]);
expect(reporter.suiteResults(2, 3)).toEqual([]);
});
});
describe("#executionTime", function() {
it("should start the timer when jasmine starts", function() {
describe('#executionTime', function() {
it('should start the timer when jasmine starts', function() {
var timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']),
reporter = new jasmineUnderTest.JsApiReporter({
timer: timerSpy
});
reporter = new jasmineUnderTest.JsApiReporter({
timer: timerSpy
});
reporter.jasmineStarted();
expect(timerSpy.start).toHaveBeenCalled();
});
it("should return the time it took the specs to run, in ms", function() {
it('should return the time it took the specs to run, in ms', function() {
var timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']),
reporter = new jasmineUnderTest.JsApiReporter({
timer: timerSpy
});
reporter = new jasmineUnderTest.JsApiReporter({
timer: timerSpy
});
timerSpy.elapsed.and.returnValue(1000);
reporter.jasmineDone();
@@ -238,11 +158,11 @@ describe("JsApiReporter", function() {
});
describe("when the specs haven't finished being run", function() {
it("should return undefined", function() {
it('should return undefined', function() {
var timerSpy = jasmine.createSpyObj('timer', ['start', 'elapsed']),
reporter = new jasmineUnderTest.JsApiReporter({
timer: timerSpy
});
reporter = new jasmineUnderTest.JsApiReporter({
timer: timerSpy
});
expect(reporter.executionTime()).toBeUndefined();
});
@@ -252,8 +172,8 @@ describe("JsApiReporter", function() {
describe('#runDetails', function() {
it('should have details about the run', function() {
var reporter = new jasmineUnderTest.JsApiReporter({});
reporter.jasmineDone({some: {run: 'details'}});
expect(reporter.runDetails).toEqual({some: {run: 'details'}});
reporter.jasmineDone({ some: { run: 'details' } });
expect(reporter.runDetails).toEqual({ some: { run: 'details' } });
});
});
});

View File

@@ -1,5 +1,5 @@
describe("FakeDate", function() {
it("does not fail if no global date is found", function() {
describe('FakeDate', function() {
it('does not fail if no global date is found', function() {
var fakeGlobal = {},
mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
@@ -10,11 +10,11 @@ describe("FakeDate", function() {
}).not.toThrow();
});
it("replaces the global Date when it is installed", function() {
var globalDate = jasmine.createSpy("global Date").and.callFake(function() {
it('replaces the global Date when it is installed', function() {
var globalDate = jasmine.createSpy('global Date').and.callFake(function() {
return {
getTime: function() {}
}
};
}),
fakeGlobal = { Date: globalDate },
mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
@@ -25,11 +25,11 @@ describe("FakeDate", function() {
expect(fakeGlobal.Date).not.toEqual(globalDate);
});
it("replaces the global Date on uninstall", function() {
var globalDate = jasmine.createSpy("global Date").and.callFake(function() {
it('replaces the global Date on uninstall', function() {
var globalDate = jasmine.createSpy('global Date').and.callFake(function() {
return {
getTime: function() {}
}
};
}),
fakeGlobal = { Date: globalDate },
mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
@@ -40,13 +40,13 @@ describe("FakeDate", function() {
expect(fakeGlobal.Date).toEqual(globalDate);
});
it("takes the current time as the base when installing without parameters", function() {
var globalDate = jasmine.createSpy("global Date").and.callFake(function() {
it('takes the current time as the base when installing without parameters', function() {
var globalDate = jasmine.createSpy('global Date').and.callFake(function() {
return {
getTime: function() {
return 1000;
}
}
};
}),
fakeGlobal = { Date: globalDate },
mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
@@ -58,7 +58,7 @@ describe("FakeDate", function() {
expect(globalDate).toHaveBeenCalledWith(1000);
});
it("can accept a date as time base when installing", function() {
it('can accept a date as time base when installing', function() {
var fakeGlobal = { Date: Date },
mockDate = new jasmineUnderTest.MockDate(fakeGlobal),
baseDate = new Date();
@@ -69,7 +69,7 @@ describe("FakeDate", function() {
expect(new fakeGlobal.Date().getTime()).toEqual(123);
});
it("makes real dates", function() {
it('makes real dates', function() {
var fakeGlobal = { Date: Date },
mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
@@ -78,13 +78,13 @@ describe("FakeDate", function() {
expect(new fakeGlobal.Date() instanceof fakeGlobal.Date).toBe(true);
});
it("fakes current time when using Date.now()", function() {
var globalDate = jasmine.createSpy("global Date").and.callFake(function() {
it('fakes current time when using Date.now()', function() {
var globalDate = jasmine.createSpy('global Date').and.callFake(function() {
return {
getTime: function() {
return 1000;
}
}
};
}),
fakeGlobal = { Date: globalDate };
@@ -97,28 +97,30 @@ describe("FakeDate", function() {
});
it("does not stub Date.now() if it doesn't already exist", function() {
var globalDate = jasmine.createSpy("global Date").and.callFake(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()");
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() {
it('makes time passes using tick', function() {
var globalDate = jasmine.createSpy('global Date').and.callFake(function() {
return {
getTime: function() {
return 1000;
}
}
};
}),
fakeGlobal = { Date: globalDate };
@@ -136,13 +138,13 @@ describe("FakeDate", function() {
expect(fakeGlobal.Date.now()).toEqual(2100);
});
it("allows to increase 0 milliseconds using tick", function() {
var globalDate = jasmine.createSpy("global Date").and.callFake(function() {
it('allows to increase 0 milliseconds using tick', function() {
var globalDate = jasmine.createSpy('global Date').and.callFake(function() {
return {
getTime: function() {
return 1000;
}
}
};
}),
fakeGlobal = { Date: globalDate };
@@ -158,14 +160,16 @@ describe("FakeDate", function() {
expect(fakeGlobal.Date.now()).toEqual(1000);
});
it("allows creation of a Date in a different time than the mocked time", function() {
it('allows creation of a Date in a different time than the mocked time', function() {
var fakeGlobal = { Date: Date },
mockDate = new jasmineUnderTest.MockDate(fakeGlobal);
mockDate.install();
var otherDate = new fakeGlobal.Date(2013, 9, 23, 0, 0, 1, 0);
expect(otherDate.getTime()).toEqual(new Date(2013, 9, 23, 0, 0, 1, 0).getTime());
expect(otherDate.getTime()).toEqual(
new Date(2013, 9, 23, 0, 0, 1, 0).getTime()
);
});
it("allows creation of a Date that isn't fully specified", function() {
@@ -189,7 +193,7 @@ describe("FakeDate", function() {
expect(otherDate.getTime()).toEqual(now);
});
it("copies all Date properties to the mocked date", function() {
it('copies all Date properties to the mocked date', function() {
var fakeGlobal = { Date: Date },
mockDate = new jasmineUnderTest.MockDate(fakeGlobal);

View File

@@ -1,144 +1,177 @@
describe("jasmineUnderTest.pp", function () {
it("should wrap strings in single quotes", function() {
expect(jasmineUnderTest.pp("some string")).toEqual("'some string'");
expect(jasmineUnderTest.pp("som' string")).toEqual("'som' string'");
describe('PrettyPrinter', function() {
it('should wrap strings in single quotes', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp('some string')).toEqual("'some string'");
expect(pp("som' string")).toEqual("'som' string'");
});
it("should stringify primitives properly", function() {
expect(jasmineUnderTest.pp(true)).toEqual("true");
expect(jasmineUnderTest.pp(false)).toEqual("false");
expect(jasmineUnderTest.pp(null)).toEqual("null");
expect(jasmineUnderTest.pp(jasmine.undefined)).toEqual("undefined");
expect(jasmineUnderTest.pp(3)).toEqual("3");
expect(jasmineUnderTest.pp(-3.14)).toEqual("-3.14");
expect(jasmineUnderTest.pp(-0)).toEqual("-0");
it('should stringify primitives properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(true)).toEqual('true');
expect(pp(false)).toEqual('false');
expect(pp(null)).toEqual('null');
expect(pp(jasmine.undefined)).toEqual('undefined');
expect(pp(3)).toEqual('3');
expect(pp(-3.14)).toEqual('-3.14');
expect(pp(-0)).toEqual('-0');
});
describe('stringify sets', function() {
it("should stringify sets properly", function() {
it('should stringify sets properly', function() {
jasmine.getEnv().requireFunctioningSets();
var set = new Set();
var set = new Set(); // eslint-disable-line compat/compat
set.add(1);
set.add(2);
expect(jasmineUnderTest.pp(set)).toEqual("Set( 1, 2 )");
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(set)).toEqual('Set( 1, 2 )');
});
it("should truncate sets with more elments than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH", 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();
var set = new Set(); // eslint-disable-line compat/compat
set.add('a');
set.add('b');
set.add('c');
expect(jasmineUnderTest.pp(set)).toEqual("Set( 'a', 'b', ... )");
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(set)).toEqual("Set( 'a', 'b', ... )");
} finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize;
}
})
});
});
describe('stringify maps', function() {
it("should stringify maps properly", function() {
it('should stringify maps properly', function() {
jasmine.getEnv().requireFunctioningMaps();
var map = new Map();
map.set(1,2);
expect(jasmineUnderTest.pp(map)).toEqual("Map( [ 1, 2 ] )");
var map = new Map(); // eslint-disable-line compat/compat
map.set(1, 2);
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(map)).toEqual('Map( [ 1, 2 ] )');
});
it("should truncate maps with more elments than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH", function() {
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();
map.set("a",1);
map.set("b",2);
map.set("c",3);
expect(jasmineUnderTest.pp(map)).toEqual("Map( [ 'a', 1 ], [ 'b', 2 ], ... )");
var map = new Map(); // eslint-disable-line compat/compat
map.set('a', 1);
map.set('b', 2);
map.set('c', 3);
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(map)).toEqual("Map( [ 'a', 1 ], [ 'b', 2 ], ... )");
} finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize;
}
})
});
});
describe('stringify arrays', function() {
it("should stringify arrays properly", function() {
expect(jasmineUnderTest.pp([1, 2])).toEqual("[ 1, 2 ]");
expect(jasmineUnderTest.pp([1, 'foo', {}, jasmine.undefined, null])).toEqual("[ 1, 'foo', Object({ }), undefined, null ]");
it('should stringify arrays properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp([1, 2])).toEqual('[ 1, 2 ]');
expect(pp([1, 'foo', {}, jasmine.undefined, null])).toEqual(
"[ 1, 'foo', Object({ }), undefined, null ]"
);
});
it("should truncate arrays that are longer than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH", function() {
it('should truncate arrays that are longer than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() {
var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH;
var array = [1, 2, 3];
var pp = jasmineUnderTest.makePrettyPrinter();
try {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2;
expect(jasmineUnderTest.pp(array)).toEqual("[ 1, 2, ... ]");
expect(pp(array)).toEqual('[ 1, 2, ... ]');
} finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength;
}
});
it("should stringify arrays with properties properly", function() {
it('should stringify arrays with properties properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var arr = [1, 2];
arr.foo = 'bar';
arr.baz = {};
expect(jasmineUnderTest.pp(arr)).toEqual("[ 1, 2, foo: 'bar', baz: Object({ }) ]");
expect(pp(arr)).toEqual("[ 1, 2, foo: 'bar', baz: Object({ }) ]");
});
it("should stringify empty arrays with properties properly", function() {
it('should stringify empty arrays with properties properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var empty = [];
empty.foo = 'bar';
empty.baz = {};
expect(jasmineUnderTest.pp(empty)).toEqual("[ foo: 'bar', baz: Object({ }) ]");
expect(pp(empty)).toEqual("[ foo: 'bar', baz: Object({ }) ]");
});
it("should stringify long arrays with properties properly", function() {
it('should stringify long arrays with properties properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH;
var long = [1,2,3];
var long = [1, 2, 3];
long.foo = 'bar';
long.baz = {};
try {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2;
expect(jasmineUnderTest.pp(long)).toEqual("[ 1, 2, ..., foo: 'bar', baz: Object({ }) ]");
expect(pp(long)).toEqual(
"[ 1, 2, ..., foo: 'bar', baz: Object({ }) ]"
);
} finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength;
}
});
it("should indicate circular array references", function() {
it('should indicate circular array references', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var array1 = [1, 2];
var array2 = [array1];
array1.push(array2);
expect(jasmineUnderTest.pp(array1)).toEqual("[ 1, 2, [ <circular reference: Array> ] ]");
expect(pp(array1)).toEqual('[ 1, 2, [ <circular reference: Array> ] ]');
});
it("should not indicate circular references incorrectly", function() {
var array = [ [1] ];
expect(jasmineUnderTest.pp(array)).toEqual("[ [ 1 ] ]");
it('should not indicate circular references incorrectly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var array = [[1]];
expect(pp(array)).toEqual('[ [ 1 ] ]');
});
});
it("should stringify objects properly", function() {
expect(jasmineUnderTest.pp({foo: 'bar'})).toEqual("Object({ foo: 'bar' })");
expect(jasmineUnderTest.pp({foo:'bar', baz:3, nullValue: null, undefinedValue: jasmine.undefined})).toEqual("Object({ foo: 'bar', baz: 3, nullValue: null, undefinedValue: undefined })");
expect(jasmineUnderTest.pp({foo: function () {
}, bar: [1, 2, 3]})).toEqual("Object({ foo: Function, bar: [ 1, 2, 3 ] })");
it('should stringify objects properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp({ foo: 'bar' })).toEqual("Object({ foo: 'bar' })");
expect(
pp({
foo: 'bar',
baz: 3,
nullValue: null,
undefinedValue: jasmine.undefined
})
).toEqual(
"Object({ foo: 'bar', baz: 3, nullValue: null, undefinedValue: undefined })"
);
expect(pp({ foo: function() {}, bar: [1, 2, 3] })).toEqual(
'Object({ foo: Function, bar: [ 1, 2, 3 ] })'
);
});
it("should truncate objects with too many keys", function () {
it('should stringify objects that almost look like DOM nodes', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp({ nodeType: 1 })).toEqual('Object({ nodeType: 1 })');
});
it('should truncate objects with too many keys', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH;
var long = {a: 1, b: 2, c: 3};
var long = { a: 1, b: 2, c: 3 };
try {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2;
expect(jasmineUnderTest.pp(long)).toEqual("Object({ a: 1, b: 2, ... })");
expect(pp(long)).toEqual('Object({ a: 1, b: 2, ... })');
} finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength;
}
@@ -155,86 +188,118 @@ describe("jasmineUnderTest.pp", function () {
}
}
it("should truncate outputs that are too long", function() {
var big = [
{ a: 1, b: "a long string" },
{}
];
it('should truncate outputs that are too long', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var big = [{ a: 1, b: 'a long string' }, {}];
withMaxChars(34, function() {
expect(jasmineUnderTest.pp(big)).toEqual("[ Object({ a: 1, b: 'a long st ...");
expect(pp(big)).toEqual("[ Object({ a: 1, b: 'a long st ...");
});
});
it("should not serialize more objects after hitting MAX_PRETTY_PRINT_CHARS", function() {
var a = { jasmineToString: function() { return 'object a'; } },
b = { jasmineToString: function() { return 'object b'; } },
c = { jasmineToString: jasmine.createSpy('c jasmineToString').and.returnValue('') },
d = { jasmineToString: jasmine.createSpy('d jasmineToString').and.returnValue('') };
it('should not serialize more objects after hitting MAX_PRETTY_PRINT_CHARS', function() {
var a = {
jasmineToString: function() {
return 'object a';
}
},
b = {
jasmineToString: function() {
return 'object b';
}
},
c = {
jasmineToString: jasmine
.createSpy('c jasmineToString')
.and.returnValue('')
},
d = {
jasmineToString: jasmine
.createSpy('d jasmineToString')
.and.returnValue('')
},
pp = jasmineUnderTest.makePrettyPrinter();
withMaxChars(30, function() {
jasmineUnderTest.pp([{a: a, b: b, c: c}, d]);
pp([{ a: a, b: b, c: c }, d]);
expect(c.jasmineToString).not.toHaveBeenCalled();
expect(d.jasmineToString).not.toHaveBeenCalled();
});
});
it("should print 'null' as the constructor of an object with its own constructor property", function() {
expect(jasmineUnderTest.pp({constructor: function() {}})).toContain("null({");
expect(jasmineUnderTest.pp({constructor: 'foo'})).toContain("null({");
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp({ constructor: function() {} })).toContain('null({');
expect(pp({ constructor: 'foo' })).toContain('null({');
});
it("should not include inherited properties when stringifying an object", function() {
it('should not include inherited properties when stringifying an object', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var SomeClass = function SomeClass() {};
SomeClass.prototype.foo = "inherited foo";
SomeClass.prototype.foo = 'inherited foo';
var instance = new SomeClass();
instance.bar = "my own bar";
expect(jasmineUnderTest.pp(instance)).toEqual("SomeClass({ bar: 'my own bar' })");
instance.bar = 'my own bar';
expect(pp(instance)).toEqual("SomeClass({ bar: 'my own bar' })");
});
it("should not recurse objects and arrays more deeply than jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH", function() {
it('should not recurse objects and arrays more deeply than jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var originalMaxDepth = jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH;
var nestedObject = { level1: { level2: { level3: { level4: "leaf" } } } };
var nestedArray = [1, [2, [3, [4, "leaf"]]]];
var nestedObject = { level1: { level2: { level3: { level4: 'leaf' } } } };
var nestedArray = [1, [2, [3, [4, 'leaf']]]];
try {
jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 2;
expect(jasmineUnderTest.pp(nestedObject)).toEqual("Object({ level1: Object({ level2: Object }) })");
expect(jasmineUnderTest.pp(nestedArray)).toEqual("[ 1, [ 2, Array ] ]");
expect(pp(nestedObject)).toEqual(
'Object({ level1: Object({ level2: Object }) })'
);
expect(pp(nestedArray)).toEqual('[ 1, [ 2, Array ] ]');
jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 3;
expect(jasmineUnderTest.pp(nestedObject)).toEqual("Object({ level1: Object({ level2: Object({ level3: Object }) }) })");
expect(jasmineUnderTest.pp(nestedArray)).toEqual("[ 1, [ 2, [ 3, Array ] ] ]");
expect(pp(nestedObject)).toEqual(
'Object({ level1: Object({ level2: Object({ level3: Object }) }) })'
);
expect(pp(nestedArray)).toEqual('[ 1, [ 2, [ 3, Array ] ] ]');
jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 4;
expect(jasmineUnderTest.pp(nestedObject)).toEqual("Object({ level1: Object({ level2: Object({ level3: Object({ level4: 'leaf' }) }) }) })");
expect(jasmineUnderTest.pp(nestedArray)).toEqual("[ 1, [ 2, [ 3, [ 4, 'leaf' ] ] ] ]");
expect(pp(nestedObject)).toEqual(
"Object({ level1: Object({ level2: Object({ level3: Object({ level4: 'leaf' }) }) }) })"
);
expect(pp(nestedArray)).toEqual("[ 1, [ 2, [ 3, [ 4, 'leaf' ] ] ] ]");
} finally {
jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = originalMaxDepth;
}
});
it("should stringify immutable circular objects", function(){
if(Object.freeze){
var frozenObject = {foo: {bar: 'baz'}};
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(jasmineUnderTest.pp(frozenObject)).toEqual("Object({ foo: Object({ bar: 'baz' }), circular: <circular reference: Object> })");
expect(pp(frozenObject)).toEqual(
"Object({ foo: Object({ bar: 'baz' }), circular: <circular reference: Object> })"
);
}
});
it("should stringify RegExp objects properly", function() {
expect(jasmineUnderTest.pp(/x|y|z/)).toEqual("/x|y|z/");
it('should stringify RegExp objects properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(/x|y|z/)).toEqual('/x|y|z/');
});
it("should indicate circular object references", function() {
var sampleValue = {foo: 'hello'};
it('should indicate circular object references', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var sampleValue = { foo: 'hello' };
sampleValue.nested = sampleValue;
expect(jasmineUnderTest.pp(sampleValue)).toEqual("Object({ foo: 'hello', nested: <circular reference: Object> })");
expect(pp(sampleValue)).toEqual(
"Object({ foo: 'hello', nested: <circular reference: Object> })"
);
});
it("should indicate getters on objects as such", function() {
var sampleValue = {id: 1};
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() {
@@ -242,91 +307,260 @@ describe("jasmineUnderTest.pp", function () {
});
}
if (sampleValue.__defineGetter__) {
expect(jasmineUnderTest.pp(sampleValue)).toEqual("Object({ id: 1, calculatedValue: <getter> })");
}
else {
expect(jasmineUnderTest.pp(sampleValue)).toEqual("Object({ id: 1 })");
expect(pp(sampleValue)).toEqual(
'Object({ id: 1, calculatedValue: <getter> })'
);
} else {
expect(pp(sampleValue)).toEqual('Object({ id: 1 })');
}
});
it('should not do HTML escaping of strings', function() {
expect(jasmineUnderTest.pp('some <b>html string</b> &', false)).toEqual('\'some <b>html string</b> &\'');
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp('some <b>html string</b> &', false)).toEqual(
"'some <b>html string</b> &'"
);
});
it("should abbreviate the global (usually window) object", function() {
expect(jasmineUnderTest.pp(jasmine.getGlobal())).toEqual("<global>");
it('should abbreviate the global (usually window) object', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(jasmine.getGlobal())).toEqual('<global>');
});
it("should stringify Date objects properly", function() {
it('should stringify Date objects properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var now = new Date();
expect(jasmineUnderTest.pp(now)).toEqual("Date(" + now.toString() + ")");
expect(pp(now)).toEqual('Date(' + now.toString() + ')');
});
it("should stringify spy objects properly", function() {
var TestObject = {
someFunction: function() {}
},
env = new jasmineUnderTest.Env();
describe('with a spy object', function() {
var env, pp;
var spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() {return [];},
createSpy: function(name, originalFn) {
return jasmineUnderTest.Spy(name, originalFn);
}
beforeEach(function() {
env = new jasmineUnderTest.Env();
pp = jasmineUnderTest.makePrettyPrinter();
});
spyRegistry.spyOn(TestObject, 'someFunction');
expect(jasmineUnderTest.pp(TestObject.someFunction)).toEqual("spy on someFunction");
afterEach(function() {
env.cleanup_();
});
expect(jasmineUnderTest.pp(env.createSpy("something"))).toEqual("spy on something");
it('should stringify spy objects properly', function() {
var TestObject = {
someFunction: function() {}
};
var spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() {
return [];
},
createSpy: function(name, originalFn) {
return jasmineUnderTest.Spy(name, originalFn);
}
});
spyRegistry.spyOn(TestObject, 'someFunction');
expect(pp(TestObject.someFunction)).toEqual('spy on someFunction');
expect(pp(env.createSpy('something'))).toEqual('spy on something');
});
it('should stringify spyOn toString properly', function() {
var TestObject = {
someFunction: function() {}
},
env = new jasmineUnderTest.Env(),
pp = jasmineUnderTest.makePrettyPrinter();
var spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() {
return [];
},
createSpy: function(name, originalFn) {
return jasmineUnderTest.Spy(name, originalFn);
}
});
spyRegistry.spyOn(TestObject, 'toString');
var testSpyObj = env.createSpyObj('TheClassName', ['toString']);
expect(pp(testSpyObj)).toEqual('spy on TheClassName.toString');
});
});
it("should stringify objects that implement jasmineToString", function () {
it('should stringify objects that implement jasmineToString', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var obj = {
jasmineToString: function () { return "strung"; }
jasmineToString: function() {
return 'strung';
}
};
expect(jasmineUnderTest.pp(obj)).toEqual("strung");
expect(pp(obj)).toEqual('strung');
});
it("should stringify objects that implement custom toString", function () {
it('should pass itself to jasmineToString', function() {
var pp = jasmineUnderTest.makePrettyPrinter([]);
var obj = {
toString: function () { return "my toString"; }
jasmineToString: jasmine.createSpy('jasmineToString').and.returnValue('')
};
expect(jasmineUnderTest.pp(obj)).toEqual("my toString");
pp(obj);
expect(obj.jasmineToString).toHaveBeenCalledWith(pp);
});
it('should stringify objects that implement custom toString', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var obj = {
toString: function() {
return 'my toString';
}
};
expect(pp(obj)).toEqual('my toString');
// Simulate object from another global context (e.g. an iframe or Web Worker) that does not actually have a custom
// toString despite obj.toString !== Object.prototype.toString
var objFromOtherContext = {
foo: 'bar',
toString: function () { return Object.prototype.toString.call(this); }
toString: function() {
return Object.prototype.toString.call(this);
}
};
expect(jasmineUnderTest.pp(objFromOtherContext)).toEqual("Object({ foo: 'bar', toString: Function })");
expect(pp(objFromOtherContext)).toEqual(
"Object({ foo: 'bar', toString: Function })"
);
});
it("should stringify objects have have a toString that isn't a function", function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var obj = {
toString: "foo"
toString: 'foo'
};
expect(jasmineUnderTest.pp(obj)).toEqual("Object({ toString: 'foo' })");
expect(pp(obj)).toEqual("Object({ toString: 'foo' })");
});
it("should stringify objects from anonymous constructors with custom toString", function () {
var MyAnonymousConstructor = (function() { return function () {}; })();
MyAnonymousConstructor.toString = function () { return ''; };
it('should stringify objects from anonymous constructors with custom toString', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var MyAnonymousConstructor = (function() {
return function() {};
})();
MyAnonymousConstructor.toString = function() {
return '';
};
var a = new MyAnonymousConstructor();
expect(jasmineUnderTest.pp(a)).toEqual("<anonymous>({ })");
expect(pp(a)).toEqual('<anonymous>({ })');
});
it("should handle objects with null prototype", function() {
it('should handle objects with null prototype', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var obj = Object.create(null);
obj.foo = 'bar';
expect(jasmineUnderTest.pp(obj)).toEqual("null({ foo: 'bar' })");
expect(pp(obj)).toEqual("null({ foo: 'bar' })");
});
it('should gracefully handle objects with invalid toString implementations', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var obj = {
foo: {
toString: function() {
// Invalid: toString returning a number
return 3;
}
},
bar: {
toString: function() {
// Really invalid: a nested bad toString().
return {
toString: function() {
return new Date();
}
};
}
},
// Valid: an actual number
baz: 3,
// Valid: an actual Error object
qux: new Error('bar'),
//
baddy: {
toString: function() {
throw new Error('I am a bad toString');
}
}
};
expect(pp(obj)).toEqual(
'Object({ foo: [object Number], bar: [object Object], baz: 3, qux: Error: bar, baddy: has-invalid-toString-method })'
);
});
describe('Custom object formatters', function() {
it('should use the first custom object formatter that does not return undefined', function() {
var customObjectFormatters = [
function(obj) {
return undefined;
},
function(obj) {
return '2nd: ' + obj.foo;
},
function(obj) {
return '3rd: ' + obj.foo;
}
],
pp = jasmineUnderTest.makePrettyPrinter(customObjectFormatters),
obj = { foo: 'bar' };
expect(pp(obj)).toEqual('2nd: bar');
});
it('should fall back to built in logic if all custom object formatters return undefined', function() {
var customObjectFormatters = [
function(obj) {
return undefined;
}
],
pp = jasmineUnderTest.makePrettyPrinter(customObjectFormatters),
obj = { foo: 'bar' };
expect(pp(obj)).toEqual("Object({ foo: 'bar' })");
});
});
describe('#customFormat_', function() {
it('should use the first custom object formatter that does not return undefined', function() {
var customObjectFormatters = [
function(obj) {
return undefined;
},
function(obj) {
return '2nd: ' + obj.foo;
},
function(obj) {
return '3rd: ' + obj.foo;
}
],
pp = jasmineUnderTest.makePrettyPrinter(customObjectFormatters),
obj = { foo: 'bar' };
expect(pp.customFormat_(obj)).toEqual('2nd: bar');
});
it('should return undefined if all custom object formatters return undefined', function() {
var customObjectFormatters = [
function(obj) {
return undefined;
}
],
pp = jasmineUnderTest.makePrettyPrinter(customObjectFormatters),
obj = { foo: 'bar' };
expect(pp.customFormat_(obj)).toBeUndefined();
});
});
});

View File

@@ -1,5 +1,4 @@
describe("QueueRunner", function() {
describe('QueueRunner', function() {
it("runs all the functions it's passed", function() {
var calls = [],
queueableFn1 = { fn: jasmine.createSpy('fn1') },
@@ -19,7 +18,7 @@ describe("QueueRunner", function() {
expect(calls).toEqual(['fn1', 'fn2']);
});
it("runs cleanup functions after the others", function() {
it('runs cleanup functions after the others', function() {
var calls = [],
queueableFn1 = { fn: jasmine.createSpy('fn1') },
queueableFn2 = { fn: jasmine.createSpy('fn2') },
@@ -41,12 +40,17 @@ describe("QueueRunner", function() {
it("calls each function with a consistent 'this'-- an empty object", function() {
var queueableFn1 = { fn: jasmine.createSpy('fn1') },
queueableFn2 = { fn: jasmine.createSpy('fn2') },
queueableFn3 = { fn: function(done) { asyncContext = this; done(); } },
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2, queueableFn3]
}),
asyncContext;
queueableFn2 = { fn: jasmine.createSpy('fn2') },
queueableFn3 = {
fn: function(done) {
asyncContext = this;
done();
}
},
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2, queueableFn3]
}),
asyncContext;
queueRunner.execute();
@@ -56,7 +60,7 @@ describe("QueueRunner", function() {
expect(asyncContext).toBe(context);
});
describe("with an asynchronous function", function() {
describe('with an asynchronous function', function() {
beforeEach(function() {
jasmine.clock().install();
});
@@ -65,7 +69,7 @@ describe("QueueRunner", function() {
jasmine.clock().uninstall();
});
it("supports asynchronous functions, only advancing to next function after a done() callback", function() {
it('supports asynchronous functions, only advancing to next function after a done() callback', function() {
//TODO: it would be nice if spy arity could match the fake, so we could do something like:
//createSpy('asyncfn').and.callFake(function(done) {});
@@ -73,18 +77,24 @@ describe("QueueRunner", function() {
beforeCallback = jasmine.createSpy('beforeCallback'),
fnCallback = jasmine.createSpy('fnCallback'),
afterCallback = jasmine.createSpy('afterCallback'),
queueableFn1 = { fn: function(done) {
beforeCallback();
setTimeout(done, 100);
} },
queueableFn2 = { fn: function(done) {
fnCallback();
setTimeout(done, 100);
} },
queueableFn3 = { fn: function(done) {
afterCallback();
setTimeout(done, 100);
} },
queueableFn1 = {
fn: function(done) {
beforeCallback();
setTimeout(done, 100);
}
},
queueableFn2 = {
fn: function(done) {
fnCallback();
setTimeout(done, 100);
}
},
queueableFn3 = {
fn: function(done) {
afterCallback();
setTimeout(done, 100);
}
},
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2, queueableFn3],
onComplete: onComplete
@@ -113,10 +123,14 @@ describe("QueueRunner", function() {
expect(onComplete).toHaveBeenCalled();
});
it("explicitly fails an async function with a provided fail function and moves to the next function", function() {
var queueableFn1 = { fn: function(done) {
setTimeout(function() { done.fail('foo'); }, 100);
} },
it('explicitly fails an async function with a provided fail function and moves to the next function', function() {
var queueableFn1 = {
fn: function(done) {
setTimeout(function() {
done.fail('foo');
}, 100);
}
},
queueableFn2 = { fn: jasmine.createSpy('fn2') },
failFn = jasmine.createSpy('fail'),
queueRunner = new jasmineUnderTest.QueueRunner({
@@ -135,11 +149,15 @@ describe("QueueRunner", function() {
expect(queueableFn2.fn).toHaveBeenCalled();
});
it("explicitly fails an async function when next is called with an Error and moves to the next function", function() {
it('explicitly fails an async function when next is called with an Error and moves to the next function', function() {
var err = new Error('foo'),
queueableFn1 = { fn: function(done) {
setTimeout(function() { done(err); }, 100);
} },
queueableFn1 = {
fn: function(done) {
setTimeout(function() {
done(err);
}, 100);
}
},
queueableFn2 = { fn: jasmine.createSpy('fn2') },
failFn = jasmine.createSpy('fail'),
queueRunner = new jasmineUnderTest.QueueRunner({
@@ -158,11 +176,15 @@ describe("QueueRunner", function() {
expect(queueableFn2.fn).toHaveBeenCalled();
});
it("does not cause an explicit fail if execution is being stopped", function() {
it('does not cause an explicit fail if execution is being stopped', function() {
var err = new jasmineUnderTest.StopExecutionError('foo'),
queueableFn1 = { fn: function(done) {
setTimeout(function() { done(err); }, 100);
} },
queueableFn1 = {
fn: function(done) {
setTimeout(function() {
done(err);
}, 100);
}
},
queueableFn2 = { fn: jasmine.createSpy('fn2') },
failFn = jasmine.createSpy('fail'),
queueRunner = new jasmineUnderTest.QueueRunner({
@@ -183,7 +205,7 @@ describe("QueueRunner", function() {
it("sets a timeout if requested for asynchronous functions so they don't go on forever", function() {
var timeout = 3,
beforeFn = { fn: function(done) { }, type: 'before', timeout: timeout },
beforeFn = { fn: function(done) {}, type: 'before', timeout: timeout },
queueableFn = { fn: jasmine.createSpy('fn'), type: 'queueable' },
onComplete = jasmine.createSpy('onComplete'),
onException = jasmine.createSpy('onException'),
@@ -203,15 +225,15 @@ describe("QueueRunner", function() {
expect(onComplete).toHaveBeenCalled();
});
it("by default does not set a timeout for asynchronous functions", function() {
var beforeFn = { fn: function(done) { } },
it('by default does not set a timeout for asynchronous functions', function() {
var beforeFn = { fn: function(done) {} },
queueableFn = { fn: jasmine.createSpy('fn') },
onComplete = jasmine.createSpy('onComplete'),
onException = jasmine.createSpy('onException'),
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [beforeFn, queueableFn],
onComplete: onComplete,
onException: onException,
onException: onException
});
queueRunner.execute();
@@ -224,8 +246,12 @@ describe("QueueRunner", function() {
expect(onComplete).not.toHaveBeenCalled();
});
it("clears the timeout when an async function throws an exception, to prevent additional exception reporting", function() {
var queueableFn = { fn: function(done) { throw new Error("error!"); } },
it('clears the timeout when an async function throws an exception, to prevent additional exception reporting', function() {
var queueableFn = {
fn: function(done) {
throw new Error('error!');
}
},
onComplete = jasmine.createSpy('onComplete'),
onException = jasmine.createSpy('onException'),
queueRunner = new jasmineUnderTest.QueueRunner({
@@ -243,8 +269,12 @@ describe("QueueRunner", function() {
expect(onException.calls.count()).toEqual(1);
});
it("clears the timeout when the done callback is called", function() {
var queueableFn = { fn: function(done) { done(); } },
it('clears the timeout when the done callback is called', function() {
var queueableFn = {
fn: function(done) {
done();
}
},
onComplete = jasmine.createSpy('onComplete'),
onException = jasmine.createSpy('onException'),
queueRunner = new jasmineUnderTest.QueueRunner({
@@ -262,8 +292,13 @@ describe("QueueRunner", function() {
expect(onException).not.toHaveBeenCalled();
});
it("only moves to the next spec the first time you call done", function() {
var queueableFn = { fn: function(done) {done(); done();} },
it('only moves to the next spec the first time you call done', function() {
var queueableFn = {
fn: function(done) {
done();
done();
}
},
nextQueueableFn = { fn: jasmine.createSpy('nextFn') },
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn]
@@ -274,27 +309,31 @@ describe("QueueRunner", function() {
expect(nextQueueableFn.fn.calls.count()).toEqual(1);
});
it("does not move to the next spec if done is called after an exception has ended the spec", function() {
var queueableFn = { fn: function(done) {
setTimeout(done, 1);
throw new Error('error!');
} },
nextQueueableFn = { fn: jasmine.createSpy('nextFn') },
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn]
});
it('does not move to the next spec if done is called after an exception has ended the spec', function() {
var queueableFn = {
fn: function(done) {
setTimeout(done, 1);
throw new Error('error!');
}
},
nextQueueableFn = { fn: jasmine.createSpy('nextFn') },
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn]
});
queueRunner.execute();
jasmine.clock().tick(1);
expect(nextQueueableFn.fn.calls.count()).toEqual(1);
});
it("should return a null when you call done", function () {
it('should return a null when you call done', function() {
// Some promises want handlers to return anything but undefined to help catch "forgotten returns".
var doneReturn,
queueableFn = { fn: function(done) {
doneReturn = done();
} },
queueableFn = {
fn: function(done) {
doneReturn = done();
}
},
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn]
});
@@ -303,24 +342,36 @@ describe("QueueRunner", function() {
expect(doneReturn).toBe(null);
});
it("continues running functions when an exception is thrown in async code without timing out", function() {
var queueableFn = { fn: function(done) { throwAsync(); }, timeout: 1 },
nextQueueableFn = { fn: jasmine.createSpy("nextFunction") },
it('continues running functions when an exception is thrown in async code without timing out', function() {
var queueableFn = {
fn: function(done) {
throwAsync();
},
timeout: 1
},
nextQueueableFn = { fn: jasmine.createSpy('nextFunction') },
onException = jasmine.createSpy('onException'),
globalErrors = { pushListener: jasmine.createSpy('pushListener'), popListener: jasmine.createSpy('popListener') },
globalErrors = {
pushListener: jasmine.createSpy('pushListener'),
popListener: jasmine.createSpy('popListener')
},
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn],
onException: onException,
globalErrors: globalErrors
}),
throwAsync = function() {
globalErrors.pushListener.calls.mostRecent().args[0](new Error('foo'));
globalErrors.pushListener.calls
.mostRecent()
.args[0](new Error('foo'));
jasmine.clock().tick(2);
};
nextQueueableFn.fn.and.callFake(function() {
// should remove the same function that was added
expect(globalErrors.popListener).toHaveBeenCalledWith(globalErrors.pushListener.calls.argsFor(1)[0]);
expect(globalErrors.popListener).toHaveBeenCalledWith(
globalErrors.pushListener.calls.argsFor(1)[0]
);
});
queueRunner.execute();
@@ -335,28 +386,37 @@ describe("QueueRunner", function() {
}
};
}
expect(onException).not.toHaveBeenCalledWith(errorWithMessage(/DEFAULT_TIMEOUT_INTERVAL/));
expect(onException).not.toHaveBeenCalledWith(
errorWithMessage(/DEFAULT_TIMEOUT_INTERVAL/)
);
expect(onException).toHaveBeenCalledWith(errorWithMessage(/^foo$/));
expect(nextQueueableFn.fn).toHaveBeenCalled();
});
it("handles exceptions thrown while waiting for the stack to clear", function() {
var queueableFn = { fn: function(done) { done() } },
global = {},
errorListeners = [],
globalErrors = {
pushListener: function(f) { errorListeners.push(f); },
popListener: function() { errorListeners.pop(); }
},
clearStack = jasmine.createSpy('clearStack'),
onException = jasmine.createSpy('onException'),
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn],
globalErrors: globalErrors,
clearStack: clearStack,
onException: onException
}),
error = new Error('nope');
it('handles exceptions thrown while waiting for the stack to clear', function() {
var queueableFn = {
fn: function(done) {
done();
}
},
errorListeners = [],
globalErrors = {
pushListener: function(f) {
errorListeners.push(f);
},
popListener: function() {
errorListeners.pop();
}
},
clearStack = jasmine.createSpy('clearStack'),
onException = jasmine.createSpy('onException'),
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn],
globalErrors: globalErrors,
clearStack: clearStack,
onException: onException
}),
error = new Error('nope');
queueRunner.execute();
jasmine.clock().tick();
@@ -368,7 +428,7 @@ describe("QueueRunner", function() {
});
});
describe("with a function that returns a promise", function() {
describe('with a function that returns a promise', function() {
function StubPromise() {}
StubPromise.prototype.then = function(resolve, reject) {
@@ -384,28 +444,32 @@ describe("QueueRunner", function() {
jasmine.clock().uninstall();
});
it("runs the function asynchronously, advancing once the promise is settled", function() {
it('runs the function asynchronously, advancing once the promise is settled', function() {
var onComplete = jasmine.createSpy('onComplete'),
fnCallback = jasmine.createSpy('fnCallback'),
fnCallback = jasmine.createSpy('fnCallback'),
p1 = new StubPromise(),
p2 = new StubPromise(),
queueableFn1 = { fn: function() {
setTimeout(function() {
p1.resolveHandler();
}, 100);
return p1;
} };
queueableFn2 = { fn: function() {
queueableFn1 = {
fn: function() {
setTimeout(function() {
p1.resolveHandler();
}, 100);
return p1;
}
};
(queueableFn2 = {
fn: function() {
fnCallback();
setTimeout(function() {
p2.resolveHandler();
}, 100);
return p2;
} },
queueRunner = new jasmineUnderTest.QueueRunner({
}
}),
(queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2],
onComplete: onComplete
});
}));
queueRunner.execute();
expect(fnCallback).not.toHaveBeenCalled();
@@ -421,16 +485,17 @@ describe("QueueRunner", function() {
expect(onComplete).toHaveBeenCalled();
});
it("handles a rejected promise like an unhandled exception", function() {
it('handles a rejected promise like an unhandled exception', function() {
var promise = new StubPromise(),
queueableFn1 = { fn: function() {
setTimeout(function() {
promise.rejectHandler('foo')
}, 100);
return promise;
} },
queueableFn1 = {
fn: function() {
setTimeout(function() {
promise.rejectHandler('foo');
}, 100);
return promise;
}
},
queueableFn2 = { fn: jasmine.createSpy('fn2') },
failFn = jasmine.createSpy('fail'),
onExceptionCallback = jasmine.createSpy('on exception callback'),
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn1, queueableFn2],
@@ -449,11 +514,39 @@ describe("QueueRunner", function() {
});
});
it("calls exception handlers when an exception is thrown in a fn", function() {
var queueableFn = { type: 'queueable',
fn: function() {
throw new Error('fake error');
} },
it('passes the error instance to exception handlers in HTML browsers', function() {
var error = new Error('fake error'),
onExceptionCallback = jasmine.createSpy('on exception callback'),
queueRunner = new jasmineUnderTest.QueueRunner({
onException: onExceptionCallback
});
queueRunner.execute();
queueRunner.handleFinalError(error.message, 'fake.js', 1, 1, error);
expect(onExceptionCallback).toHaveBeenCalledWith(error);
});
it('passes the first argument to exception handlers for compatibility', function() {
var error = new Error('fake error'),
onExceptionCallback = jasmine.createSpy('on exception callback'),
queueRunner = new jasmineUnderTest.QueueRunner({
onException: onExceptionCallback
});
queueRunner.execute();
queueRunner.handleFinalError(error.message);
expect(onExceptionCallback).toHaveBeenCalledWith(error.message);
});
it('calls exception handlers when an exception is thrown in a fn', function() {
var queueableFn = {
type: 'queueable',
fn: function() {
throw new Error('fake error');
}
},
onExceptionCallback = jasmine.createSpy('on exception callback'),
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn],
@@ -465,9 +558,13 @@ describe("QueueRunner", function() {
expect(onExceptionCallback).toHaveBeenCalledWith(jasmine.any(Error));
});
it("continues running the functions even after an exception is thrown in an async spec", function() {
var queueableFn = { fn: function(done) { throw new Error("error"); } },
nextQueueableFn = { fn: jasmine.createSpy("nextFunction") },
it('continues running the functions even after an exception is thrown in an async spec', function() {
var queueableFn = {
fn: function(done) {
throw new Error('error');
}
},
nextQueueableFn = { fn: jasmine.createSpy('nextFunction') },
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn]
});
@@ -476,12 +573,16 @@ describe("QueueRunner", function() {
expect(nextQueueableFn.fn).toHaveBeenCalled();
});
describe("When configured to complete on first error", function() {
it("skips to cleanup functions on the first exception", function() {
var queueableFn = { fn: function() { throw new Error("error"); } },
nextQueueableFn = { fn: jasmine.createSpy("nextFunction") },
cleanupFn = { fn: jasmine.createSpy("cleanup") },
onComplete = jasmine.createSpy("onComplete"),
describe('When configured to complete on first error', function() {
it('skips to cleanup functions on the first exception', function() {
var queueableFn = {
fn: function() {
throw new Error('error');
}
},
nextQueueableFn = { fn: jasmine.createSpy('nextFunction') },
cleanupFn = { fn: jasmine.createSpy('cleanup') },
onComplete = jasmine.createSpy('onComplete'),
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn],
cleanupFns: [cleanupFn],
@@ -492,13 +593,19 @@ describe("QueueRunner", function() {
queueRunner.execute();
expect(nextQueueableFn.fn).not.toHaveBeenCalled();
expect(cleanupFn.fn).toHaveBeenCalled();
expect(onComplete).toHaveBeenCalledWith(jasmine.any(jasmineUnderTest.StopExecutionError));
expect(onComplete).toHaveBeenCalledWith(
jasmine.any(jasmineUnderTest.StopExecutionError)
);
});
it("does not skip when a cleanup function throws", function() {
var queueableFn = { fn: function() { } },
cleanupFn1 = { fn: function() { throw new Error("error"); } },
cleanupFn2 = { fn: jasmine.createSpy("cleanupFn2") },
it('does not skip when a cleanup function throws', function() {
var queueableFn = { fn: function() {} },
cleanupFn1 = {
fn: function() {
throw new Error('error');
}
},
cleanupFn2 = { fn: jasmine.createSpy('cleanupFn2') },
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn],
cleanupFns: [cleanupFn1, cleanupFn2],
@@ -509,7 +616,7 @@ describe("QueueRunner", function() {
expect(cleanupFn2.fn).toHaveBeenCalled();
});
describe("with an asynchronous function", function() {
describe('with an asynchronous function', function() {
beforeEach(function() {
jasmine.clock().install();
});
@@ -518,21 +625,24 @@ describe("QueueRunner", function() {
jasmine.clock().uninstall();
});
it("skips to cleanup functions on the first exception", function() {
it('skips to cleanup functions on the first exception', function() {
var errorListeners = [],
queueableFn = { fn: function(done) {} },
nextQueueableFn = { fn: jasmine.createSpy('nextFunction') },
cleanupFn = { fn: jasmine.createSpy('cleanup') },
queueRunner = new jasmineUnderTest.QueueRunner({
globalErrors: {
pushListener: function(f) { errorListeners.push(f); },
popListener: function() { errorListeners.pop(); },
pushListener: function(f) {
errorListeners.push(f);
},
popListener: function() {
errorListeners.pop();
}
},
queueableFns: [queueableFn, nextQueueableFn],
cleanupFns: [cleanupFn],
completeOnFirstError: true,
});
completeOnFirstError: true
});
queueRunner.execute();
errorListeners[errorListeners.length - 1](new Error('error'));
@@ -540,17 +650,19 @@ describe("QueueRunner", function() {
expect(cleanupFn.fn).toHaveBeenCalled();
});
it("skips to cleanup functions when next.fail is called", function() {
var queueableFn = { fn: function(done) {
done.fail('nope');
} },
it('skips to cleanup functions when next.fail is called', function() {
var queueableFn = {
fn: function(done) {
done.fail('nope');
}
},
nextQueueableFn = { fn: jasmine.createSpy('nextFunction') },
cleanupFn = { fn: jasmine.createSpy('cleanup') },
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn],
cleanupFns: [cleanupFn],
completeOnFirstError: true,
});
completeOnFirstError: true
});
queueRunner.execute();
jasmine.clock().tick();
@@ -558,17 +670,19 @@ describe("QueueRunner", function() {
expect(cleanupFn.fn).toHaveBeenCalled();
});
it("skips to cleanup functions when next is called with an Error", function() {
var queueableFn = { fn: function(done) {
done(new Error('nope'));
} },
it('skips to cleanup functions when next is called with an Error', function() {
var queueableFn = {
fn: function(done) {
done(new Error('nope'));
}
},
nextQueueableFn = { fn: jasmine.createSpy('nextFunction') },
cleanupFn = { fn: jasmine.createSpy('cleanup') },
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [queueableFn, nextQueueableFn],
cleanupFns: [cleanupFn],
completeOnFirstError: true,
});
completeOnFirstError: true
});
queueRunner.execute();
jasmine.clock().tick();
@@ -578,7 +692,7 @@ describe("QueueRunner", function() {
});
});
it("calls a provided complete callback when done", function() {
it('calls a provided complete callback when done', function() {
var queueableFn = { fn: jasmine.createSpy('fn') },
completeCallback = jasmine.createSpy('completeCallback'),
queueRunner = new jasmineUnderTest.QueueRunner({
@@ -591,7 +705,7 @@ describe("QueueRunner", function() {
expect(completeCallback).toHaveBeenCalled();
});
describe("clearing the stack", function() {
describe('clearing the stack', function() {
beforeEach(function() {
jasmine.clock().install();
});
@@ -600,18 +714,24 @@ describe("QueueRunner", function() {
jasmine.clock().uninstall();
});
it("calls a provided stack clearing function when done", function() {
var asyncFn = { fn: function(done) { done() } },
afterFn = { fn: jasmine.createSpy('afterFn') },
completeCallback = jasmine.createSpy('completeCallback'),
clearStack = jasmine.createSpy('clearStack'),
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [asyncFn, afterFn],
clearStack: clearStack,
onComplete: completeCallback
});
it('calls a provided stack clearing function when done', function() {
var asyncFn = {
fn: function(done) {
done();
}
},
afterFn = { fn: jasmine.createSpy('afterFn') },
completeCallback = jasmine.createSpy('completeCallback'),
clearStack = jasmine.createSpy('clearStack'),
queueRunner = new jasmineUnderTest.QueueRunner({
queueableFns: [asyncFn, afterFn],
clearStack: clearStack,
onComplete: completeCallback
});
clearStack.and.callFake(function(fn) { fn(); });
clearStack.and.callFake(function(fn) {
fn();
});
queueRunner.execute();
jasmine.clock().tick();
@@ -633,9 +753,7 @@ describe("QueueRunner", function() {
});
it('runs the functions on the scope of a UserContext', function() {
var calls = [],
context;
var context;
this.fn.and.callFake(function() {
context = this;
});
@@ -659,8 +777,7 @@ describe("QueueRunner", function() {
});
it('runs the functions on the scope of a UserContext', function() {
var calls = [],
context;
var context;
this.fn.and.callFake(function() {
context = this;
});

View File

@@ -1,16 +1,22 @@
describe("ReportDispatcher", function() {
it("builds an interface of requested methods", function() {
var dispatcher = new jasmineUnderTest.ReportDispatcher(['foo', 'bar', 'baz']);
describe('ReportDispatcher', function() {
it('builds an interface of requested methods', function() {
var dispatcher = new jasmineUnderTest.ReportDispatcher([
'foo',
'bar',
'baz'
]);
expect(dispatcher.foo).toBeDefined();
expect(dispatcher.bar).toBeDefined();
expect(dispatcher.baz).toBeDefined();
});
it("dispatches requested methods to added reporters", function() {
it('dispatches requested methods to added reporters', function() {
var queueRunnerFactory = jasmine.createSpy('queueRunner'),
dispatcher = new jasmineUnderTest.ReportDispatcher(['foo', 'bar'], queueRunnerFactory),
dispatcher = new jasmineUnderTest.ReportDispatcher(
['foo', 'bar'],
queueRunnerFactory
),
reporter = jasmine.createSpyObj('reporter', ['foo', 'bar']),
anotherReporter = jasmine.createSpyObj('reporter', ['foo', 'bar']),
completeCallback = jasmine.createSpy('complete');
@@ -20,10 +26,15 @@ describe("ReportDispatcher", function() {
dispatcher.foo(123, 456, completeCallback);
expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({
queueableFns: [{fn: jasmine.any(Function)}, {fn: jasmine.any(Function)}],
isReporter: true
}));
expect(queueRunnerFactory).toHaveBeenCalledWith(
jasmine.objectContaining({
queueableFns: [
{ fn: jasmine.any(Function) },
{ fn: jasmine.any(Function) }
],
isReporter: true
})
);
var fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns;
fns[0].fn();
@@ -38,10 +49,15 @@ describe("ReportDispatcher", function() {
dispatcher.bar('a', 'b', completeCallback);
expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({
queueableFns: [{fn: jasmine.any(Function)}, {fn: jasmine.any(Function)}],
isReporter: true
}));
expect(queueRunnerFactory).toHaveBeenCalledWith(
jasmine.objectContaining({
queueableFns: [
{ fn: jasmine.any(Function) },
{ fn: jasmine.any(Function) }
],
isReporter: true
})
);
fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns;
fns[0].fn();
@@ -53,39 +69,52 @@ describe("ReportDispatcher", function() {
it("does not dispatch to a reporter if the reporter doesn't accept the method", function() {
var queueRunnerFactory = jasmine.createSpy('queueRunner'),
dispatcher = new jasmineUnderTest.ReportDispatcher(['foo'], queueRunnerFactory),
dispatcher = new jasmineUnderTest.ReportDispatcher(
['foo'],
queueRunnerFactory
),
reporter = jasmine.createSpyObj('reporter', ['baz']);
dispatcher.addReporter(reporter);
dispatcher.foo(123, 456);
expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({
queueableFns: []
}));
expect(queueRunnerFactory).toHaveBeenCalledWith(
jasmine.objectContaining({
queueableFns: []
})
);
});
it("allows providing a fallback reporter in case there's no other reporter", function() {
var queueRunnerFactory = jasmine.createSpy('queueRunner'),
dispatcher = new jasmineUnderTest.ReportDispatcher(['foo', 'bar'], queueRunnerFactory),
dispatcher = new jasmineUnderTest.ReportDispatcher(
['foo', 'bar'],
queueRunnerFactory
),
reporter = jasmine.createSpyObj('reporter', ['foo', 'bar']),
completeCallback = jasmine.createSpy('complete');
dispatcher.provideFallbackReporter(reporter);
dispatcher.foo(123, 456, completeCallback);
expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({
queueableFns: [{fn: jasmine.any(Function)}],
isReporter: true
}));
expect(queueRunnerFactory).toHaveBeenCalledWith(
jasmine.objectContaining({
queueableFns: [{ fn: jasmine.any(Function) }],
isReporter: true
})
);
var fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns;
fns[0].fn();
expect(reporter.foo).toHaveBeenCalledWith(123, 456);
});
it("does not call fallback reporting methods when another reporter is provided", function() {
it('does not call fallback reporting methods when another reporter is provided', function() {
var queueRunnerFactory = jasmine.createSpy('queueRunner'),
dispatcher = new jasmineUnderTest.ReportDispatcher(['foo', 'bar'], queueRunnerFactory),
dispatcher = new jasmineUnderTest.ReportDispatcher(
['foo', 'bar'],
queueRunnerFactory
),
reporter = jasmine.createSpyObj('reporter', ['foo', 'bar']),
fallbackReporter = jasmine.createSpyObj('otherReporter', ['foo', 'bar']),
completeCallback = jasmine.createSpy('complete');
@@ -94,10 +123,12 @@ describe("ReportDispatcher", function() {
dispatcher.addReporter(reporter);
dispatcher.foo(123, 456, completeCallback);
expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({
queueableFns: [{fn: jasmine.any(Function)}],
isReporter: true
}));
expect(queueRunnerFactory).toHaveBeenCalledWith(
jasmine.objectContaining({
queueableFns: [{ fn: jasmine.any(Function) }],
isReporter: true
})
);
var fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns;
fns[0].fn();
@@ -105,19 +136,24 @@ describe("ReportDispatcher", function() {
expect(fallbackReporter.foo).not.toHaveBeenCalledWith(123, 456);
});
it("allows registered reporters to be cleared", function() {
it('allows registered reporters to be cleared', function() {
var queueRunnerFactory = jasmine.createSpy('queueRunner'),
dispatcher = new jasmineUnderTest.ReportDispatcher(['foo', 'bar'], queueRunnerFactory),
reporter1 = jasmine.createSpyObj('reporter1', ['foo', 'bar']),
reporter2 = jasmine.createSpyObj('reporter2', ['foo', 'bar']),
dispatcher = new jasmineUnderTest.ReportDispatcher(
['foo', 'bar'],
queueRunnerFactory
),
reporter1 = jasmine.createSpyObj('reporter1', ['foo', 'bar']),
reporter2 = jasmine.createSpyObj('reporter2', ['foo', 'bar']),
completeCallback = jasmine.createSpy('complete');
dispatcher.addReporter(reporter1);
dispatcher.foo(123, completeCallback);
expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({
queueableFns: [{fn: jasmine.any(Function)}],
isReporter: true
}));
expect(queueRunnerFactory).toHaveBeenCalledWith(
jasmine.objectContaining({
queueableFns: [{ fn: jasmine.any(Function) }],
isReporter: true
})
);
var fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns;
fns[0].fn();
@@ -127,10 +163,12 @@ describe("ReportDispatcher", function() {
dispatcher.addReporter(reporter2);
dispatcher.bar(456, completeCallback);
expect(queueRunnerFactory).toHaveBeenCalledWith(jasmine.objectContaining({
queueableFns: [{fn: jasmine.any(Function)}],
isReporter: true
}));
expect(queueRunnerFactory).toHaveBeenCalledWith(
jasmine.objectContaining({
queueableFns: [{ fn: jasmine.any(Function) }],
isReporter: true
})
);
fns = queueRunnerFactory.calls.mostRecent().args[0].queueableFns;
fns[0].fn();

View File

@@ -1,25 +1,30 @@
describe("Spec", function() {
it("#isPendingSpecException returns true for a pending spec exception", function() {
describe('Spec', function() {
it('#isPendingSpecException returns true for a pending spec exception', function() {
var e = new Error(jasmineUnderTest.Spec.pendingSpecExceptionMessage);
expect(jasmineUnderTest.Spec.isPendingSpecException(e)).toBe(true);
});
it("#isPendingSpecException returns true for a pending spec exception (even when FF bug is present)", function() {
it('#isPendingSpecException returns true for a pending spec exception (even when FF bug is present)', function() {
var fakeError = {
toString: function() { return "Error: " + jasmineUnderTest.Spec.pendingSpecExceptionMessage; }
toString: function() {
return 'Error: ' + jasmineUnderTest.Spec.pendingSpecExceptionMessage;
}
};
expect(jasmineUnderTest.Spec.isPendingSpecException(fakeError)).toBe(true);
});
it("#isPendingSpecException returns true for a pending spec exception with a custom message", function() {
expect(jasmineUnderTest.Spec.isPendingSpecException(jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'foo')).toBe(true);
it('#isPendingSpecException returns true for a pending spec exception with a custom message', function() {
expect(
jasmineUnderTest.Spec.isPendingSpecException(
jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'foo'
)
).toBe(true);
});
it("#isPendingSpecException returns false for not a pending spec exception", function() {
var e = new Error("foo");
it('#isPendingSpecException returns false for not a pending spec exception', function() {
var e = new Error('foo');
expect(jasmineUnderTest.Spec.isPendingSpecException(e)).toBe(false);
});
@@ -28,7 +33,7 @@ describe("Spec", function() {
expect(jasmineUnderTest.Spec.isPendingSpecException(void 0)).toBe(false);
});
it("delegates execution to a QueueRunner", function() {
it('delegates execution to a QueueRunner', function() {
var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'),
spec = new jasmineUnderTest.Spec({
description: 'my test',
@@ -42,7 +47,7 @@ describe("Spec", function() {
expect(fakeQueueRunner).toHaveBeenCalled();
});
it("should call the start callback on execution", function() {
it('should call the start callback on execution', function() {
var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'),
startCallback = jasmine.createSpy('startCallback'),
spec = new jasmineUnderTest.Spec({
@@ -64,18 +69,22 @@ describe("Spec", function() {
expect(startCallback.calls.first().object).toEqual(spec);
});
it("should call the start callback on execution but before any befores are called", function() {
it('should call the start callback on execution but before any befores are called', function() {
var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'),
beforesWereCalled = false,
startCallback = jasmine.createSpy('start-callback').and.callFake(function() {
expect(beforesWereCalled).toBe(false);
}),
startCallback = jasmine
.createSpy('start-callback')
.and.callFake(function() {
expect(beforesWereCalled).toBe(false);
}),
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: function() {} },
beforeFns: function() {
return [function() {
beforesWereCalled = true
}]
return [
function() {
beforesWereCalled = true;
}
];
},
onStart: startCallback,
queueRunnerFactory: fakeQueueRunner
@@ -87,18 +96,20 @@ describe("Spec", function() {
expect(startCallback).toHaveBeenCalled();
});
it("provides all before fns and after fns to be run", function() {
it('provides all before fns and after fns to be run', function() {
var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'),
before = jasmine.createSpy('before'),
after = jasmine.createSpy('after'),
queueableFn = { fn: jasmine.createSpy('test body').and.callFake(function() {
expect(before).toHaveBeenCalled();
expect(after).not.toHaveBeenCalled();
}) },
queueableFn = {
fn: jasmine.createSpy('test body').and.callFake(function() {
expect(before).toHaveBeenCalled();
expect(after).not.toHaveBeenCalled();
})
},
spec = new jasmineUnderTest.Spec({
queueableFn: queueableFn,
beforeAndAfterFns: function() {
return {befores: [before], afters: [after]}
return { befores: [before], afters: [after] };
},
queueRunnerFactory: fakeQueueRunner
});
@@ -106,8 +117,12 @@ describe("Spec", function() {
spec.execute();
var options = fakeQueueRunner.calls.mostRecent().args[0];
expect(options.queueableFns).toEqual([{fn: jasmine.any(Function)}, before, queueableFn]);
expect(options.cleanupFns).toEqual([after, {fn: jasmine.any(Function)}]);
expect(options.queueableFns).toEqual([
{ fn: jasmine.any(Function) },
before,
queueableFn
]);
expect(options.cleanupFns).toEqual([after, { fn: jasmine.any(Function) }]);
});
it("tells the queue runner that it's a leaf node", function() {
@@ -115,21 +130,22 @@ describe("Spec", function() {
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: function() {} },
beforeAndAfterFns: function() {
return {befores: [], afters: []}
return { befores: [], afters: [] };
},
queueRunnerFactory: fakeQueueRunner
});
spec.execute();
expect(fakeQueueRunner).toHaveBeenCalledWith(jasmine.objectContaining({
isLeaf: true
}));
expect(fakeQueueRunner).toHaveBeenCalledWith(
jasmine.objectContaining({
isLeaf: true
})
);
});
it("is marked pending if created without a function body", function() {
it('is marked pending if created without a function body', function() {
var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'),
startCallback = jasmine.createSpy('startCallback'),
resultCallback = jasmine.createSpy('resultCallback'),
spec = new jasmineUnderTest.Spec({
@@ -142,13 +158,13 @@ describe("Spec", function() {
expect(spec.status()).toBe('pending');
});
it("can be excluded at execution time by a parent", function() {
it('can be excluded at execution time by a parent', function() {
var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'),
startCallback = jasmine.createSpy('startCallback'),
specBody = jasmine.createSpy('specBody'),
resultCallback = jasmine.createSpy('resultCallback'),
spec = new jasmineUnderTest.Spec({
onStart:startCallback,
onStart: startCallback,
queueableFn: { fn: specBody },
resultCallback: resultCallback,
queueRunnerFactory: fakeQueueRunner
@@ -156,11 +172,13 @@ describe("Spec", function() {
spec.execute('cally-back', true);
expect(fakeQueueRunner).toHaveBeenCalledWith(jasmine.objectContaining({
onComplete: jasmine.any(Function),
queueableFns: [{fn: jasmine.any(Function)}],
cleanupFns: [{fn: jasmine.any(Function)}]
}));
expect(fakeQueueRunner).toHaveBeenCalledWith(
jasmine.objectContaining({
onComplete: jasmine.any(Function),
queueableFns: [{ fn: jasmine.any(Function) }],
cleanupFns: [{ fn: jasmine.any(Function) }]
})
);
expect(specBody).not.toHaveBeenCalled();
var args = fakeQueueRunner.calls.mostRecent().args[0];
@@ -172,16 +190,16 @@ describe("Spec", function() {
expect(spec.result.status).toBe('excluded');
});
it("can be marked pending, but still calls callbacks when executed", function() {
it('can be marked pending, but still calls callbacks when executed', function() {
var fakeQueueRunner = jasmine.createSpy('fakeQueueRunner'),
startCallback = jasmine.createSpy('startCallback'),
resultCallback = jasmine.createSpy('resultCallback'),
spec = new jasmineUnderTest.Spec({
onStart: startCallback,
resultCallback: resultCallback,
description: "with a spec",
description: 'with a spec',
getSpecName: function() {
return "a suite with a spec"
return 'a suite with a spec';
},
queueRunnerFactory: fakeQueueRunner,
queueableFn: { fn: null }
@@ -199,25 +217,34 @@ describe("Spec", function() {
args.queueableFns[0].fn();
expect(startCallback).toHaveBeenCalled();
args.cleanupFns[0].fn('things');
expect(resultCallback).toHaveBeenCalledWith({
id: spec.id,
status: 'pending',
description: 'with a spec',
fullName: 'a suite with a spec',
failedExpectations: [],
passedExpectations: [],
deprecationWarnings: [],
pendingReason: ''
}, 'things');
expect(resultCallback).toHaveBeenCalledWith(
{
id: spec.id,
status: 'pending',
description: 'with a spec',
fullName: 'a suite with a spec',
failedExpectations: [],
passedExpectations: [],
deprecationWarnings: [],
pendingReason: '',
duration: jasmine.any(Number),
properties: null
},
'things'
);
});
it("should call the done callback on execution complete", function() {
it('should call the done callback on execution complete', function() {
var done = jasmine.createSpy('done callback'),
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: function() {} },
catchExceptions: function() { return false; },
catchExceptions: function() {
return false;
},
resultCallback: function() {},
queueRunnerFactory: function(attrs) { attrs.onComplete(); }
queueRunnerFactory: function(attrs) {
attrs.onComplete();
}
});
spec.execute(done);
@@ -225,11 +252,13 @@ describe("Spec", function() {
expect(done).toHaveBeenCalled();
});
it("should call the done callback with an error if the spec is failed", function() {
it('should call the done callback with an error if the spec is failed', function() {
var done = jasmine.createSpy('done callback'),
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: function() {} },
catchExceptions: function() { return false; },
catchExceptions: function() {
return false;
},
resultCallback: function() {},
queueRunnerFactory: function(attrs) {
spec.result.status = 'failed';
@@ -239,33 +268,87 @@ describe("Spec", function() {
spec.execute(done);
expect(done).toHaveBeenCalledWith(jasmine.any(jasmineUnderTest.StopExecutionError));
expect(done).toHaveBeenCalledWith(
jasmine.any(jasmineUnderTest.StopExecutionError)
);
});
it("#status returns passing by default", function() {
var spec = new jasmineUnderTest.Spec({queueableFn: { fn: jasmine.createSpy("spec body")} });
it('should report the duration of the test', function() {
var timer = jasmine.createSpyObj('timer', { start: null, elapsed: 77000 }),
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: jasmine.createSpy('spec body') },
catchExceptions: function() {
return false;
},
resultCallback: function(result) {
duration = result.duration;
},
queueRunnerFactory: function(config) {
config.queueableFns.forEach(function(qf) {
qf.fn();
});
config.cleanupFns.forEach(function(qf) {
qf.fn();
});
config.onComplete();
},
timer: timer
}),
duration = undefined;
spec.execute(function() {});
expect(duration).toBe(77000);
});
it('should report properties set during the test', function() {
var done = jasmine.createSpy('done callback'),
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: jasmine.createSpy('spec body') },
catchExceptions: function() {
return false;
},
resultCallback: function() {},
queueRunnerFactory: function(attrs) {
attrs.onComplete();
}
});
spec.setSpecProperty('a', 4);
spec.execute(done);
expect(spec.result.properties).toEqual({ a: 4 });
});
it('#status returns passing by default', function() {
var spec = new jasmineUnderTest.Spec({
queueableFn: { fn: jasmine.createSpy('spec body') }
});
expect(spec.status()).toBe('passed');
});
it("#status returns passed if all expectations in the spec have passed", function() {
var spec = new jasmineUnderTest.Spec({queueableFn: { fn: jasmine.createSpy("spec body")} });
it('#status returns passed if all expectations in the spec have passed', function() {
var spec = new jasmineUnderTest.Spec({
queueableFn: { fn: jasmine.createSpy('spec body') }
});
spec.addExpectationResult(true);
expect(spec.status()).toBe('passed');
});
it("#status returns failed if any expectations in the spec have failed", function() {
var spec = new jasmineUnderTest.Spec({queueableFn: { fn: jasmine.createSpy("spec body") } });
it('#status returns failed if any expectations in the spec have failed', function() {
var spec = new jasmineUnderTest.Spec({
queueableFn: { fn: jasmine.createSpy('spec body') }
});
spec.addExpectationResult(true);
spec.addExpectationResult(false);
expect(spec.status()).toBe('failed');
});
it("keeps track of passed and failed expectations", function() {
it('keeps track of passed and failed expectations', function() {
var fakeQueueRunner = jasmine.createSpy('queueRunner'),
resultCallback = jasmine.createSpy('resultCallback'),
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: jasmine.createSpy("spec body") },
expectationResultFactory: function (data) { return data; },
queueableFn: { fn: jasmine.createSpy('spec body') },
expectationResultFactory: function(data) {
return data;
},
queueRunnerFactory: fakeQueueRunner,
resultCallback: resultCallback
});
@@ -275,8 +358,12 @@ describe("Spec", function() {
spec.execute();
fakeQueueRunner.calls.mostRecent().args[0].cleanupFns[0].fn();
expect(resultCallback.calls.first().args[0].passedExpectations).toEqual(['expectation1']);
expect(resultCallback.calls.first().args[0].failedExpectations).toEqual(['expectation2']);
expect(resultCallback.calls.first().args[0].passedExpectations).toEqual([
'expectation1'
]);
expect(resultCallback.calls.first().args[0].failedExpectations).toEqual([
'expectation2'
]);
});
it("throws an ExpectationFailed error upon receiving a failed expectation when 'throwOnExpectationFailure' is set", function() {
@@ -284,7 +371,9 @@ describe("Spec", function() {
resultCallback = jasmine.createSpy('resultCallback'),
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: function() {} },
expectationResultFactory: function(data) { return data; },
expectationResultFactory: function(data) {
return data;
},
queueRunnerFactory: fakeQueueRunner,
resultCallback: resultCallback,
throwOnExpectationFailure: true
@@ -292,22 +381,30 @@ describe("Spec", function() {
spec.addExpectationResult(true, 'passed');
expect(function() {
spec.addExpectationResult(false, 'failed')
spec.addExpectationResult(false, 'failed');
}).toThrowError(jasmineUnderTest.errors.ExpectationFailed);
spec.execute();
fakeQueueRunner.calls.mostRecent().args[0].cleanupFns[0].fn();
expect(resultCallback.calls.first().args[0].passedExpectations).toEqual(['passed']);
expect(resultCallback.calls.first().args[0].failedExpectations).toEqual(['failed']);
expect(resultCallback.calls.first().args[0].passedExpectations).toEqual([
'passed'
]);
expect(resultCallback.calls.first().args[0].failedExpectations).toEqual([
'failed'
]);
});
it("does not throw an ExpectationFailed error when handling an error", function() {
it('does not throw an ExpectationFailed error when handling an error', function() {
var resultCallback = jasmine.createSpy('resultCallback'),
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: function() {} },
expectationResultFactory: function(data) { return data; },
queueRunnerFactory: function(attrs) { attrs.onComplete(); },
expectationResultFactory: function(data) {
return data;
},
queueRunnerFactory: function(attrs) {
attrs.onComplete();
},
resultCallback: resultCallback,
throwOnExpectationFailure: true
});
@@ -315,8 +412,10 @@ describe("Spec", function() {
spec.onException('failing exception');
});
it("can return its full name", function() {
var specNameSpy = jasmine.createSpy('specNameSpy').and.returnValue('expected val');
it('can return its full name', function() {
var specNameSpy = jasmine
.createSpy('specNameSpy')
.and.returnValue('expected val');
var spec = new jasmineUnderTest.Spec({
getSpecName: specNameSpy,
@@ -327,48 +426,57 @@ describe("Spec", function() {
expect(specNameSpy.calls.mostRecent().args[0].id).toEqual(spec.id);
});
describe("when a spec is marked pending during execution", function() {
it("should mark the spec as pending", function() {
describe('when a spec is marked pending during execution', function() {
it('should mark the spec as pending', function() {
var fakeQueueRunner = function(opts) {
opts.onException(new Error(jasmineUnderTest.Spec.pendingSpecExceptionMessage));
opts.onException(
new Error(jasmineUnderTest.Spec.pendingSpecExceptionMessage)
);
},
spec = new jasmineUnderTest.Spec({
description: 'my test',
id: 'some-id',
queueableFn: { fn: function() { } },
queueableFn: { fn: function() {} },
queueRunnerFactory: fakeQueueRunner
});
spec.execute();
expect(spec.status()).toEqual("pending");
expect(spec.status()).toEqual('pending');
expect(spec.result.pendingReason).toEqual('');
});
it("should set the pendingReason", function() {
it('should set the pendingReason', function() {
var fakeQueueRunner = function(opts) {
opts.onException(new Error(jasmineUnderTest.Spec.pendingSpecExceptionMessage + 'custom message'));
opts.onException(
new Error(
jasmineUnderTest.Spec.pendingSpecExceptionMessage +
'custom message'
)
);
},
spec = new jasmineUnderTest.Spec({
description: 'my test',
id: 'some-id',
queueableFn: { fn: function() { } },
queueableFn: { fn: function() {} },
queueRunnerFactory: fakeQueueRunner
});
spec.execute();
expect(spec.status()).toEqual("pending");
expect(spec.status()).toEqual('pending');
expect(spec.result.pendingReason).toEqual('custom message');
});
});
it("should log a failure when handling an exception", function() {
it('should log a failure when handling an exception', function() {
var fakeQueueRunner = jasmine.createSpy('queueRunner'),
resultCallback = jasmine.createSpy('resultCallback'),
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: function() {} },
expectationResultFactory: function(data) { return data; },
expectationResultFactory: function(data) {
return data;
},
queueRunnerFactory: fakeQueueRunner,
resultCallback: resultCallback
});
@@ -378,21 +486,25 @@ describe("Spec", function() {
var args = fakeQueueRunner.calls.mostRecent().args[0];
args.cleanupFns[0].fn();
expect(resultCallback.calls.first().args[0].failedExpectations).toEqual([{
error: 'foo',
matcherName: '',
passed: false,
expected: '',
actual: ''
}]);
expect(resultCallback.calls.first().args[0].failedExpectations).toEqual([
{
error: 'foo',
matcherName: '',
passed: false,
expected: '',
actual: ''
}
]);
});
it("should not log an additional failure when handling an ExpectationFailed error", function() {
it('should not log an additional failure when handling an ExpectationFailed error', function() {
var fakeQueueRunner = jasmine.createSpy('queueRunner'),
resultCallback = jasmine.createSpy('resultCallback'),
spec = new jasmineUnderTest.Spec({
queueableFn: { fn: function() {} },
expectationResultFactory: function(data) { return data; },
expectationResultFactory: function(data) {
return data;
},
queueRunnerFactory: fakeQueueRunner,
resultCallback: resultCallback
});

View File

@@ -1,33 +1,35 @@
describe("SpyRegistry", function() {
describe('SpyRegistry', function() {
function createSpy(name, originalFn) {
return jasmineUnderTest.Spy(name, originalFn);
}
describe("#spyOn", function() {
it("checks for the existence of the object", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy});
describe('#spyOn', function() {
it('checks for the existence of the object', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy
});
expect(function() {
spyRegistry.spyOn(void 0, 'pants');
}).toThrowError(/could not find an object/);
});
it("checks that a method name was passed", function() {
it('checks that a method name was passed', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
expect(function() {
spyRegistry.spyOn(subject);
}).toThrowError(/No method name supplied/);
expect(function() {
spyRegistry.spyOn(subject);
}).toThrowError(/No method name supplied/);
});
it("checks that the object is not `null`", function() {
it('checks that the object is not `null`', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry();
expect(function() {
spyRegistry.spyOn(null, 'pants');
}).toThrowError(/could not find an object/);
});
it("checks that the method name is not `null`", function() {
it('checks that the method name is not `null`', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
@@ -36,7 +38,7 @@ describe("SpyRegistry", function() {
}).toThrowError(/No method name supplied/);
});
it("checks for the existence of the method", function() {
it('checks for the existence of the method', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
@@ -45,10 +47,12 @@ describe("SpyRegistry", function() {
}).toThrowError(/method does not exist/);
});
it("checks if it has already been spied upon", function() {
it('checks if it has already been spied upon', function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { return spies; },
currentSpies: function() {
return spies;
},
createSpy: createSpy
}),
subject = { spiedFunc: function() {} };
@@ -60,7 +64,7 @@ describe("SpyRegistry", function() {
}).toThrowError(/has already been spied upon/);
});
it("checks if it can be spied upon", function() {
it('checks if it can be spied upon', function() {
var scope = {};
function myFunc() {
@@ -74,7 +78,11 @@ describe("SpyRegistry", function() {
});
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({currentSpies: function() { return spies; }}),
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() {
return spies;
}
}),
subject = { spiedFunc: scope.myFunc };
expect(function() {
@@ -86,35 +94,43 @@ describe("SpyRegistry", function() {
}).not.toThrowError(/is not declared writable or has no setter/);
});
it("overrides the method on the object and returns the spy", function() {
it('overrides the method on the object and returns the spy', function() {
var originalFunctionWasCalled = false,
spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy}),
subject = { spiedFunc: function() { originalFunctionWasCalled = true; } };
spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy
}),
subject = {
spiedFunc: function() {
originalFunctionWasCalled = true;
}
};
var spy = spyRegistry.spyOn(subject, 'spiedFunc');
expect(subject.spiedFunc).toEqual(spy);
subject.spiedFunc();
expect(originalFunctionWasCalled).toBe(false);
});
});
describe("#spyOnProperty", function() {
it("checks for the existence of the object", function() {
describe('#spyOnProperty', function() {
it('checks for the existence of the object', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry();
expect(function() {
spyRegistry.spyOnProperty(void 0, 'pants');
}).toThrowError(/could not find an object/);
});
it("checks that a property name was passed", function() {
it('checks that a property name was passed', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
expect(function() {
spyRegistry.spyOnProperty(subject);
}).toThrowError(/No property name supplied/);
expect(function() {
spyRegistry.spyOnProperty(subject);
}).toThrowError(/No property name supplied/);
});
it("checks for the existence of the method", function() {
it('checks for the existence of the method', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
@@ -123,12 +139,14 @@ describe("SpyRegistry", function() {
}).toThrowError(/property does not exist/);
});
it("checks for the existence of access type", function() {
it('checks for the existence of access type', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
Object.defineProperty(subject, 'pants', {
get: function() { return 1; },
get: function() {
return 1;
},
configurable: true
});
@@ -137,23 +155,7 @@ describe("SpyRegistry", function() {
}).toThrowError(/does not have access type/);
});
it("checks if it has already been spied upon", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy}),
subject = {};
Object.defineProperty(subject, 'spiedProp', {
get: function() { return 1; },
configurable: true
});
spyRegistry.spyOnProperty(subject, 'spiedProp');
expect(function() {
spyRegistry.spyOnProperty(subject, 'spiedProp');
}).toThrowError(/has already been spied upon/);
});
it("checks if it can be spied upon", function() {
it('checks if it can be spied upon', function() {
var subject = {};
Object.defineProperty(subject, 'myProp', {
@@ -176,57 +178,117 @@ describe("SpyRegistry", function() {
}).not.toThrowError(/is not declared configurable/);
});
it("overrides the property getter on the object and returns the spy", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy}),
it('overrides the property getter on the object and returns the spy', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy
}),
subject = {},
returnValue = 1;
Object.defineProperty(subject, 'spiedProperty', {
get: function() { return returnValue; },
get: function() {
return returnValue;
},
configurable: true
});
expect(subject.spiedProperty).toEqual(returnValue);
var spy = spyRegistry.spyOnProperty(subject, 'spiedProperty');
var getter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty').get;
var getter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty')
.get;
expect(getter).toEqual(spy);
expect(subject.spiedProperty).toBeUndefined();
});
it("overrides the property setter on the object and returns the spy", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: createSpy}),
it('overrides the property setter on the object and returns the spy', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy
}),
subject = {},
returnValue = 1;
Object.defineProperty(subject, 'spiedProperty', {
get: function() { return returnValue; },
get: function() {
return returnValue;
},
set: function() {},
configurable: true
});
var spy = spyRegistry.spyOnProperty(subject, 'spiedProperty', 'set');
var setter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty').set;
var setter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty')
.set;
expect(subject.spiedProperty).toEqual(returnValue);
expect(setter).toEqual(spy);
});
describe('when the property is already spied upon', function() {
it('throws an error if respy is not allowed', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy
}),
subject = {};
Object.defineProperty(subject, 'spiedProp', {
get: function() {
return 1;
},
configurable: true
});
spyRegistry.spyOnProperty(subject, 'spiedProp');
expect(function() {
spyRegistry.spyOnProperty(subject, 'spiedProp');
}).toThrowError(/spiedProp#get has already been spied upon/);
});
it('returns the original spy if respy is allowed', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: createSpy
}),
subject = {};
spyRegistry.allowRespy(true);
Object.defineProperty(subject, 'spiedProp', {
get: function() {
return 1;
},
configurable: true
});
var originalSpy = spyRegistry.spyOnProperty(subject, 'spiedProp');
expect(spyRegistry.spyOnProperty(subject, 'spiedProp')).toBe(
originalSpy
);
});
});
});
describe("#spyOnAllFunctions", function() {
it("checks for the existence of the object", function() {
describe('#spyOnAllFunctions', function() {
it('checks for the existence of the object', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry();
expect(function() {
spyRegistry.spyOnAllFunctions(void 0);
}).toThrowError(/spyOnAllFunctions could not find an object to spy upon/);
});
it("overrides all writable and configurable functions of the object", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({createSpy: function() {
return 'I am a spy';
}});
var createNoop = function() { return function() { /**/}; };
it('overrides all writable and configurable functions of the object and its parents', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() {
return 'I am a spy';
}
});
var createNoop = function() {
return function() {
/**/
};
};
var noop1 = createNoop();
var noop2 = createNoop();
var noop3 = createNoop();
@@ -234,7 +296,7 @@ describe("SpyRegistry", function() {
var noop5 = createNoop();
var parent = {
notSpied1: noop1
parentSpied1: noop1
};
var subject = Object.create(parent);
Object.defineProperty(subject, 'spied1', {
@@ -252,7 +314,7 @@ describe("SpyRegistry", function() {
var _spied3 = noop3;
Object.defineProperty(subject, 'spied3', {
configurable: true,
set: function (val) {
set: function(val) {
_spied3 = val;
},
get: function() {
@@ -275,7 +337,9 @@ describe("SpyRegistry", function() {
});
Object.defineProperty(subject, 'notSpied4', {
configurable: false,
set: function(val) { /**/ },
set: function(val) {
/**/
},
get: function() {
return noop4;
},
@@ -291,7 +355,7 @@ describe("SpyRegistry", function() {
var spiedObject = spyRegistry.spyOnAllFunctions(subject);
expect(subject.notSpied1).toBe(noop1);
expect(subject.parentSpied1).toBe('I am a spy');
expect(subject.notSpied2).toBe(noop2);
expect(subject.notSpied3).toBe(noop3);
expect(subject.notSpied4).toBe(noop4);
@@ -303,13 +367,55 @@ describe("SpyRegistry", function() {
expect(subject.spied4).toBe('I am a spy');
expect(spiedObject).toBe(subject);
});
it('overrides prototype methods on the object', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() {
return 'I am a spy';
}
});
var noop1 = function() {};
var noop2 = function() {};
var MyClass = function() {
this.spied1 = noop1;
};
MyClass.prototype.spied2 = noop2;
var subject = new MyClass();
spyRegistry.spyOnAllFunctions(subject);
expect(subject.spied1).toBe('I am a spy');
expect(subject.spied2).toBe('I am a spy');
expect(MyClass.prototype.spied2).toBe(noop2);
});
it('does not override non-enumerable properties (like Object.prototype methods)', function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry({
createSpy: function() {
return 'I am a spy';
}
});
var subject = {
spied1: function() {}
};
spyRegistry.spyOnAllFunctions(subject);
expect(subject.spied1).toBe('I am a spy');
expect(subject.toString).not.toBe('I am a spy');
expect(subject.hasOwnProperty).not.toBe('I am a spy');
});
});
describe("#clearSpies", function() {
it("restores the original functions on the spied-upon objects", function() {
describe('#clearSpies', function() {
it('restores the original functions on the spied-upon objects', function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { return spies; },
currentSpies: function() {
return spies;
},
createSpy: createSpy
}),
originalFunction = function() {},
@@ -321,10 +427,12 @@ describe("SpyRegistry", function() {
expect(subject.spiedFunc).toBe(originalFunction);
});
it("restores the original functions, even when that spy has been replace and re-spied upon", function() {
it('restores the original functions, even when that spy has been replace and re-spied upon', function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { return spies; },
currentSpies: function() {
return spies;
},
createSpy: createSpy
}),
originalFunction = function() {},
@@ -346,11 +454,13 @@ describe("SpyRegistry", function() {
it("does not add a property that the spied-upon object didn't originally have", function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { return spies; },
currentSpies: function() {
return spies;
},
createSpy: createSpy
}),
originalFunction = function() {},
subjectParent = {spiedFunc: originalFunction};
subjectParent = { spiedFunc: originalFunction };
var subject = Object.create(subjectParent);
@@ -363,14 +473,16 @@ describe("SpyRegistry", function() {
expect(subject.spiedFunc).toBe(originalFunction);
});
it("restores the original function when it\'s inherited and cannot be deleted", function() {
it("restores the original function when it's inherited and cannot be deleted", function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { return spies; },
currentSpies: function() {
return spies;
},
createSpy: createSpy
}),
originalFunction = function() {},
subjectParent = {spiedFunc: originalFunction};
subjectParent = { spiedFunc: originalFunction };
var subject = Object.create(subjectParent);
@@ -386,15 +498,16 @@ describe("SpyRegistry", function() {
expect(jasmineUnderTest.isSpy(subject.spiedFunc)).toBe(false);
});
it("restores window.onerror by overwriting, not deleting", function() {
function FakeWindow() {
}
it('restores window.onerror by overwriting, not deleting', function() {
function FakeWindow() {}
FakeWindow.prototype.onerror = function() {};
var spies = [],
global = new FakeWindow(),
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { return spies; },
currentSpies: function() {
return spies;
},
createSpy: createSpy,
global: global
});
@@ -406,50 +519,58 @@ describe("SpyRegistry", function() {
});
});
describe('spying on properties', function() {
it("restores the original properties on the spied-upon objects", function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { return spies; },
createSpy: createSpy
}),
originalReturn = 1,
subject = {};
describe('spying on properties', function() {
it('restores the original properties on the spied-upon objects', function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() {
return spies;
},
createSpy: createSpy
}),
originalReturn = 1,
subject = {};
Object.defineProperty(subject, 'spiedProp', {
get: function() { return originalReturn; },
configurable: true
});
spyRegistry.spyOnProperty(subject, 'spiedProp');
spyRegistry.clearSpies();
expect(subject.spiedProp).toBe(originalReturn);
Object.defineProperty(subject, 'spiedProp', {
get: function() {
return originalReturn;
},
configurable: true
});
it("does not add a property that the spied-upon object didn't originally have", function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { return spies; },
createSpy: createSpy
}),
originalReturn = 1,
subjectParent = {};
spyRegistry.spyOnProperty(subject, 'spiedProp');
spyRegistry.clearSpies();
Object.defineProperty(subjectParent, 'spiedProp', {
get: function() { return originalReturn; },
configurable: true
});
var subject = Object.create(subjectParent);
expect(subject.hasOwnProperty('spiedProp')).toBe(false);
spyRegistry.spyOnProperty(subject, 'spiedProp');
spyRegistry.clearSpies();
expect(subject.hasOwnProperty('spiedProp')).toBe(false);
expect(subject.spiedProp).toBe(originalReturn);
});
expect(subject.spiedProp).toBe(originalReturn);
});
it("does not add a property that the spied-upon object didn't originally have", function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() {
return spies;
},
createSpy: createSpy
}),
originalReturn = 1,
subjectParent = {};
Object.defineProperty(subjectParent, 'spiedProp', {
get: function() {
return originalReturn;
},
configurable: true
});
var subject = Object.create(subjectParent);
expect(subject.hasOwnProperty('spiedProp')).toBe(false);
spyRegistry.spyOnProperty(subject, 'spiedProp');
spyRegistry.clearSpies();
expect(subject.hasOwnProperty('spiedProp')).toBe(false);
expect(subject.spiedProp).toBe(originalReturn);
});
});
});

View File

@@ -1,64 +1,82 @@
describe('Spies', function () {
describe('Spies', function() {
var env;
beforeEach(function() {
env = new jasmineUnderTest.Env();
});
describe("createSpy", function() {
afterEach(function() {
env.cleanup_();
});
describe('createSpy', function() {
var TestClass;
beforeEach(function() {
TestClass = function() {};
TestClass.prototype.someFunction = function() {};
TestClass.prototype.someFunction.bob = "test";
TestClass.prototype.someFunction.bob = 'test';
});
it("preserves the properties of the spied function", function() {
var spy = env.createSpy(TestClass.prototype, TestClass.prototype.someFunction);
it('preserves the properties of the spied function', function() {
var spy = env.createSpy(
TestClass.prototype,
TestClass.prototype.someFunction
);
expect(spy.bob).toEqual("test");
expect(spy.bob).toEqual('test');
});
it("should allow you to omit the name argument and only pass the originalFn argument", function() {
it('should allow you to omit the name argument and only pass the originalFn argument', 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");
if (fn.name === 'test') {
expect(spy.and.identity).toEqual('test');
} else {
expect(spy.and.identity).toEqual("unknown");
expect(spy.and.identity).toEqual('unknown');
}
})
});
it("warns the user that we intend to overwrite an existing property", function() {
TestClass.prototype.someFunction.and = "turkey";
it('warns the user that we intend to overwrite an existing property', function() {
TestClass.prototype.someFunction.and = 'turkey';
expect(function() {
env.createSpy(TestClass.prototype, TestClass.prototype.someFunction);
}).toThrowError("Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon");
}).toThrowError(
"Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon"
);
});
it("adds a spyStrategy and callTracker to the spy", function() {
var spy = env.createSpy(TestClass.prototype, TestClass.prototype.someFunction);
it('adds a spyStrategy and callTracker to the spy', function() {
var spy = env.createSpy(
TestClass.prototype,
TestClass.prototype.someFunction
);
expect(spy.and).toEqual(jasmine.any(jasmineUnderTest.SpyStrategy));
expect(spy.calls).toEqual(jasmine.any(jasmineUnderTest.CallTracker));
});
it("tracks the argument of calls", function () {
var spy = env.createSpy(TestClass.prototype, TestClass.prototype.someFunction);
var trackSpy = spyOn(spy.calls, "track");
it('tracks the argument of calls', function() {
var spy = env.createSpy(
TestClass.prototype,
TestClass.prototype.someFunction
);
var trackSpy = spyOn(spy.calls, 'track');
spy("arg");
spy('arg');
expect(trackSpy.calls.mostRecent().args[0].args).toEqual(["arg"]);
expect(trackSpy.calls.mostRecent().args[0].args).toEqual(['arg']);
});
it("tracks the context of calls", function () {
var spy = env.createSpy(TestClass.prototype, TestClass.prototype.someFunction);
var trackSpy = spyOn(spy.calls, "track");
it('tracks the context of calls', function() {
var spy = env.createSpy(
TestClass.prototype,
TestClass.prototype.someFunction
);
var trackSpy = spyOn(spy.calls, 'track');
var contextObject = { spyMethod: spy };
contextObject.spyMethod();
@@ -66,39 +84,47 @@ describe('Spies', function () {
expect(trackSpy.calls.mostRecent().args[0].object).toEqual(contextObject);
});
it("tracks the return value of calls", function () {
var spy = env.createSpy(TestClass.prototype, TestClass.prototype.someFunction);
var trackSpy = spyOn(spy.calls, "track");
it('tracks the return value of calls', function() {
var spy = env.createSpy(
TestClass.prototype,
TestClass.prototype.someFunction
);
var trackSpy = spyOn(spy.calls, 'track');
spy.and.returnValue("return value");
spy.and.returnValue('return value');
spy();
expect(trackSpy.calls.mostRecent().args[0].returnValue).toEqual("return value");
expect(trackSpy.calls.mostRecent().args[0].returnValue).toEqual(
'return value'
);
});
it("preserves arity of original function", function () {
it('preserves arity of original function', function() {
var functions = [
function nullary () {},
function unary (arg) {},
function binary (arg1, arg2) {},
function ternary (arg1, arg2, arg3) {},
function quaternary (arg1, arg2, arg3, arg4) {},
function quinary (arg1, arg2, arg3, arg4, arg5) {},
function senary (arg1, arg2, arg3, arg4, arg5, arg6) {}
function nullary() {},
function unary(arg) {},
function binary(arg1, arg2) {},
function ternary(arg1, arg2, arg3) {},
function quaternary(arg1, arg2, arg3, arg4) {},
function quinary(arg1, arg2, arg3, arg4, arg5) {},
function senary(arg1, arg2, arg3, arg4, arg5, arg6) {}
];
for (var arity = 0; arity < functions.length; arity++) {
var someFunction = functions[arity],
spy = env.createSpy(someFunction.name, someFunction);
spy = env.createSpy(someFunction.name, someFunction);
expect(spy.length).toEqual(arity);
}
});
});
describe("createSpyObj", function() {
it("should create an object with spy methods and corresponding return values when you call jasmine.createSpyObj() with an object", function () {
var spyObj = env.createSpyObj('BaseName', {'method1': 42, 'method2': 'special sauce' });
describe('createSpyObj', function() {
it('should create an object with spy methods and corresponding return values when you call jasmine.createSpyObj() with an object', function() {
var spyObj = env.createSpyObj('BaseName', {
method1: 42,
method2: 'special sauce'
});
expect(spyObj.method1()).toEqual(42);
expect(spyObj.method1.and.identity).toEqual('BaseName.method1');
@@ -107,43 +133,97 @@ describe('Spies', function () {
expect(spyObj.method2.and.identity).toEqual('BaseName.method2');
});
it("should create an object with a bunch of spy methods when you call jasmine.createSpyObj()", function() {
it('should create an object with a bunch of spy methods when you call jasmine.createSpyObj()', function() {
var spyObj = env.createSpyObj('BaseName', ['method1', 'method2']);
expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function)});
expect(spyObj).toEqual({
method1: jasmine.any(Function),
method2: jasmine.any(Function)
});
expect(spyObj.method1.and.identity).toEqual('BaseName.method1');
expect(spyObj.method2.and.identity).toEqual('BaseName.method2');
});
it("should allow you to omit the baseName", function() {
it('should allow you to omit the baseName', function() {
var spyObj = env.createSpyObj(['method1', 'method2']);
expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function)});
expect(spyObj).toEqual({
method1: jasmine.any(Function),
method2: jasmine.any(Function)
});
expect(spyObj.method1.and.identity).toEqual('unknown.method1');
expect(spyObj.method2.and.identity).toEqual('unknown.method2');
});
it("should throw if you do not pass an array or object argument", function() {
it('should throw if you do not pass an array or object argument', function() {
expect(function() {
env.createSpyObj('BaseName');
}).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for");
}).toThrow(
'createSpyObj requires a non-empty array or object of method names to create spies for'
);
});
it("should throw if you pass an empty array argument", function() {
it('should throw if you pass an empty array argument', function() {
expect(function() {
env.createSpyObj('BaseName', []);
}).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for");
}).toThrow(
'createSpyObj requires a non-empty array or object of method names to create spies for'
);
});
it("should throw if you pass an empty object argument", function() {
it('should throw if you pass an empty object argument', function() {
expect(function() {
env.createSpyObj('BaseName', {});
}).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for");
}).toThrow(
'createSpyObj requires a non-empty array or object of method names to create spies for'
);
});
it('creates an object with spy properties if a second list is passed', function() {
var spyObj = env.createSpyObj('base', ['method1'], ['prop1']);
expect(spyObj).toEqual({
method1: jasmine.any(Function)
});
var descriptor = Object.getOwnPropertyDescriptor(spyObj, 'prop1');
expect(descriptor.get.and.identity).toEqual('base.prop1.get');
expect(descriptor.set.and.identity).toEqual('base.prop1.set');
expect(spyObj.prop1).toBeUndefined();
});
it('creates an object with property names and return values if second object is passed', function() {
var spyObj = env.createSpyObj('base', ['method1'], {
prop1: 'foo',
prop2: 37
});
expect(spyObj).toEqual({
method1: jasmine.any(Function)
});
expect(spyObj.prop1).toEqual('foo');
expect(spyObj.prop2).toEqual(37);
spyObj.prop2 = 4;
expect(spyObj.prop2).toEqual(37);
expect(
Object.getOwnPropertyDescriptor(spyObj, 'prop2').set.calls.count()
).toBe(1);
});
it('allows base name to be ommitted when assigning methods and properties', function() {
var spyObj = env.createSpyObj({ m: 3 }, { p: 4 });
expect(spyObj.m()).toEqual(3);
expect(spyObj.p).toEqual(4);
expect(
Object.getOwnPropertyDescriptor(spyObj, 'p').get.and.identity
).toEqual('unknown.p.get');
});
});
it("can use different strategies for different arguments", function() {
it('can use different strategies for different arguments', function() {
var spy = env.createSpy('foo');
spy.and.returnValue(42);
spy.withArgs('baz', 'grault').and.returnValue(-1);
@@ -155,7 +235,7 @@ describe('Spies', function () {
expect(spy('baz', 'grault', 'waldo')).toEqual(42);
});
it("uses custom equality testers when selecting a strategy", function() {
it('uses custom equality testers when selecting a strategy', function() {
var spy = env.createSpy('foo');
spy.and.returnValue(42);
spy.withArgs(jasmineUnderTest.any(String)).and.returnValue(-1);
@@ -164,15 +244,42 @@ describe('Spies', function () {
expect(spy({})).toEqual(42);
});
it("can reconfigure an argument-specific strategy", function() {
it('can reconfigure an argument-specific strategy', function() {
var spy = env.createSpy('foo');
spy.withArgs('foo').and.returnValue(42);
spy.withArgs('foo').and.returnValue(17);
expect(spy('foo')).toEqual(17);
});
describe("When withArgs is used without a base strategy", function() {
it("uses the matching strategy", function() {
describe('any promise-based strategy', function() {
it('works with global Promise library when available', function(done) {
jasmine.getEnv().requirePromises();
var spy = env.createSpy('foo').and.resolveTo(42);
spy()
.then(function(result) {
expect(result).toEqual(42);
done();
})
.catch(done.fail);
});
it('works with a custom Promise library', function() {
var customPromise = {
resolve: jasmine.createSpy(),
reject: jasmine.createSpy()
};
customPromise.resolve.and.returnValue('resolved');
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() {
it('uses the matching strategy', function() {
var spy = env.createSpy('foo');
spy.withArgs('baz').and.returnValue(-1);
@@ -183,7 +290,11 @@ describe('Spies', function () {
var spy = env.createSpy('foo');
spy.withArgs('bar').and.returnValue(-1);
expect(function() { spy('baz', {qux: 42}); }).toThrowError('Spy \'foo\' receieved a call with arguments [ \'baz\', Object({ qux: 42 }) ] but all configured strategies specify other arguments.');
expect(function() {
spy('baz', { qux: 42 });
}).toThrowError(
"Spy 'foo' received a call with arguments [ 'baz', Object({ qux: 42 }) ] but all configured strategies specify other arguments."
);
});
});
});

View File

@@ -1,20 +1,19 @@
describe("SpyStrategy", function() {
it("defaults its name to unknown", function() {
describe('SpyStrategy', function() {
it('defaults its name to unknown', function() {
var spyStrategy = new jasmineUnderTest.SpyStrategy();
expect(spyStrategy.identity).toEqual("unknown");
expect(spyStrategy.identity).toEqual('unknown');
});
it("takes a name", function() {
var spyStrategy = new jasmineUnderTest.SpyStrategy({name: "foo"});
it('takes a name', function() {
var spyStrategy = new jasmineUnderTest.SpyStrategy({ name: 'foo' });
expect(spyStrategy.identity).toEqual("foo");
expect(spyStrategy.identity).toEqual('foo');
});
it("stubs an original function, if provided", function() {
var originalFn = jasmine.createSpy("original"),
spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn});
it('stubs an original function, if provided', function() {
var originalFn = jasmine.createSpy('original'),
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.exec();
@@ -22,22 +21,22 @@ describe("SpyStrategy", function() {
});
it("allows an original function to be called, passed through the params and returns it's value", function() {
var originalFn = jasmine.createSpy("original").and.returnValue(42),
spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}),
returnValue;
var originalFn = jasmine.createSpy('original').and.returnValue(42),
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }),
returnValue;
spyStrategy.callThrough();
returnValue = spyStrategy.exec(null, ["foo"]);
returnValue = spyStrategy.exec(null, ['foo']);
expect(originalFn).toHaveBeenCalled();
expect(originalFn.calls.mostRecent().args).toEqual(["foo"]);
expect(originalFn.calls.mostRecent().args).toEqual(['foo']);
expect(returnValue).toEqual(42);
});
it("can return a specified value when executed", function() {
var originalFn = jasmine.createSpy("original"),
spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}),
returnValue;
it('can return a specified value when executed', function() {
var originalFn = jasmine.createSpy('original'),
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }),
returnValue;
spyStrategy.returnValue(17);
returnValue = spyStrategy.exec();
@@ -46,9 +45,9 @@ describe("SpyStrategy", function() {
expect(returnValue).toEqual(17);
});
it("can return specified values in order specified when executed", function() {
var originalFn = jasmine.createSpy("original"),
spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn});
it('can return specified values in order specified when executed', function() {
var originalFn = jasmine.createSpy('original'),
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.returnValues('value1', 'value2', 'value3');
@@ -59,31 +58,47 @@ describe("SpyStrategy", function() {
expect(originalFn).not.toHaveBeenCalled();
});
it("allows an exception to be thrown when executed", function() {
var originalFn = jasmine.createSpy("original"),
spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn});
it('allows an exception to be thrown when executed', function() {
var originalFn = jasmine.createSpy('original'),
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.throwError(new TypeError("bar"));
spyStrategy.throwError(new TypeError('bar'));
expect(function() { spyStrategy.exec(); }).toThrowError(TypeError, "bar");
expect(function() {
spyStrategy.exec();
}).toThrowError(TypeError, 'bar');
expect(originalFn).not.toHaveBeenCalled();
});
it("allows a non-Error to be thrown, wrapping it into an exception when executed", function() {
var originalFn = jasmine.createSpy("original"),
spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn});
it('allows a string to be thrown, wrapping it into an exception when executed', function() {
var originalFn = jasmine.createSpy('original'),
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.throwError("bar");
spyStrategy.throwError('bar');
expect(function() { spyStrategy.exec(); }).toThrowError(Error, "bar");
expect(function() {
spyStrategy.exec();
}).toThrowError(Error, 'bar');
expect(originalFn).not.toHaveBeenCalled();
});
it("allows a fake function to be called instead", function() {
var originalFn = jasmine.createSpy("original"),
fakeFn = jasmine.createSpy("fake").and.returnValue(67),
spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}),
returnValue;
it('allows a non-Error to be thrown when executed', function() {
var originalFn = jasmine.createSpy('original'),
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.throwError({ code: 'ESRCH' });
expect(function() {
spyStrategy.exec();
}).toThrow({ code: 'ESRCH' });
expect(originalFn).not.toHaveBeenCalled();
});
it('allows a fake function to be called instead', function() {
var originalFn = jasmine.createSpy('original'),
fakeFn = jasmine.createSpy('fake').and.returnValue(67),
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }),
returnValue;
spyStrategy.callFake(fakeFn);
returnValue = spyStrategy.exec();
@@ -92,28 +107,173 @@ describe("SpyStrategy", function() {
expect(returnValue).toEqual(67);
});
it("allows a fake async function to be called instead", function(done) {
it('allows a fake async function to be called instead', function(done) {
jasmine.getEnv().requireAsyncAwait();
var originalFn = jasmine.createSpy("original"),
fakeFn = jasmine.createSpy("fake").and.callFake(eval("async () => { return 67; }")),
spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}),
returnValue;
var originalFn = jasmine.createSpy('original'),
fakeFn = jasmine
.createSpy('fake')
.and.callFake(eval('async () => { return 67; }')),
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyStrategy.callFake(fakeFn);
spyStrategy.exec().then(function (returnValue) {
expect(originalFn).not.toHaveBeenCalled();
expect(fakeFn).toHaveBeenCalled();
expect(returnValue).toEqual(67);
done();
}).catch(function (err) {
done.fail(err);
})
spyStrategy
.exec()
.then(function(returnValue) {
expect(originalFn).not.toHaveBeenCalled();
expect(fakeFn).toHaveBeenCalled();
expect(returnValue).toEqual(67);
done();
})
.catch(function(err) {
done.fail(err);
});
});
it("allows a custom strategy to be used", function() {
var plan = jasmine.createSpy('custom strategy')
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
});
spyStrategy.resolveTo(37);
spyStrategy
.exec()
.then(function(returnValue) {
expect(returnValue).toEqual(37);
done();
})
.catch(done.fail);
});
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
});
spyStrategy.resolveTo();
spyStrategy
.exec()
.then(function(returnValue) {
expect(returnValue).toBe();
done();
})
.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
});
spyStrategy.rejectWith(new Error('oops'));
spyStrategy
.exec()
.then(done.fail)
.catch(function(error) {
expect(error).toEqual(new Error('oops'));
done();
})
.catch(done.fail);
});
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
});
spyStrategy.rejectWith();
spyStrategy
.exec()
.then(done.fail)
.catch(function(error) {
expect(error).toBe();
done();
})
.catch(done.fail);
});
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
});
spyStrategy.rejectWith('oops');
spyStrategy
.exec()
.then(done.fail)
.catch(function(error) {
expect(error).toEqual('oops');
done();
})
.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() {
var plan = jasmine
.createSpy('custom strategy')
.and.returnValue('custom strategy result'),
customStrategy = jasmine.createSpy('custom strategy')
customStrategy = jasmine
.createSpy('custom strategy')
.and.returnValue(plan),
originalFn = jasmine.createSpy('original'),
spyStrategy = new jasmineUnderTest.SpyStrategy({
@@ -125,8 +285,9 @@ describe("SpyStrategy", function() {
spyStrategy.doSomething(1, 2, 3);
expect(customStrategy).toHaveBeenCalledWith(1, 2, 3);
expect(spyStrategy.exec(null, ['some', 'args']))
.toEqual('custom strategy result');
expect(spyStrategy.exec(null, ['some', 'args'])).toEqual(
'custom strategy result'
);
expect(plan).toHaveBeenCalledWith('some', 'args');
});
@@ -135,46 +296,49 @@ describe("SpyStrategy", function() {
spyStrategy = new jasmineUnderTest.SpyStrategy({
fn: originalFn,
customStrategies: {
doSomething: function() { return 'not a function' }
doSomething: function() {
return 'not a function';
}
}
});
expect(function() { spyStrategy.doSomething(1, 2, 3) }).toThrowError('Spy strategy must return a function');
expect(function() {
spyStrategy.doSomething(1, 2, 3);
}).toThrowError('Spy strategy must return a function');
});
it("does not allow custom strategies to overwrite existing methods", function() {
it('does not allow custom strategies to overwrite existing methods', function() {
var spyStrategy = new jasmineUnderTest.SpyStrategy({
fn: function() {},
customStrategies: {
exec: function() {}
}
});
fn: function() {},
customStrategies: {
exec: function() {}
}
});
expect(spyStrategy.exec).toBe(jasmineUnderTest.SpyStrategy.prototype.exec);
});
it('throws an error when a non-function is passed to callFake strategy', function() {
var originalFn = jasmine.createSpy('original'),
spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}),
invalidFakes = [5, 'foo', {}, true, false, null, void 0, new Date(), /.*/];
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn });
spyOn(jasmineUnderTest, 'isFunction_').and.returnValue(false);
spyOn(jasmineUnderTest, 'isAsyncFunction_').and.returnValue(false);
expect(function () {
expect(function() {
spyStrategy.callFake(function() {});
}).toThrowError(/^Argument passed to callFake should be a function, got/);
expect(function () {
expect(function() {
spyStrategy.callFake(function() {});
}).toThrowError(/^Argument passed to callFake should be a function, got/);
});
it("allows a return to plan stubbing after another strategy", function() {
var originalFn = jasmine.createSpy("original"),
fakeFn = jasmine.createSpy("fake").and.returnValue(67),
spyStrategy = new jasmineUnderTest.SpyStrategy({fn: originalFn}),
returnValue;
it('allows a return to plan stubbing after another strategy', function() {
var originalFn = jasmine.createSpy('original'),
fakeFn = jasmine.createSpy('fake').and.returnValue(67),
spyStrategy = new jasmineUnderTest.SpyStrategy({ fn: originalFn }),
returnValue;
spyStrategy.callFake(fakeFn);
returnValue = spyStrategy.exec();
@@ -188,10 +352,10 @@ describe("SpyStrategy", function() {
expect(returnValue).toEqual(void 0);
});
it("returns the spy after changing the strategy", function(){
it('returns the spy after changing the strategy', function() {
var spy = {},
spyFn = jasmine.createSpy('spyFn').and.returnValue(spy),
spyStrategy = new jasmineUnderTest.SpyStrategy({getSpy: spyFn});
spyFn = jasmine.createSpy('spyFn').and.returnValue(spy),
spyStrategy = new jasmineUnderTest.SpyStrategy({ getSpy: spyFn });
expect(spyStrategy.callThrough()).toBe(spy);
expect(spyStrategy.returnValue()).toBe(spy);

View File

@@ -1,5 +1,5 @@
describe("StackTrace", function() {
it("understands Chrome/IE/Edge style traces", function() {
describe('StackTrace', function() {
it('understands Chrome/IE/Edge style traces', function() {
var error = {
message: 'nope',
stack:
@@ -14,13 +14,15 @@ describe("StackTrace", function() {
expect(result.style).toEqual('v8');
expect(result.frames).toEqual([
{
raw: ' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)',
raw:
' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)',
func: 'UserContext.<anonymous>',
file: 'http://localhost:8888/__spec__/core/UtilSpec.js',
line: 115
},
{
raw: ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)',
raw:
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)',
func: 'QueueRunner.run',
file: 'http://localhost:8888/__jasmine__/jasmine.js',
line: 4320
@@ -28,7 +30,7 @@ describe("StackTrace", function() {
]);
});
it("understands Chrome/IE/Edge style traces with multiline messages", function() {
it('understands Chrome/IE/Edge style traces with multiline messages', function() {
var error = {
message: 'line 1\nline 2',
stack:
@@ -40,14 +42,16 @@ describe("StackTrace", function() {
var result = new jasmineUnderTest.StackTrace(error);
expect(result.message).toEqual('Error: line 1\nline 2');
var rawFrames = result.frames.map(function(f) { return f.raw; });
var rawFrames = result.frames.map(function(f) {
return f.raw;
});
expect(rawFrames).toEqual([
' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)',
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)',
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)'
]);
});
it("understands Node style traces", function() {
it('understands Node style traces', function() {
var error = {
message: 'nope',
stack:
@@ -69,13 +73,15 @@ describe("StackTrace", function() {
line: 4255
},
{
raw: ' at QueueRunner.complete [as onComplete] (/somewhere/jasmine/lib/jasmine-core/jasmine.js:579:9)',
raw:
' at QueueRunner.complete [as onComplete] (/somewhere/jasmine/lib/jasmine-core/jasmine.js:579:9)',
func: 'QueueRunner.complete [as onComplete]',
file: '/somewhere/jasmine/lib/jasmine-core/jasmine.js',
line: 579
},
{
raw: ' at Immediate.<anonymous> (/somewhere/jasmine/lib/jasmine-core/jasmine.js:4314:12)',
raw:
' at Immediate.<anonymous> (/somewhere/jasmine/lib/jasmine-core/jasmine.js:4314:12)',
func: 'Immediate.<anonymous>',
file: '/somewhere/jasmine/lib/jasmine-core/jasmine.js',
line: 4314
@@ -89,7 +95,7 @@ describe("StackTrace", function() {
]);
});
it("understands Safari/Firefox/Phantom-OS X style traces", function() {
it('understands Safari/Firefox/Phantom-OS X style traces', function() {
var error = {
message: 'nope',
stack:
@@ -116,22 +122,20 @@ describe("StackTrace", function() {
]);
});
it("does not mistake gibberish for Safari/Firefox/Phantom-OS X style traces", function() {
it('does not mistake gibberish for Safari/Firefox/Phantom-OS X style traces', function() {
var error = {
message: 'nope',
stack: 'randomcharsnotincludingwhitespace'
};
var result = new jasmineUnderTest.StackTrace(error);
expect(result.style).toBeNull();
expect(result.frames).toEqual([
{ raw: error.stack }
]);
expect(result.frames).toEqual([{ raw: error.stack }]);
});
it("understands Phantom-Linux style traces", function() {
it('understands Phantom-Linux style traces', function() {
var error = {
message: 'nope',
stack:
stack:
' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n' +
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)'
};
@@ -142,13 +146,15 @@ describe("StackTrace", function() {
expect(result.style).toEqual('v8');
expect(result.frames).toEqual([
{
raw: ' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)',
raw:
' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)',
func: 'UserContext.<anonymous>',
file: 'http://localhost:8888/__spec__/core/UtilSpec.js',
line: 115
},
{
raw: ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)',
raw:
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)',
func: 'QueueRunner.run',
file: 'http://localhost:8888/__jasmine__/jasmine.js',
line: 4320
@@ -156,7 +162,7 @@ describe("StackTrace", function() {
]);
});
it("ignores blank lines", function() {
it('ignores blank lines', function() {
var error = {
message: 'nope',
stack:
@@ -167,7 +173,8 @@ describe("StackTrace", function() {
expect(result.frames).toEqual([
{
raw: ' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)',
raw:
' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)',
func: 'UserContext.<anonymous>',
file: 'http://localhost:8888/__spec__/core/UtilSpec.js',
line: 115
@@ -188,7 +195,8 @@ describe("StackTrace", function() {
expect(result.style).toEqual('v8');
expect(result.frames).toEqual([
{
raw: ' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)',
raw:
' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)',
func: 'UserContext.<anonymous>',
file: 'http://localhost:8888/__spec__/core/UtilSpec.js',
line: 115
@@ -197,11 +205,54 @@ describe("StackTrace", function() {
raw: ' but this is quite unexpected'
},
{
raw: ' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)',
raw:
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)',
func: 'QueueRunner.run',
file: 'http://localhost:8888/__jasmine__/jasmine.js',
line: 4320
}
]);
});
it('consideres different types of errors', function() {
var error = {
message: 'nope',
stack:
'TypeError: nope\n' +
' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n' +
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)'
};
var result = new jasmineUnderTest.StackTrace(error);
expect(result.message).toEqual('TypeError: nope');
expect(result.frames).toEqual([
{
raw:
' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)',
func: 'UserContext.<anonymous>',
file: 'http://localhost:8888/__spec__/core/UtilSpec.js',
line: 115
},
{
raw:
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)',
func: 'QueueRunner.run',
file: 'http://localhost:8888/__jasmine__/jasmine.js',
line: 4320
}
]);
var no_error = {
message: 'nope',
stack:
'Type Error: nope\n' +
' at UserContext.<anonymous> (http://localhost:8888/__spec__/core/UtilSpec.js:115:19)\n' +
' at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)'
};
var result_no_error = new jasmineUnderTest.StackTrace(no_error);
expect(result_no_error.message).not.toEqual(jasmine.anything());
});
});

View File

@@ -1,47 +1,52 @@
describe("Suite", function() {
describe('Suite', function() {
var env;
it("keeps its id", function() {
var env = new jasmineUnderTest.Env(),
suite = new jasmineUnderTest.Suite({
env: env,
id: 456,
description: "I am a suite"
});
beforeEach(function() {
env = new jasmineUnderTest.Env();
});
afterEach(function() {
env.cleanup_();
});
it('keeps its id', function() {
var suite = new jasmineUnderTest.Suite({
env: env,
id: 456,
description: 'I am a suite'
});
expect(suite.id).toEqual(456);
});
it("returns blank full name for top level suite", function() {
var env = new jasmineUnderTest.Env(),
suite = new jasmineUnderTest.Suite({
env: env,
description: "I am a suite"
});
it('returns blank full name for top level suite', function() {
var suite = new jasmineUnderTest.Suite({
env: env,
description: 'I am a suite'
});
expect(suite.getFullName()).toEqual("");
expect(suite.getFullName()).toEqual('');
});
it("returns its full name when it has parent suites", function() {
var env = new jasmineUnderTest.Env(),
parentSuite = new jasmineUnderTest.Suite({
it('returns its full name when it has parent suites', function() {
var parentSuite = new jasmineUnderTest.Suite({
env: env,
description: "I am a parent suite",
description: 'I am a parent suite',
parentSuite: jasmine.createSpy('pretend top level suite')
}),
suite = new jasmineUnderTest.Suite({
env: env,
description: "I am a suite",
description: 'I am a suite',
parentSuite: parentSuite
});
expect(suite.getFullName()).toEqual("I am a parent suite I am a suite");
expect(suite.getFullName()).toEqual('I am a parent suite I am a suite');
});
it("adds before functions in order of needed execution", function() {
var env = new jasmineUnderTest.Env(),
suite = new jasmineUnderTest.Suite({
it('adds before functions in order of needed execution', function() {
var suite = new jasmineUnderTest.Suite({
env: env,
description: "I am a suite"
description: 'I am a suite'
}),
outerBefore = jasmine.createSpy('outerBeforeEach'),
innerBefore = jasmine.createSpy('insideBeforeEach');
@@ -52,11 +57,10 @@ describe("Suite", function() {
expect(suite.beforeFns).toEqual([innerBefore, outerBefore]);
});
it("adds after functions in order of needed execution", function() {
var env = new jasmineUnderTest.Env(),
suite = new jasmineUnderTest.Suite({
it('adds after functions in order of needed execution', function() {
var suite = new jasmineUnderTest.Suite({
env: env,
description: "I am a suite"
description: 'I am a suite'
}),
outerAfter = jasmine.createSpy('outerAfterEach'),
innerAfter = jasmine.createSpy('insideAfterEach');
@@ -69,29 +73,33 @@ describe("Suite", function() {
it('has a status of failed if any expectations have failed', function() {
var suite = new jasmineUnderTest.Suite({
expectationResultFactory: function() { return 'hi'; }
expectationResultFactory: function() {
return 'hi';
}
});
suite.addExpectationResult(false);
expect(suite.status()).toBe('failed');
});
it("retrieves a result with updated status", function() {
it('retrieves a result with updated status', function() {
var suite = new jasmineUnderTest.Suite({});
expect(suite.getResult().status).toBe('passed');
});
it("retrieves a result with pending status", function() {
it('retrieves a result with pending status', function() {
var suite = new jasmineUnderTest.Suite({});
suite.pend();
expect(suite.getResult().status).toBe('pending');
});
it("throws an ExpectationFailed when receiving a failed expectation when throwOnExpectationFailure is set", function() {
it('throws an ExpectationFailed when receiving a failed expectation when throwOnExpectationFailure is set', function() {
var suite = new jasmineUnderTest.Suite({
expectationResultFactory: function(data) { return data; },
expectationResultFactory: function(data) {
return data;
},
throwOnExpectationFailure: true
});
@@ -103,7 +111,7 @@ describe("Suite", function() {
expect(suite.result.failedExpectations).toEqual(['failed']);
});
it("does not add an additional failure when an expectation fails", function(){
it('does not add an additional failure when an expectation fails', function() {
var suite = new jasmineUnderTest.Suite({});
suite.onException(new jasmineUnderTest.errors.ExpectationFailed());
@@ -111,13 +119,27 @@ describe("Suite", function() {
expect(suite.getResult().failedExpectations).toEqual([]);
});
it('calls timer to compute duration', function() {
var suite = new jasmineUnderTest.Suite({
env: env,
id: 456,
description: 'I am a suite',
timer: jasmine.createSpyObj('timer', { start: null, elapsed: 77000 })
});
suite.startTimer();
suite.endTimer();
expect(suite.getResult().duration).toEqual(77000);
});
describe('#sharedUserContext', function() {
beforeEach(function() {
this.suite = new jasmineUnderTest.Suite({});
});
it('returns a UserContext', function() {
expect(this.suite.sharedUserContext().constructor).toBe(jasmineUnderTest.UserContext);
expect(this.suite.sharedUserContext().constructor).toBe(
jasmineUnderTest.UserContext
);
});
});
});

View File

@@ -1,7 +1,7 @@
describe("Timer", function() {
it("reports the time elapsed", function() {
describe('Timer', function() {
it('reports the time elapsed', function() {
var fakeNow = jasmine.createSpy('fake Date.now'),
timer = new jasmineUnderTest.Timer({now: fakeNow});
timer = new jasmineUnderTest.Timer({ now: fakeNow });
fakeNow.and.returnValue(100);
timer.start();
@@ -11,7 +11,7 @@ describe("Timer", function() {
expect(timer.elapsed()).toEqual(100);
});
describe("when date is stubbed, perhaps by other testing helpers", function() {
describe('when date is stubbed, perhaps by other testing helpers', function() {
var origDate = Date;
beforeEach(function() {
Date = jasmine.createSpy('date spy');
@@ -21,7 +21,7 @@ describe("Timer", function() {
Date = origDate;
});
it("does not throw even though Date was taken away", function() {
it('does not throw even though Date was taken away', function() {
var timer = new jasmineUnderTest.Timer();
expect(timer.start).not.toThrow();

View File

@@ -1,5 +1,6 @@
describe("TreeProcessor", function() {
var nodeNumber = 0, leafNumber = 0;
describe('TreeProcessor', function() {
var nodeNumber = 0,
leafNumber = 0;
function Node(attrs) {
attrs = attrs || {};
@@ -15,7 +16,7 @@ describe("TreeProcessor", function() {
this.getResult = jasmine.createSpy(this.id + '#execute');
this.beforeAllFns = attrs.beforeAllFns || [];
this.afterAllFns = attrs.afterAllFns || [];
this.cleanupBeforeAfter = function() { };
this.cleanupBeforeAfter = function() {};
}
function Leaf(attrs) {
@@ -25,10 +26,13 @@ describe("TreeProcessor", function() {
this.execute = jasmine.createSpy(this.id + '#execute');
}
it("processes a single leaf", function() {
it('processes a single leaf', function() {
var leaf = new Leaf(),
processor = new jasmineUnderTest.TreeProcessor({ tree: leaf, runnableIds: [leaf.id] }),
result = processor.processTree();
processor = new jasmineUnderTest.TreeProcessor({
tree: leaf,
runnableIds: [leaf.id]
}),
result = processor.processTree();
expect(result.valid).toBe(true);
@@ -39,10 +43,13 @@ describe("TreeProcessor", function() {
});
});
it("processes a single pending leaf", function() {
it('processes a single pending leaf', function() {
var leaf = new Leaf({ markedPending: true }),
processor = new jasmineUnderTest.TreeProcessor({ tree: leaf, runnableIds: [leaf.id] }),
result = processor.processTree();
processor = new jasmineUnderTest.TreeProcessor({
tree: leaf,
runnableIds: [leaf.id]
}),
result = processor.processTree();
expect(result.valid).toBe(true);
@@ -53,10 +60,13 @@ describe("TreeProcessor", function() {
});
});
it("processes a single non-specified leaf", function() {
it('processes a single non-specified leaf', function() {
var leaf = new Leaf(),
processor = new jasmineUnderTest.TreeProcessor({ tree: leaf, runnableIds: [] }),
result = processor.processTree();
processor = new jasmineUnderTest.TreeProcessor({
tree: leaf,
runnableIds: []
}),
result = processor.processTree();
expect(result.valid).toBe(true);
@@ -67,14 +77,16 @@ describe("TreeProcessor", function() {
});
});
it("processes a single excluded leaf", function() {
it('processes a single excluded leaf', function() {
var leaf = new Leaf(),
processor = new jasmineUnderTest.TreeProcessor({
tree: leaf,
runnableIds: [leaf.id],
excludeNode: function(node) { return true; }
}),
result = processor.processTree();
processor = new jasmineUnderTest.TreeProcessor({
tree: leaf,
runnableIds: [leaf.id],
excludeNode: function(node) {
return true;
}
}),
result = processor.processTree();
expect(result.valid).toBe(true);
@@ -85,11 +97,14 @@ describe("TreeProcessor", function() {
});
});
it("processes a tree with a single leaf with the root specified", function() {
it('processes a tree with a single leaf with the root specified', function() {
var leaf = new Leaf(),
parent = new Node({ children: [leaf] }),
processor = new jasmineUnderTest.TreeProcessor({ tree: parent, runnableIds: [parent.id] }),
result = processor.processTree();
parent = new Node({ children: [leaf] }),
processor = new jasmineUnderTest.TreeProcessor({
tree: parent,
runnableIds: [parent.id]
}),
result = processor.processTree();
expect(result.valid).toBe(true);
@@ -106,11 +121,14 @@ describe("TreeProcessor", function() {
});
});
it("processes a tree with a single pending leaf, with the root specified", function() {
it('processes a tree with a single pending leaf, with the root specified', function() {
var leaf = new Leaf({ markedPending: true }),
parent = new Node({ children: [leaf] }),
processor = new jasmineUnderTest.TreeProcessor({ tree: parent, runnableIds: [parent.id] }),
result = processor.processTree();
parent = new Node({ children: [leaf] }),
processor = new jasmineUnderTest.TreeProcessor({
tree: parent,
runnableIds: [parent.id]
}),
result = processor.processTree();
expect(result.valid).toBe(true);
@@ -127,17 +145,26 @@ describe("TreeProcessor", function() {
});
});
it("processes a complicated tree with the root specified", function() {
it('processes a complicated tree with the root specified', function() {
var pendingLeaf = new Leaf({ markedPending: true }),
executableLeaf = new Leaf({ markedPending: false }),
parent = new Node({ children: [pendingLeaf, executableLeaf] }),
childless = new Node(),
childOfPending = new Leaf({ markedPending: true }),
pendingNode = new Node({ markedPending: true, children: [childOfPending] }),
parentOfPendings = new Node({ markedPending: false, children: [childless, pendingNode] }),
root = new Node({ children: [parent, parentOfPendings] }),
processor = new jasmineUnderTest.TreeProcessor({ tree: root, runnableIds: [root.id] }),
result = processor.processTree();
executableLeaf = new Leaf({ markedPending: false }),
parent = new Node({ children: [pendingLeaf, executableLeaf] }),
childless = new Node(),
childOfPending = new Leaf({ markedPending: true }),
pendingNode = new Node({
markedPending: true,
children: [childOfPending]
}),
parentOfPendings = new Node({
markedPending: false,
children: [childless, pendingNode]
}),
root = new Node({ children: [parent, parentOfPendings] }),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [root.id]
}),
result = processor.processTree();
expect(result.valid).toBe(true);
@@ -190,58 +217,73 @@ describe("TreeProcessor", function() {
});
});
it("marks the run order invalid if it would re-enter a node that does not allow re-entry", function() {
it('marks the run order invalid if it would re-enter a node that does not allow re-entry', function() {
var leaf1 = new Leaf(),
leaf2 = new Leaf(),
leaf3 = new Leaf(),
reentered = new Node({ noReenter: true, children: [leaf1, leaf2] }),
root = new Node({ children: [reentered, leaf3] }),
processor = new jasmineUnderTest.TreeProcessor({ tree: root, runnableIds: [leaf1.id, leaf3.id, leaf2.id] }),
result = processor.processTree();
leaf2 = new Leaf(),
leaf3 = new Leaf(),
reentered = new Node({ noReenter: true, children: [leaf1, leaf2] }),
root = new Node({ children: [reentered, leaf3] }),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf1.id, leaf3.id, leaf2.id]
}),
result = processor.processTree();
expect(result).toEqual({ valid: false });
});
it("marks the run order valid if a node being re-entered allows re-entry", function() {
it('marks the run order valid if a node being re-entered allows re-entry', function() {
var leaf1 = new Leaf(),
leaf2 = new Leaf(),
leaf3 = new Leaf(),
reentered = new Node({ children: [leaf1, leaf2] }),
root = new Node({ children: [reentered, leaf3] }),
processor = new jasmineUnderTest.TreeProcessor({ tree: root, runnableIds: [leaf1.id, leaf3.id, leaf2.id] }),
result = processor.processTree();
leaf2 = new Leaf(),
leaf3 = new Leaf(),
reentered = new Node({ children: [leaf1, leaf2] }),
root = new Node({ children: [reentered, leaf3] }),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf1.id, leaf3.id, leaf2.id]
}),
result = processor.processTree();
expect(result.valid).toBe(true);
});
it("marks the run order valid if a node which can't be re-entered is only entered once", function() {
var leaf1 = new Leaf(),
leaf2 = new Leaf(),
leaf3 = new Leaf(),
noReentry = new Node({ noReenter: true }),
root = new Node({ children: [noReentry] }),
processor = new jasmineUnderTest.TreeProcessor({ tree: root, runnableIds: [leaf2.id, leaf1.id, leaf3.id] }),
result = processor.processTree();
leaf2 = new Leaf(),
leaf3 = new Leaf(),
noReentry = new Node({ noReenter: true }),
root = new Node({ children: [noReentry] }),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf2.id, leaf1.id, leaf3.id]
}),
result = processor.processTree();
expect(result.valid).toBe(true);
});
it("marks the run order valid if a node which can't be re-entered is run directly", function() {
var leaf1 = new Leaf(),
noReentry = new Node({ noReenter: true }),
root = new Node({ children: [noReentry] }),
processor = new jasmineUnderTest.TreeProcessor({ tree: root, runnableIds: [root.id] }),
result = processor.processTree();
var noReentry = new Node({ noReenter: true }),
root = new Node({ children: [noReentry] }),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [root.id]
}),
result = processor.processTree();
expect(result.valid).toBe(true);
});
it("runs a single leaf", function() {
it('runs a single leaf', function() {
var leaf = new Leaf(),
node = new Node({ children: [leaf], userContext: { root: 'context' } }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({ tree: node, runnableIds: [leaf.id], queueRunnerFactory: queueRunner }),
treeComplete = jasmine.createSpy('treeComplete');
node = new Node({ children: [leaf], userContext: { root: 'context' } }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: node,
runnableIds: [leaf.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete');
processor.execute(treeComplete);
@@ -254,24 +296,24 @@ describe("TreeProcessor", function() {
queueRunner.calls.mostRecent().args[0].queueableFns[0].fn('foo');
expect(leaf.execute).toHaveBeenCalledWith('foo', false);
expect(leaf.execute).toHaveBeenCalledWith('foo', false, false);
});
it("runs a node with no children", function() {
it('runs a node with no children', function() {
var node = new Node({ userContext: { node: 'context' } }),
root = new Node({ children: [node], userContext: { root: 'context' } }),
nodeStart = jasmine.createSpy('nodeStart'),
nodeComplete = jasmine.createSpy('nodeComplete'),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
nodeStart: nodeStart,
nodeComplete: nodeComplete,
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
root = new Node({ children: [node], userContext: { root: 'context' } }),
nodeStart = jasmine.createSpy('nodeStart'),
nodeComplete = jasmine.createSpy('nodeComplete'),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
nodeStart: nodeStart,
nodeComplete: nodeComplete,
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
processor.execute(treeComplete);
@@ -297,22 +339,26 @@ describe("TreeProcessor", function() {
node.getResult.and.returnValue({ my: 'result' });
queueRunner.calls.mostRecent().args[0].onComplete();
expect(nodeComplete).toHaveBeenCalledWith(node, { my: 'result' }, jasmine.any(Function));
expect(nodeComplete).toHaveBeenCalledWith(
node,
{ my: 'result' },
jasmine.any(Function)
);
});
it("runs a node with children", function() {
it('runs a node with children', function() {
var leaf1 = new Leaf(),
leaf2 = new Leaf(),
node = new Node({ children: [leaf1, leaf2] }),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
leaf2 = new Leaf(),
node = new Node({ children: [leaf1, leaf2] }),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
processor.execute(treeComplete);
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -322,26 +368,26 @@ describe("TreeProcessor", function() {
expect(queueableFns.length).toBe(3);
queueableFns[1].fn('foo');
expect(leaf1.execute).toHaveBeenCalledWith('foo', false);
expect(leaf1.execute).toHaveBeenCalledWith('foo', false, false);
queueableFns[2].fn('bar');
expect(leaf2.execute).toHaveBeenCalledWith('bar', false);
expect(leaf2.execute).toHaveBeenCalledWith('bar', false, false);
});
it("cascades errors up the tree", function() {
it('cascades errors up the tree', function() {
var leaf = new Leaf(),
node = new Node({ children: [leaf] }),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
nodeComplete = jasmine.createSpy('nodeComplete'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
nodeComplete: nodeComplete,
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
node = new Node({ children: [leaf] }),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
nodeComplete = jasmine.createSpy('nodeComplete'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
nodeComplete: nodeComplete,
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
processor.execute(treeComplete);
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -351,7 +397,7 @@ describe("TreeProcessor", function() {
expect(queueableFns.length).toBe(2);
queueableFns[1].fn('foo');
expect(leaf.execute).toHaveBeenCalledWith('foo', false);
expect(leaf.execute).toHaveBeenCalledWith('foo', false, false);
queueRunner.calls.mostRecent().args[0].onComplete('things');
expect(nodeComplete).toHaveBeenCalled();
@@ -359,22 +405,22 @@ describe("TreeProcessor", function() {
expect(nodeDone).toHaveBeenCalledWith('things');
});
it("runs an excluded node with leaf", function() {
it('runs an excluded node with leaf', function() {
var leaf1 = new Leaf(),
node = new Node({ children: [leaf1] }),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
nodeStart = jasmine.createSpy('nodeStart'),
nodeComplete = jasmine.createSpy('nodeComplete'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [],
queueRunnerFactory: queueRunner,
nodeStart: nodeStart,
nodeComplete: nodeComplete
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
node = new Node({ children: [leaf1] }),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
nodeStart = jasmine.createSpy('nodeStart'),
nodeComplete = jasmine.createSpy('nodeComplete'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [],
queueRunnerFactory: queueRunner,
nodeStart: nodeStart,
nodeComplete: nodeComplete
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
processor.execute(treeComplete);
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -387,29 +433,62 @@ describe("TreeProcessor", function() {
expect(nodeStart).toHaveBeenCalledWith(node, 'bar');
queueableFns[1].fn('foo');
expect(leaf1.execute).toHaveBeenCalledWith('foo', true);
expect(leaf1.execute).toHaveBeenCalledWith('foo', true, false);
node.getResult.and.returnValue({ im: 'disabled' });
queueRunner.calls.mostRecent().args[0].onComplete();
expect(nodeComplete).toHaveBeenCalledWith(node, { im: 'disabled' }, jasmine.any(Function));
expect(nodeComplete).toHaveBeenCalledWith(
node,
{ im: 'disabled' },
jasmine.any(Function)
);
});
it("runs beforeAlls for a node with children", function() {
it('should execute node with correct arguments when failSpecWithNoExpectations option is set', function() {
var leaf = new Leaf(),
node = new Node({
children: [leaf],
beforeAllFns: ['beforeAll1', 'beforeAll2']
}),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
node = new Node({ children: [leaf] }),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
nodeStart = jasmine.createSpy('nodeStart'),
nodeComplete = jasmine.createSpy('nodeComplete'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [],
queueRunnerFactory: queueRunner,
nodeStart: nodeStart,
nodeComplete: nodeComplete,
failSpecWithNoExpectations: true
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
processor.execute(treeComplete);
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
queueableFns[0].fn(nodeDone);
queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
expect(queueableFns.length).toBe(2);
queueableFns[1].fn('foo');
expect(leaf.execute).toHaveBeenCalledWith('foo', true, true);
});
it('runs beforeAlls for a node with children', function() {
var leaf = new Leaf(),
node = new Node({
children: [leaf],
beforeAllFns: ['beforeAll1', 'beforeAll2']
}),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
processor.execute(treeComplete);
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -417,24 +496,29 @@ describe("TreeProcessor", function() {
queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
expect(queueableFns).toEqual([{ fn: jasmine.any(Function) }, 'beforeAll1', 'beforeAll2', { fn: jasmine.any(Function) }]);
expect(queueableFns).toEqual([
{ fn: jasmine.any(Function) },
'beforeAll1',
'beforeAll2',
{ fn: jasmine.any(Function) }
]);
});
it("runs afterAlls for a node with children", function() {
it('runs afterAlls for a node with children', function() {
var leaf = new Leaf(),
node = new Node({
children: [leaf],
afterAllFns: ['afterAll1', 'afterAll2']
}),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
node = new Node({
children: [leaf],
afterAllFns: ['afterAll1', 'afterAll2']
}),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
processor.execute(treeComplete);
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -442,23 +526,28 @@ describe("TreeProcessor", function() {
queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
expect(queueableFns).toEqual([{ fn: jasmine.any(Function) }, { fn: jasmine.any(Function) }, 'afterAll1', 'afterAll2']);
expect(queueableFns).toEqual([
{ fn: jasmine.any(Function) },
{ fn: jasmine.any(Function) },
'afterAll1',
'afterAll2'
]);
});
it("does not run beforeAlls or afterAlls for a node with no children", function() {
it('does not run beforeAlls or afterAlls for a node with no children', function() {
var node = new Node({
beforeAllFns: ['before'],
afterAllFns: ['after']
}),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
beforeAllFns: ['before'],
afterAllFns: ['after']
}),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
processor.execute(treeComplete);
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -466,26 +555,26 @@ describe("TreeProcessor", function() {
queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
expect(queueableFns).toEqual([{fn: jasmine.any(Function)}]);
expect(queueableFns).toEqual([{ fn: jasmine.any(Function) }]);
});
it("does not run beforeAlls or afterAlls for a node with only pending children", function() {
it('does not run beforeAlls or afterAlls for a node with only pending children', function() {
var leaf = new Leaf({ markedPending: true }),
node = new Node({
children: [leaf],
beforeAllFns: ['before'],
afterAllFns: ['after'],
markedPending: false
}),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
node = new Node({
children: [leaf],
beforeAllFns: ['before'],
afterAllFns: ['after'],
markedPending: false
}),
root = new Node({ children: [node] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [node.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete'),
nodeDone = jasmine.createSpy('nodeDone');
processor.execute(treeComplete);
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -493,20 +582,23 @@ describe("TreeProcessor", function() {
queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
expect(queueableFns).toEqual([{ fn: jasmine.any(Function) }, { fn: jasmine.any(Function) }]);
expect(queueableFns).toEqual([
{ fn: jasmine.any(Function) },
{ fn: jasmine.any(Function) }
]);
});
it("runs leaves in the order specified", function() {
it('runs leaves in the order specified', function() {
var leaf1 = new Leaf(),
leaf2 = new Leaf(),
root = new Node({ children: [leaf1, leaf2] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf2.id, leaf1.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete');
leaf2 = new Leaf(),
root = new Node({ children: [leaf1, leaf2] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf2.id, leaf1.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete');
processor.execute(treeComplete);
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -520,41 +612,41 @@ describe("TreeProcessor", function() {
expect(leaf1.execute).toHaveBeenCalled();
});
it("runs specified leaves before non-specified leaves within a parent node", function() {
it('runs specified leaves before non-specified leaves within a parent node', function() {
var specified = new Leaf(),
nonSpecified = new Leaf(),
root = new Node({ children: [nonSpecified, specified] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [specified.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete');
nonSpecified = new Leaf(),
root = new Node({ children: [nonSpecified, specified] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [specified.id],
queueRunnerFactory: queueRunner
}),
treeComplete = jasmine.createSpy('treeComplete');
processor.execute(treeComplete);
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
queueableFns[0].fn();
expect(nonSpecified.execute).not.toHaveBeenCalled();
expect(specified.execute).toHaveBeenCalledWith(undefined, false);
expect(specified.execute).toHaveBeenCalledWith(undefined, false, false);
queueableFns[1].fn();
expect(nonSpecified.execute).toHaveBeenCalledWith(undefined, true);
expect(nonSpecified.execute).toHaveBeenCalledWith(undefined, true, false);
});
it("runs nodes and leaves with a specified order", function() {
it('runs nodes and leaves with a specified order', function() {
var specifiedLeaf = new Leaf(),
childLeaf = new Leaf(),
specifiedNode = new Node({ children: [childLeaf] }),
root = new Node({ children: [specifiedLeaf, specifiedNode] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [specifiedNode.id, specifiedLeaf.id],
queueRunnerFactory: queueRunner
});
childLeaf = new Leaf(),
specifiedNode = new Node({ children: [childLeaf] }),
root = new Node({ children: [specifiedLeaf, specifiedNode] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [specifiedNode.id, specifiedLeaf.id],
queueRunnerFactory: queueRunner
});
processor.execute();
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -571,20 +663,20 @@ describe("TreeProcessor", function() {
expect(specifiedLeaf.execute).toHaveBeenCalled();
});
it("runs a node multiple times if the order specified leaves and re-enters it", function() {
it('runs a node multiple times if the order specified leaves and re-enters it', function() {
var leaf1 = new Leaf(),
leaf2 = new Leaf(),
leaf3 = new Leaf(),
leaf4 = new Leaf(),
leaf5 = new Leaf(),
reentered = new Node({ children: [leaf1, leaf2, leaf3] }),
root = new Node({ children: [reentered, leaf4, leaf5] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf1.id, leaf4.id, leaf2.id, leaf5.id, leaf3.id],
queueRunnerFactory: queueRunner
});
leaf2 = new Leaf(),
leaf3 = new Leaf(),
leaf4 = new Leaf(),
leaf5 = new Leaf(),
reentered = new Node({ children: [leaf1, leaf2, leaf3] }),
root = new Node({ children: [reentered, leaf4, leaf5] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf1.id, leaf4.id, leaf2.id, leaf5.id, leaf3.id],
queueRunnerFactory: queueRunner
});
processor.execute();
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -614,21 +706,21 @@ describe("TreeProcessor", function() {
expect(leaf3.execute).toHaveBeenCalled();
});
it("runs a parent of a node with segments correctly", function() {
it('runs a parent of a node with segments correctly', function() {
var leaf1 = new Leaf(),
leaf2 = new Leaf(),
leaf3 = new Leaf(),
leaf4 = new Leaf(),
leaf5 = new Leaf(),
parent = new Node({ children: [leaf1, leaf2, leaf3] }),
grandparent = new Node({ children: [parent] }),
root = new Node({ children: [grandparent, leaf4, leaf5] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf1.id, leaf4.id, leaf2.id, leaf5.id, leaf3.id],
queueRunnerFactory: queueRunner
});
leaf2 = new Leaf(),
leaf3 = new Leaf(),
leaf4 = new Leaf(),
leaf5 = new Leaf(),
parent = new Node({ children: [leaf1, leaf2, leaf3] }),
grandparent = new Node({ children: [parent] }),
root = new Node({ children: [grandparent, leaf4, leaf5] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [leaf1.id, leaf4.id, leaf2.id, leaf5.id, leaf3.id],
queueRunnerFactory: queueRunner
});
processor.execute();
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -671,18 +763,18 @@ describe("TreeProcessor", function() {
expect(leaf3.execute).toHaveBeenCalled();
});
it("runs nodes in the order they were declared", function() {
it('runs nodes in the order they were declared', function() {
var leaf1 = new Leaf(),
leaf2 = new Leaf(),
leaf3 = new Leaf(),
parent = new Node({ children: [leaf2, leaf3] }),
root = new Node({ children: [leaf1, parent] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [root.id],
queueRunnerFactory: queueRunner
});
leaf2 = new Leaf(),
leaf3 = new Leaf(),
parent = new Node({ children: [leaf2, leaf3] }),
root = new Node({ children: [leaf1, parent] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [root.id],
queueRunnerFactory: queueRunner
});
processor.execute();
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -702,25 +794,39 @@ describe("TreeProcessor", function() {
expect(leaf3.execute).toHaveBeenCalled();
});
it("runs large segments of nodes in the order they were declared", function() {
it('runs large segments of nodes in the order they were declared', function() {
var leaf1 = new Leaf(),
leaf2 = new Leaf(),
leaf3 = new Leaf(),
leaf4 = new Leaf(),
leaf5 = new Leaf(),
leaf6 = new Leaf(),
leaf7 = new Leaf(),
leaf8 = new Leaf(),
leaf9 = new Leaf(),
leaf10 = new Leaf(),
leaf11 = new Leaf(),
root = new Node({ children: [leaf1, leaf2, leaf3, leaf4, leaf5, leaf6, leaf7, leaf8, leaf9, leaf10, leaf11] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [root.id],
queueRunnerFactory: queueRunner
});
leaf2 = new Leaf(),
leaf3 = new Leaf(),
leaf4 = new Leaf(),
leaf5 = new Leaf(),
leaf6 = new Leaf(),
leaf7 = new Leaf(),
leaf8 = new Leaf(),
leaf9 = new Leaf(),
leaf10 = new Leaf(),
leaf11 = new Leaf(),
root = new Node({
children: [
leaf1,
leaf2,
leaf3,
leaf4,
leaf5,
leaf6,
leaf7,
leaf8,
leaf9,
leaf10,
leaf11
]
}),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [root.id],
queueRunnerFactory: queueRunner
});
processor.execute();
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -760,29 +866,43 @@ describe("TreeProcessor", function() {
expect(leaf11.execute).toHaveBeenCalled();
});
it("runs nodes in a custom order when orderChildren is overridden", function() {
it('runs nodes in a custom order when orderChildren is overridden', function() {
var leaf1 = new Leaf(),
leaf2 = new Leaf(),
leaf3 = new Leaf(),
leaf4 = new Leaf(),
leaf5 = new Leaf(),
leaf6 = new Leaf(),
leaf7 = new Leaf(),
leaf8 = new Leaf(),
leaf9 = new Leaf(),
leaf10 = new Leaf(),
leaf11 = new Leaf(),
root = new Node({ children: [leaf1, leaf2, leaf3, leaf4, leaf5, leaf6, leaf7, leaf8, leaf9, leaf10, leaf11] }),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [root.id],
queueRunnerFactory: queueRunner,
orderChildren: function(node) {
var children = node.children.slice();
return children.reverse();
}
});
leaf2 = new Leaf(),
leaf3 = new Leaf(),
leaf4 = new Leaf(),
leaf5 = new Leaf(),
leaf6 = new Leaf(),
leaf7 = new Leaf(),
leaf8 = new Leaf(),
leaf9 = new Leaf(),
leaf10 = new Leaf(),
leaf11 = new Leaf(),
root = new Node({
children: [
leaf1,
leaf2,
leaf3,
leaf4,
leaf5,
leaf6,
leaf7,
leaf8,
leaf9,
leaf10,
leaf11
]
}),
queueRunner = jasmine.createSpy('queueRunner'),
processor = new jasmineUnderTest.TreeProcessor({
tree: root,
runnableIds: [root.id],
queueRunnerFactory: queueRunner,
orderChildren: function(node) {
var children = node.children.slice();
return children.reverse();
}
});
processor.execute();
var queueableFns = queueRunner.calls.mostRecent().args[0].queueableFns;
@@ -820,6 +940,5 @@ describe("TreeProcessor", function() {
queueableFns[10].fn();
expect(leaf1.execute).toHaveBeenCalled();
});
});

View File

@@ -1,7 +1,7 @@
describe("UserContext", function() {
it("Behaves just like an plain object", function() {
describe('UserContext', function() {
it('Behaves just like an plain object', function() {
var context = new jasmineUnderTest.UserContext(),
properties = [];
properties = [];
for (var prop in context) {
if (obj.hasOwnProperty(prop)) {
@@ -51,4 +51,3 @@ describe("UserContext", function() {
});
});
});

View File

@@ -1,11 +1,11 @@
describe("jasmineUnderTest.util", function() {
describe("isArray_", function() {
it("should return true if the argument is an array", function() {
describe('jasmineUnderTest.util', function() {
describe('isArray_', function() {
it('should return true if the argument is an array', function() {
expect(jasmineUnderTest.isArray_([])).toBe(true);
expect(jasmineUnderTest.isArray_(['a'])).toBe(true);
});
it("should return false if the argument is not an array", function() {
it('should return false if the argument is not an array', function() {
expect(jasmineUnderTest.isArray_(undefined)).toBe(false);
expect(jasmineUnderTest.isArray_({})).toBe(false);
expect(jasmineUnderTest.isArray_(function() {})).toBe(false);
@@ -15,13 +15,13 @@ describe("jasmineUnderTest.util", function() {
});
});
describe("isObject_", function() {
it("should return true if the argument is an object", function() {
describe('isObject_', function() {
it('should return true if the argument is an object', function() {
expect(jasmineUnderTest.isObject_({})).toBe(true);
expect(jasmineUnderTest.isObject_({an: "object"})).toBe(true);
expect(jasmineUnderTest.isObject_({ an: 'object' })).toBe(true);
});
it("should return false if the argument is not an object", function() {
it('should return false if the argument is not an object', function() {
expect(jasmineUnderTest.isObject_(undefined)).toBe(false);
expect(jasmineUnderTest.isObject_([])).toBe(false);
expect(jasmineUnderTest.isObject_(function() {})).toBe(false);
@@ -31,29 +31,126 @@ describe("jasmineUnderTest.util", function() {
});
});
describe("isUndefined", function() {
it("reports if a variable is defined", function() {
describe('promise utils', function() {
var mockNativePromise, mockPromiseLikeObject;
var mockPromiseLike = function() {
this.then = function() {};
};
beforeEach(function() {
jasmine.getEnv().requirePromises();
mockNativePromise = new Promise(function(res, rej) {}); // eslint-disable-line compat/compat
mockPromiseLikeObject = new mockPromiseLike();
});
describe('isPromise', function() {
it('should return true when passed a native promise', function() {
expect(jasmineUnderTest.isPromise(mockNativePromise)).toBe(true);
});
it('should return false for promise like objects', function() {
expect(jasmineUnderTest.isPromise(mockPromiseLikeObject)).toBe(false);
});
it('should return false for strings', function() {
expect(jasmineUnderTest.isPromise('hello')).toBe(false);
});
it('should return false for numbers', function() {
expect(jasmineUnderTest.isPromise(3)).toBe(false);
});
it('should return false for null', function() {
expect(jasmineUnderTest.isPromise(null)).toBe(false);
});
it('should return false for undefined', function() {
expect(jasmineUnderTest.isPromise(undefined)).toBe(false);
});
it('should return false for arrays', function() {
expect(jasmineUnderTest.isPromise([])).toBe(false);
});
it('should return false for objects', function() {
expect(jasmineUnderTest.isPromise({})).toBe(false);
});
it('should return false for boolean values', function() {
expect(jasmineUnderTest.isPromise(true)).toBe(false);
});
});
describe('isPromiseLike', function() {
it('should return true when passed a native promise', function() {
expect(jasmineUnderTest.isPromiseLike(mockNativePromise)).toBe(true);
});
it('should return true for promise like objects', function() {
expect(jasmineUnderTest.isPromiseLike(mockPromiseLikeObject)).toBe(
true
);
});
it('should return false if then is not a function', function() {
expect(
jasmineUnderTest.isPromiseLike({ then: { its: 'Not a function :O' } })
).toBe(false);
});
it('should return false for strings', function() {
expect(jasmineUnderTest.isPromiseLike('hello')).toBe(false);
});
it('should return false for numbers', function() {
expect(jasmineUnderTest.isPromiseLike(3)).toBe(false);
});
it('should return false for null', function() {
expect(jasmineUnderTest.isPromiseLike(null)).toBe(false);
});
it('should return false for undefined', function() {
expect(jasmineUnderTest.isPromiseLike(undefined)).toBe(false);
});
it('should return false for arrays', function() {
expect(jasmineUnderTest.isPromiseLike([])).toBe(false);
});
it('should return false for objects', function() {
expect(jasmineUnderTest.isPromiseLike({})).toBe(false);
});
it('should return false for boolean values', function() {
expect(jasmineUnderTest.isPromiseLike(true)).toBe(false);
});
});
});
describe('isUndefined', function() {
it('reports if a variable is defined', function() {
var a;
expect(jasmineUnderTest.util.isUndefined(a)).toBe(true);
expect(jasmineUnderTest.util.isUndefined(undefined)).toBe(true);
var undefined = "diz be undefined yo";
var undefined = 'diz be undefined yo';
expect(jasmineUnderTest.util.isUndefined(undefined)).toBe(false);
});
});
describe("getPropertyDescriptor", function() {
it("get property descriptor from object", function() {
var obj = {prop: 1},
describe('getPropertyDescriptor', function() {
it('get property descriptor from object', function() {
var obj = { prop: 1 },
actual = jasmineUnderTest.util.getPropertyDescriptor(obj, 'prop'),
expected = Object.getOwnPropertyDescriptor(obj, 'prop');
expect(actual).toEqual(expected);
});
it("get property descriptor from object property", function() {
var proto = {prop: 1},
obj = Object.create(proto),
it('get property descriptor from object property', function() {
var proto = { prop: 1 },
actual = jasmineUnderTest.util.getPropertyDescriptor(proto, 'prop'),
expected = Object.getOwnPropertyDescriptor(proto, 'prop');
@@ -61,8 +158,8 @@ describe("jasmineUnderTest.util", function() {
});
});
describe("objectDifference", function() {
it("given two objects A and B, returns the properties in A not present in B", function() {
describe('objectDifference', function() {
it('given two objects A and B, returns the properties in A not present in B', function() {
var a = {
foo: 3,
bar: 4,
@@ -74,10 +171,13 @@ describe("jasmineUnderTest.util", function() {
quux: 7
};
expect(jasmineUnderTest.util.objectDifference(a, b)).toEqual({foo: 3, baz: 5})
expect(jasmineUnderTest.util.objectDifference(a, b)).toEqual({
foo: 3,
baz: 5
});
});
it("only looks at own properties of both objects", function() {
it('only looks at own properties of both objects', function() {
function Foo() {}
Foo.prototype.x = 1;
@@ -89,13 +189,13 @@ describe("jasmineUnderTest.util", function() {
var b = new Foo();
b.y = 2;
expect(jasmineUnderTest.util.objectDifference(a, b)).toEqual({x: 1});
expect(jasmineUnderTest.util.objectDifference(b, a)).toEqual({y: 2});
expect(jasmineUnderTest.util.objectDifference(a, b)).toEqual({ x: 1 });
expect(jasmineUnderTest.util.objectDifference(b, a)).toEqual({ y: 2 });
});
});
describe("jasmineFile", function() {
it("returns the file containing jasmine.util", function() {
describe('jasmineFile', function() {
it('returns the file containing jasmine.util', function() {
// Chrome sometimes reports foo.js as foo.js/, so tolerate
// a trailing slash if present.
expect(jasmineUnderTest.util.jasmineFile()).toMatch(/util.js\/?$/);

View File

@@ -0,0 +1,101 @@
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 all the properties of the customEqualityTesters', function() {
var customEqualityTesters = [function() {}, function() {}],
shim = jasmineUnderTest.asymmetricEqualityTesterArgCompatShim(
{},
customEqualityTesters
);
expect(shim.length).toBe(2);
expect(shim[0]).toBe(customEqualityTesters[0]);
expect(shim[1]).toBe(customEqualityTesters[1]);
});
it('provides all the properties of Array.prototype', function() {
var shim = jasmineUnderTest.asymmetricEqualityTesterArgCompatShim({}, []);
expect(shim.filter).toBe(Array.prototype.filter);
expect(shim.forEach).toBe(Array.prototype.forEach);
expect(shim.map).toBe(Array.prototype.map);
});
it('provides properties of Array.prototype', function() {
var keys = [
'concat',
'constructor',
'every',
'filter',
'forEach',
'indexOf',
'join',
'lastIndexOf',
'length',
'map',
'pop',
'push',
'reduce',
'reduceRight',
'reverse',
'shift',
'slice',
'some',
'sort',
'splice',
'toLocaleString',
'toString',
'unshift'
],
optionalKeys = [
'copyWithin',
'entries',
'fill',
'find',
'findIndex',
'flat',
'flatMap',
'includes',
'keys',
'toSource',
'values'
],
shim = jasmineUnderTest.asymmetricEqualityTesterArgCompatShim({}, []),
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]);
}
// 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]);
}
}
});
});

View File

@@ -34,7 +34,7 @@ describe("Any", function() {
var any = new jasmineUnderTest.Any(Map);
expect(any.asymmetricMatch(new Map())).toBe(true);
expect(any.asymmetricMatch(new Map())).toBe(true); // eslint-disable-line compat/compat
});
it("matches a Set", function() {
@@ -42,23 +42,23 @@ describe("Any", function() {
var any = new jasmineUnderTest.Any(Set);
expect(any.asymmetricMatch(new Set())).toBe(true);
expect(any.asymmetricMatch(new Set())).toBe(true); // eslint-disable-line compat/compat
});
it("matches a TypedArray", function() {
jasmine.getEnv().requireFunctioningTypedArrays();
var any = new jasmineUnderTest.Any(Uint32Array);
var any = new jasmineUnderTest.Any(Uint32Array); // eslint-disable-line compat/compat
expect(any.asymmetricMatch(new Uint32Array([]))).toBe(true);
expect(any.asymmetricMatch(new Uint32Array([]))).toBe(true); // eslint-disable-line compat/compat
});
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);
expect(any.asymmetricMatch(Symbol())).toBe(true); // eslint-disable-line compat/compat
});
it("matches another constructed object", function() {

View File

@@ -28,7 +28,7 @@ describe("Anything", function() {
var anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch(new Map())).toBe(true);
expect(anything.asymmetricMatch(new Map())).toBe(true); // eslint-disable-line compat/compat
});
it("matches a Set", function() {
@@ -36,7 +36,7 @@ describe("Anything", function() {
var anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch(new Set())).toBe(true);
expect(anything.asymmetricMatch(new Set())).toBe(true); // eslint-disable-line compat/compat
});
it("matches a TypedArray", function() {
@@ -44,7 +44,7 @@ describe("Anything", function() {
var anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch(new Uint32Array([]))).toBe(true);
expect(anything.asymmetricMatch(new Uint32Array([]))).toBe(true); // eslint-disable-line compat/compat
});
it("matches a Symbol", function() {
@@ -52,7 +52,7 @@ describe("Anything", function() {
var anything = new jasmineUnderTest.Anything();
expect(anything.asymmetricMatch(Symbol())).toBe(true);
expect(anything.asymmetricMatch(Symbol())).toBe(true); // eslint-disable-line compat/compat
});
it("doesn't match undefined", function() {

View File

@@ -15,26 +15,41 @@ describe("ArrayContaining", function() {
it("matches when the item is in the actual", function() {
var containing = new jasmineUnderTest.ArrayContaining(["foo"]);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(["foo"])).toBe(true);
expect(containing.asymmetricMatch(["foo"], matchersUtil)).toBe(true);
});
it("matches when additional items are in the actual", function() {
var containing = new jasmineUnderTest.ArrayContaining(["foo"]);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(["foo", "bar"])).toBe(true);
expect(containing.asymmetricMatch(["foo", "bar"], matchersUtil)).toBe(true);
});
it("does not match when the item is not in the actual", function() {
var containing = new jasmineUnderTest.ArrayContaining(["foo"]);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(["bar"])).toBe(false);
expect(containing.asymmetricMatch(["bar"], matchersUtil)).toBe(false);
});
it("does not match when the actual is not an array", function() {
var containing = new jasmineUnderTest.ArrayContaining(["foo"]);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch("foo", matchersUtil)).toBe(false);
});
it("jasmineToStrings itself", function() {
var containing = new jasmineUnderTest.ArrayContaining([]);
var sample = [],
matcher = new jasmineUnderTest.ArrayContaining(sample),
pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(containing.jasmineToString()).toMatch("<jasmine.arrayContaining");
expect(matcher.jasmineToString(pp)).toEqual(
'<jasmine.arrayContaining(sample)>'
);
expect(pp).toHaveBeenCalledWith(sample);
});
it("uses custom equality testers", function() {
@@ -46,7 +61,8 @@ describe("ArrayContaining", function() {
}
};
var containing = new jasmineUnderTest.ArrayContaining(["fooVal"]);
var matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester]});
expect(containing.asymmetricMatch(["fooBar"], [tester])).toBe(true);
expect(containing.asymmetricMatch(["fooBar"], matchersUtil)).toBe(true);
});
});

View File

@@ -1,8 +1,9 @@
describe("ArrayWithExactContents", function() {
it("matches an array with the same items in a different order", function() {
var matcher = new jasmineUnderTest.ArrayWithExactContents(['a', 2, /a/]);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matcher.asymmetricMatch([2, 'a', /a/])).toBe(true);
expect(matcher.asymmetricMatch([2, 'a', /a/], matchersUtil)).toBe(true);
});
it("does not work when not passed an array", function() {
@@ -15,21 +16,28 @@ describe("ArrayWithExactContents", function() {
it("does not match when an item is missing", function() {
var matcher = new jasmineUnderTest.ArrayWithExactContents(['a', 2, /a/]);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matcher.asymmetricMatch(['a', 2])).toBe(false);
expect(matcher.asymmetricMatch(['a', 2, undefined])).toBe(false);
expect(matcher.asymmetricMatch(['a', 2], matchersUtil)).toBe(false);
expect(matcher.asymmetricMatch(['a', 2, undefined], matchersUtil)).toBe(false);
});
it("does not match when there is an extra item", function() {
var matcher = new jasmineUnderTest.ArrayWithExactContents(['a']);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matcher.asymmetricMatch(['a', 2])).toBe(false);
expect(matcher.asymmetricMatch(['a', 2], matchersUtil)).toBe(false);
});
it("jasmineToStrings itself", function() {
var matcher = new jasmineUnderTest.ArrayWithExactContents([]);
var sample = [],
matcher = new jasmineUnderTest.ArrayWithExactContents(sample),
pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(matcher.jasmineToString()).toMatch("<jasmine.arrayWithExactContents");
expect(matcher.jasmineToString(pp)).toEqual(
'<jasmine.arrayWithExactContents(sample)>'
);
expect(pp).toHaveBeenCalledWith(sample);
});
it("uses custom equality testers", function() {
@@ -41,7 +49,8 @@ describe("ArrayWithExactContents", function() {
}
};
var matcher = new jasmineUnderTest.ArrayWithExactContents(["fooVal"]);
var matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester]});
expect(matcher.asymmetricMatch(["fooBar"], [tester])).toBe(true);
expect(matcher.asymmetricMatch(["fooBar"], matchersUtil)).toBe(true);
});
});

View File

@@ -24,20 +24,20 @@ describe("Empty", function () {
it("matches an empty map", function () {
jasmine.getEnv().requireFunctioningMaps();
var empty = new jasmineUnderTest.Empty();
var fullMap = new Map();
var fullMap = new Map(); // eslint-disable-line compat/compat
fullMap.set('thing', 2);
expect(empty.asymmetricMatch(new Map())).toBe(true);
expect(empty.asymmetricMatch(new Map())).toBe(true); // eslint-disable-line compat/compat
expect(empty.asymmetricMatch(fullMap)).toBe(false);
});
it("matches an empty set", function () {
jasmine.getEnv().requireFunctioningSets();
var empty = new jasmineUnderTest.Empty();
var fullSet = new Set();
var fullSet = new Set(); // eslint-disable-line compat/compat
fullSet.add(3);
expect(empty.asymmetricMatch(new Set())).toBe(true);
expect(empty.asymmetricMatch(new Set())).toBe(true); // eslint-disable-line compat/compat
expect(empty.asymmetricMatch(fullSet)).toBe(false);
});
@@ -45,7 +45,7 @@ describe("Empty", function () {
jasmine.getEnv().requireFunctioningTypedArrays();
var empty = new jasmineUnderTest.Empty();
expect(empty.asymmetricMatch(new Int16Array())).toBe(true);
expect(empty.asymmetricMatch(new Int16Array([1,2]))).toBe(false);
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
});
});

View File

@@ -0,0 +1,197 @@
/* 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 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([
['foo', [1, 2, 3]],
[{'foo': 'bar'}, 'baz'],
['other', 'any'],
]);
var containingMap = new MapI([
[{'foo': 'bar'}, 'baz'],
['foo', [1, 2, 3]],
]);
var containing = new jasmineUnderTest.MapContaining(containingMap);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
});
it('does not match when a key is not in actual', function() {
var actualMap = new MapI([
['foo', [1, 2, 3]],
[{'foo': 'not a bar'}, 'baz'],
]);
var containingMap = new MapI([
[{'foo': 'bar'}, 'baz'],
['foo', [1, 2, 3]],
]);
var containing = new jasmineUnderTest.MapContaining(containingMap);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
});
it('does not match when a value is not in actual', function() {
var actualMap = new MapI([
['foo', [1, 2, 3]],
[{'foo': 'bar'}, 'baz'],
]);
var containingMap = new MapI([
[{'foo': 'bar'}, 'baz'],
['foo', [1, 2]],
]);
var containing = new jasmineUnderTest.MapContaining(containingMap);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
});
it('matches when all the key/value pairs in sample have asymmetric matches in actual', function() {
var actualMap = new MapI([
['foo1', 'not a bar'],
['foo2', 'bar'],
['baz', [1, 2, 3, 4]],
]);
var containingMap = new MapI([
[
jasmineUnderTest.stringMatching(/^foo\d/),
'bar'
],
[
'baz',
jasmineUnderTest.arrayContaining([2, 3])
],
]);
var containing = new jasmineUnderTest.MapContaining(containingMap);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
});
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 containingMap = new MapI([
[
jasmineUnderTest.stringMatching(/^foo\d/),
'bar'
],
[
'baz',
jasmineUnderTest.arrayContaining([2, 3])
],
]);
var containing = new jasmineUnderTest.MapContaining(containingMap);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
});
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 containingMap = new MapI([
[
jasmineUnderTest.stringMatching(/^foo\d/),
'bar'
],
[
'baz',
jasmineUnderTest.arrayContaining([4, 5])
],
]);
var containing = new jasmineUnderTest.MapContaining(containingMap);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(false);
});
it('matches recursively', function() {
var actualMap = new MapI([
['foo', new MapI([['foo1', 1], ['foo2', 2]])],
[new MapI([[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 containing = new jasmineUnderTest.MapContaining(containingMap);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
});
it('uses custom equality testers', function() {
function tester(a, b) {
// treat all negative numbers as equal
return (typeof a == 'number' && typeof b == 'number') ? (a < 0 && b < 0) : a === b;
}
var actualMap = new MapI([['foo', -1]]);
var containing = new jasmineUnderTest.MapContaining(new MapI([['foo', -2]]));
var matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester]});
expect(containing.asymmetricMatch(actualMap, matchersUtil)).toBe(true);
});
it('does not match when actual is not a map', function() {
var containingMap = new MapI([['foo', 'bar']]);
expect(new jasmineUnderTest.MapContaining(containingMap).asymmetricMatch('foo')).toBe(false);
expect(new jasmineUnderTest.MapContaining(containingMap).asymmetricMatch(-1)).toBe(false);
expect(new jasmineUnderTest.MapContaining(containingMap).asymmetricMatch({'foo': 'bar'})).toBe(false);
});
it('throws an error when sample is not a map', function() {
expect(function() {
new jasmineUnderTest.MapContaining({'foo': 'bar'}).asymmetricMatch(new Map());
}).toThrowError(/You must provide a map/);
});
it('defines a `jasmineToString` method', function() {
var sample = new Map(),
containing = new jasmineUnderTest.MapContaining(sample),
pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(containing.jasmineToString(pp)).toEqual(
'<jasmine.mapContaining(sample)>'
);
expect(pp).toHaveBeenCalledWith(sample);
});
});

View File

@@ -24,9 +24,9 @@ describe("NotEmpty", function () {
it("matches a non empty map", function () {
jasmine.getEnv().requireFunctioningMaps();
var notEmpty = new jasmineUnderTest.NotEmpty();
var fullMap = new Map();
var fullMap = new Map(); // eslint-disable-line compat/compat
fullMap.set('one', 1);
var emptyMap = new Map();
var emptyMap = new Map(); // eslint-disable-line compat/compat
expect(notEmpty.asymmetricMatch(fullMap)).toBe(true);
expect(notEmpty.asymmetricMatch(emptyMap)).toBe(false);
@@ -35,9 +35,9 @@ describe("NotEmpty", function () {
it("matches a non empty set", function () {
jasmine.getEnv().requireFunctioningSets();
var notEmpty = new jasmineUnderTest.NotEmpty();
var filledSet = new Set();
var filledSet = new Set(); // eslint-disable-line compat/compat
filledSet.add(1);
var emptySet = new Set();
var emptySet = new Set(); // eslint-disable-line compat/compat
expect(notEmpty.asymmetricMatch(filledSet)).toBe(true);
expect(notEmpty.asymmetricMatch(emptySet)).toBe(false);
@@ -47,7 +47,7 @@ describe("NotEmpty", function () {
jasmine.getEnv().requireFunctioningTypedArrays();
var notEmpty = new jasmineUnderTest.NotEmpty();
expect(notEmpty.asymmetricMatch(new Int16Array([1,2,3]))).toBe(true);
expect(notEmpty.asymmetricMatch(new Int16Array())).toBe(false);
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
});
});

View File

@@ -1,9 +1,18 @@
describe("ObjectContaining", function() {
it("matches any actual to an empty object", function() {
it("matches any object actual to an empty object", function() {
var containing = new jasmineUnderTest.ObjectContaining({});
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({foo: 1}, matchersUtil)).toBe(true);
});
it("does not match when the actual is not an object", function() {
var containing = new jasmineUnderTest.ObjectContaining({});
expect(containing.asymmetricMatch("foo")).toBe(true);
[1, true, undefined, "a string"].forEach(function(actual) {
expect(containing.asymmetricMatch(actual)).toBe(false);
});
});
it("does not match an empty object actual", function() {
@@ -16,58 +25,72 @@ describe("ObjectContaining", function() {
it("matches when the key/value pair is present in the actual", function() {
var containing = new jasmineUnderTest.ObjectContaining({foo: "fooVal"});
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({foo: "fooVal", bar: "barVal"})).toBe(true);
expect(containing.asymmetricMatch({foo: "fooVal", bar: "barVal"}, matchersUtil)).toBe(true);
});
it("does not match when the key/value pair is not present in the actual", function() {
var containing = new jasmineUnderTest.ObjectContaining({foo: "fooVal"});
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({bar: "barVal", quux: "quuxVal"})).toBe(false);
expect(containing.asymmetricMatch({bar: "barVal", quux: "quuxVal"}, matchersUtil)).toBe(false);
});
it("does not match when the key is present but the value is different in the actual", function() {
var containing = new jasmineUnderTest.ObjectContaining({foo: "other"});
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({foo: "fooVal", bar: "barVal"})).toBe(false);
expect(containing.asymmetricMatch({foo: "fooVal", bar: "barVal"}, matchersUtil)).toBe(false);
});
it("jasmineToString's itself", function() {
var containing = new jasmineUnderTest.ObjectContaining({});
var sample = {},
matcher = new jasmineUnderTest.ObjectContaining(sample),
pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(matcher.jasmineToString(pp)).toEqual(
'<jasmine.objectContaining(sample)>'
);
expect(pp).toHaveBeenCalledWith(sample);
expect(containing.jasmineToString()).toMatch("<jasmine.objectContaining");
});
it("matches recursively", function() {
var containing = new jasmineUnderTest.ObjectContaining({one: new jasmineUnderTest.ObjectContaining({two: {}})});
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({one: {two: {}}})).toBe(true);
expect(containing.asymmetricMatch({one: {two: {}}}, matchersUtil)).toBe(true);
});
it("matches when key is present with undefined value", function() {
var containing = new jasmineUnderTest.ObjectContaining({ one: undefined });
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({ one: undefined })).toBe(true);
expect(containing.asymmetricMatch({ one: undefined }, matchersUtil)).toBe(true);
});
it("does not match when key with undefined value is not present", function() {
var containing = new jasmineUnderTest.ObjectContaining({ one: undefined });
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch({})).toBe(false);
expect(containing.asymmetricMatch({}, matchersUtil)).toBe(false);
});
it("matches defined properties", function(){
var containing = new jasmineUnderTest.ObjectContaining({ foo: "fooVal" });
var matchersUtil = new jasmineUnderTest.MatchersUtil();
var definedPropertyObject = {};
Object.defineProperty(definedPropertyObject, "foo", {
get: function() { return "fooVal" }
});
expect(containing.asymmetricMatch(definedPropertyObject)).toBe(true);
expect(containing.asymmetricMatch(definedPropertyObject, matchersUtil)).toBe(true);
});
it("matches prototype properties", function(){
var containing = new jasmineUnderTest.ObjectContaining({ foo: "fooVal" });
var matchersUtil = new jasmineUnderTest.MatchersUtil();
var prototypeObject = {foo: "fooVal"};
var obj;
@@ -81,7 +104,7 @@ describe("ObjectContaining", function() {
obj = new Foo();
}
expect(containing.asymmetricMatch(obj)).toBe(true);
expect(containing.asymmetricMatch(obj, matchersUtil)).toBe(true);
});
it("uses custom equality testers", function() {
@@ -93,7 +116,70 @@ describe("ObjectContaining", function() {
}
};
var containing = new jasmineUnderTest.ObjectContaining({foo: "fooVal"});
var matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester]});
expect(containing.asymmetricMatch({foo: "fooBar"}, [tester])).toBe(true);
expect(containing.asymmetricMatch({foo: "fooBar"}, matchersUtil)).toBe(true);
});
describe("valuesForDiff_", function() {
describe("when other is not an object", function() {
it("sets self to jasmineToString()", function () {
var containing = new jasmineUnderTest.ObjectContaining({}),
pp = jasmineUnderTest.makePrettyPrinter(),
result = containing.valuesForDiff_('a', pp);
expect(result).toEqual({
self: '<jasmine.objectContaining(Object({ }))>',
other: 'a'
});
});
});
describe("when other is an object", function() {
it("includes keys that are present in both other and sample", function() {
var sample = {a: 1, b: 2},
other = {a: 3, b: 4},
containing = new jasmineUnderTest.ObjectContaining(sample),
result = containing.valuesForDiff_(other);
expect(result.self).not.toBeInstanceOf(jasmineUnderTest.ObjectContaining);
expect(result).toEqual({
self: sample,
other: other
});
});
it("includes keys that are present only in sample", function() {
var sample = {a: 1, b: 2},
other = {a: 3},
containing = new jasmineUnderTest.ObjectContaining(sample),
result = containing.valuesForDiff_(other);
expect(result.self).not.toBeInstanceOf(jasmineUnderTest.ObjectContaining);
expect(containing.valuesForDiff_(other)).toEqual({
self: sample,
other: {
a: 3,
b: undefined
}
});
});
it("omits keys that are present only in other", function() {
var sample = {a: 1, b: 2},
other = {a: 3, b: 4, c: 5},
containing = new jasmineUnderTest.ObjectContaining(sample),
result = containing.valuesForDiff_(other);
expect(result.self).not.toBeInstanceOf(jasmineUnderTest.ObjectContaining);
expect(result).toEqual({
self: sample,
other: {
a: 3,
b: 4
}
});
});
});
});
});

View File

@@ -0,0 +1,130 @@
/* 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 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 containingSet = new SetI([
[1, 2, 3], {'foo': 'bar'}
]);
var containing = new jasmineUnderTest.SetContaining(containingSet);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(true);
});
it('does not match when a value is not in actual', function() {
var actualSet = new SetI([
{'foo': 'bar'}, 'baz', [1, 2, 3]
]);
var containingSet = new SetI([
[1, 2], {'foo': 'bar'}
]);
var containing = new jasmineUnderTest.SetContaining(containingSet);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(false);
});
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 containingSet = new SetI([
jasmineUnderTest.stringMatching(/^foo\d/),
jasmineUnderTest.arrayContaining([2, 3]),
]);
var containing = new jasmineUnderTest.SetContaining(containingSet);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(true);
});
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 containingSet = new SetI([
jasmine.stringMatching(/^foo\d/),
jasmine.arrayContaining([2, 3]),
]);
var containing = new jasmineUnderTest.SetContaining(containingSet);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(false);
});
it('matches recursively', function() {
var actualSet = new SetI([
'foo', new SetI([1, 'bar', 2]), 'other'
]);
var containingSet = new SetI([
new jasmineUnderTest.SetContaining(new SetI(['bar'])), 'foo'
]);
var containing = new jasmineUnderTest.SetContaining(containingSet);
var matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(true);
});
it('uses custom equality testers', function() {
function tester(a, b) {
// treat all negative numbers as equal
return (typeof a == 'number' && typeof b == 'number') ? (a < 0 && b < 0) : a === b;
}
var actualSet = new SetI(['foo', -1]);
var containing = new jasmineUnderTest.SetContaining(new SetI([-2, 'foo']));
var matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester]});
expect(containing.asymmetricMatch(actualSet, matchersUtil)).toBe(true);
});
it('does not match when actual is not a set', function() {
var containingSet = new SetI(['foo']);
expect(new jasmineUnderTest.SetContaining(containingSet).asymmetricMatch('foo')).toBe(false);
expect(new jasmineUnderTest.SetContaining(containingSet).asymmetricMatch(1)).toBe(false);
expect(new jasmineUnderTest.SetContaining(containingSet).asymmetricMatch(['foo'])).toBe(false);
});
it('throws an error when sample is not a set', function() {
expect(function() {
new jasmineUnderTest.SetContaining({'foo': 'bar'}).asymmetricMatch(new Set());
}).toThrowError(/You must provide a set/);
});
it('defines a `jasmineToString` method', function() {
var sample = new Set(),
containing = new jasmineUnderTest.SetContaining(sample),
pp = jasmine.createSpy('pp').and.returnValue('sample');
expect(containing.jasmineToString(pp)).toEqual(
'<jasmine.setContaining(sample)>'
);
expect(pp).toHaveBeenCalledWith(sample);
});
});

65
spec/core/baseSpec.js Normal file
View File

@@ -0,0 +1,65 @@
describe('base helpers', function() {
describe('isError_', function() {
it('correctly handles WebSocket events', function(done) {
if (typeof jasmine.getGlobal().WebSocket === 'undefined') {
done();
return;
}
var obj = (function() {
var sock = new WebSocket('ws://localhost');
var event;
sock.onerror = function(e) {
event = e;
};
return function() {
return event;
};
})();
var left = 20;
var int = setInterval(function() {
if (obj() || left === 0) {
var result = jasmineUnderTest.isError_(obj());
expect(result).toBe(false);
clearInterval(int);
done();
} else {
left--;
}
}, 100);
});
});
describe('isAsymmetricEqualityTester_', function() {
it('returns false when the argument is falsy', function() {
expect(jasmineUnderTest.isAsymmetricEqualityTester_(null)).toBe(false);
});
it('returns false when the argument does not have a asymmetricMatch property', function() {
var obj = {};
expect(jasmineUnderTest.isAsymmetricEqualityTester_(obj)).toBe(false);
});
it("returns false when the argument's asymmetricMatch is not a function", function() {
var obj = { asymmetricMatch: 'yes' };
expect(jasmineUnderTest.isAsymmetricEqualityTester_(obj)).toBe(false);
});
it("returns true when the argument's asymmetricMatch is a function", function() {
var obj = { asymmetricMatch: function() {} };
expect(jasmineUnderTest.isAsymmetricEqualityTester_(obj)).toBe(true);
});
});
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
});
it('returns false when the object is not a Set', function() {
expect(jasmineUnderTest.isSet({})).toBe(false);
});
});
});

View File

@@ -1,4 +1,4 @@
describe('formatErrorMsg', function () {
describe('formatErrorMsg', function() {
it('should format an error with a domain', function() {
var formator = jasmineUnderTest.formatErrorMsg('api');
expect(formator('message')).toBe('api : message');

View File

@@ -0,0 +1,222 @@
describe('Asymmetric equality testers (Integration)', function () {
function verifyPasses(expectations, setup) {
it('passes', function (done) {
var env = new jasmineUnderTest.Env();
env.it('a spec', function () {
expectations(env);
});
var specExpectations = function (result) {
expect(result.status).toEqual('passed');
expect(result.passedExpectations.length)
.withContext('Number of passed expectations')
.toEqual(1);
expect(result.failedExpectations.length)
.withContext('Number of failed expectations')
.toEqual(0);
expect(result.failedExpectations[0] && result.failedExpectations[0].message)
.withContext('Failure message')
.toBeUndefined();
};
env.addReporter({specDone: specExpectations, jasmineDone: done});
env.execute();
});
}
function verifyFails(expectations) {
it('fails', function (done) {
var env = new jasmineUnderTest.Env();
env.it('a spec', function () {
expectations(env);
});
var specExpectations = function (result) {
expect(result.status).toEqual('failed');
expect(result.failedExpectations.length)
.withContext('Number of failed expectations')
.toEqual(1);
expect(result.failedExpectations[0].message)
.withContext('Failed with a thrown error rather than a matcher failure')
.not.toMatch(/^Error: /);
expect(result.failedExpectations[0].matcherName).withContext('Matcher name')
.not.toEqual('');
};
env.addReporter({specDone: specExpectations, jasmineDone: done});
env.execute();
});
}
describe('any', function () {
verifyPasses(function (env) {
env.expect(5).toEqual(jasmineUnderTest.any(Number));
});
verifyFails(function (env) {
env.expect("five").toEqual(jasmineUnderTest.any(Number));
});
});
describe('anything', function () {
verifyPasses(function (env) {
env.expect('').toEqual(jasmineUnderTest.anything());
});
verifyFails(function (env) {
env.expect(null).toEqual(jasmineUnderTest.anything());
});
});
describe('arrayContaining', function () {
verifyPasses(function (env) {
env.addCustomEqualityTester(function (a, b) {
return a.toString() === b.toString();
});
env.expect([1, 2, 3]).toEqual(jasmineUnderTest.arrayContaining(["2"]));
});
verifyFails(function (env) {
env.expect(null).toEqual(jasmineUnderTest.arrayContaining([2]));
});
});
describe('arrayWithExactContents', function () {
verifyPasses(function (env) {
env.addCustomEqualityTester(function (a, b) {
return a.toString() === b.toString();
});
env.expect([1, 2]).toEqual(jasmineUnderTest.arrayWithExactContents(["2", "1"]));
});
verifyFails(function (env) {
env.expect([]).toEqual(jasmineUnderTest.arrayWithExactContents([2]));
});
});
describe('empty', function () {
verifyPasses(function (env) {
env.expect([]).toEqual(jasmineUnderTest.empty());
});
verifyFails(function (env) {
env.expect([1]).toEqual(jasmineUnderTest.empty());
});
});
describe('falsy', function () {
verifyPasses(function (env) {
env.expect(false).toEqual(jasmineUnderTest.falsy());
});
verifyFails(function (env) {
env.expect(true).toEqual(jasmineUnderTest.falsy());
});
});
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);
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');
});
}
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');
});
}
});
describe('notEmpty', function () {
verifyPasses(function (env) {
env.expect([1]).toEqual(jasmineUnderTest.notEmpty());
});
verifyFails(function (env) {
env.expect([]).toEqual(jasmineUnderTest.notEmpty());
});
});
describe('objectContaining', function () {
verifyPasses(function (env) {
env.addCustomEqualityTester(function (a, b) {
return a.toString() === b.toString();
});
env.expect({a: 1, b: 2}).toEqual(jasmineUnderTest.objectContaining({a: "1"}));
});
verifyFails(function (env) {
env.expect({}).toEqual(jasmineUnderTest.objectContaining({a: "1"}));
});
});
describe('setContaining', function () {
if (jasmine.getEnv().hasFunctioningSets()) {
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.expect(actual).toEqual(jasmineUnderTest.setContaining(expected));
});
} else {
it('pases', function() {
jasmine.getEnv().pending('Browser has incomplete or missing support for Sets');
});
}
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');
});
}
});
describe('stringMatching', function () {
verifyPasses(function (env) {
env.expect('foo').toEqual(jasmineUnderTest.stringMatching(/o/));
});
verifyFails(function (env) {
env.expect('bar').toEqual(jasmineUnderTest.stringMatching(/o/));
});
});
describe('truthy', function () {
verifyPasses(function (env) {
env.expect(true).toEqual(jasmineUnderTest.truthy());
});
verifyFails(function (env) {
env.expect(false).toEqual(jasmineUnderTest.truthy());
});
});
});

View File

@@ -0,0 +1,151 @@
/* eslint-disable compat/compat */
describe('Custom Async Matchers (Integration)', function() {
var env;
beforeEach(function() {
env = new jasmineUnderTest.Env();
env.configure({random: false});
});
afterEach(function() {
env.cleanup_();
});
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() {
return { compare: function() { return Promise.resolve({ pass: true }); } };
}
});
return env.expectAsync(true).toBeReal();
});
var specExpectations = function(result) {
expect(result.status).toEqual('passed');
};
env.addReporter({ specDone: specExpectations, jasmineDone: done });
env.execute();
});
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() {
return {
compare: function() { return Promise.resolve({ pass: true }); },
negativeCompare: function() { return Promise.resolve({ pass: true }); }
};
}
});
return env.expectAsync(true).not.toBeReal();
});
var specExpectations = function(result) {
expect(result.status).toEqual('passed');
};
env.addReporter({ specDone: specExpectations, jasmineDone: done });
env.execute();
});
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() {
return {
compare: function() {
return Promise.resolve({ pass: false });
}
};
}
});
return env.expectAsync('a').toBeReal();
});
var specExpectations = function(result) {
expect(result.failedExpectations[0].message).toEqual("Expected 'a' to be real.");
};
env.addReporter({ specDone: specExpectations, jasmineDone: done });
env.execute();
});
// TODO: remove this in the next major release.
it("passes the jasmine utility and current equality testers to the matcher factory", function(done) {
jasmine.getEnv().requirePromises();
var matcherFactory = function () {
return {
compare: function () {
return Promise.resolve({pass: true});
}
};
},
matcherFactorySpy = jasmine.createSpy("matcherFactorySpy").and.callFake(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]
);
};
env.addReporter({ specDone: specExpectations, jasmineDone: 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) {
return Promise.resolve({pass: matchersUtil.equals(actual[0], expected)});
}
};
},
customEqualityFn = jasmine.createSpy("customEqualityFn").and.callFake(function (a, b) {
return a.toString() === b;
});
env.it("spec with expectation", function() {
env.addCustomEqualityTester(customEqualityFn);
env.addAsyncMatchers({
toBeArrayWithFirstElement: matcherFactory
});
return env.expectAsync([1, 2]).toBeArrayWithFirstElement("1");
});
var specExpectations = function(result) {
expect(customEqualityFn).toHaveBeenCalledWith(1, "1");
expect(result.failedExpectations).toEqual([]);
};
env.addReporter({ specDone: specExpectations, jasmineDone: done });
env.execute();
});
});

View File

@@ -1,19 +1,23 @@
describe("Custom Matchers (Integration)", function() {
describe("Custom Matchers (Integration)", function () {
var env;
var fakeTimer;
beforeEach(function() {
beforeEach(function () {
env = new jasmineUnderTest.Env();
env.randomizeTests(false);
env.configure({random: false});
});
it("allows adding more matchers local to a spec", function(done) {
env.it('spec defining a custom matcher', function() {
afterEach(function() {
env.cleanup_();
});
it("allows adding more matchers local to a spec", function (done) {
env.it('spec defining a custom matcher', function () {
env.addMatchers({
matcherForSpec: function() {
matcherForSpec: function () {
return {
compare: function(actual, expected) {
return { pass: false, message: "matcherForSpec: actual: " + actual + "; expected: " + expected };
compare: function (actual, expected) {
return {pass: false, message: "matcherForSpec: actual: " + actual + "; expected: " + expected};
}
}
}
@@ -81,6 +85,36 @@ describe("Custom Matchers (Integration)", function() {
env.execute();
});
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);
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, jasmineDone: done });
env.execute();
});
it("displays an appropriate failure message if a custom equality matcher fails", function(done) {
env.it("spec using custom equality matcher", function() {
var customEqualityFn = function(a, b) {
@@ -175,26 +209,60 @@ describe("Custom Matchers (Integration)", function() {
env.execute();
});
it("passes the jasmine utility and current equality matchers to the expectation factory", function(done) {
// TODO: remove this in the next major release.
it("passes the jasmine utility and current equality testers to the matcher factory", function(done) {
var matcherFactory = function() { return { compare: function() { return {pass: true}; }}; },
argumentSpy = jasmine.createSpy("argument spy").and.returnValue(matcherFactory),
matcherFactorySpy = jasmine.createSpy("matcherFactorySpy").and.callFake(matcherFactory),
customEqualityFn = function() { return true; };
env.it("spec with expectation", function() {
env.addCustomEqualityTester(customEqualityFn);
env.addMatchers({
toBeReal: argumentSpy
toBeReal: matcherFactorySpy
});
env.expect(true).toBeReal();
});
var specExpectations = function() {
expect(argumentSpy).toHaveBeenCalledWith(jasmineUnderTest.matchersUtil, [customEqualityFn]);
expect(matcherFactorySpy).toHaveBeenCalledWith(
jasmine.any(jasmineUnderTest.MatchersUtil),
[customEqualityFn]
);
};
env.addReporter({ specDone: specExpectations, jasmineDone: done });
env.execute();
});
it("provides custom equality testers to the matcher factory via matchersUtil", function (done) {
var matcherFactory = function (matchersUtil) {
return {
compare: function (actual, expected) {
return {pass: matchersUtil.equals(actual[0], expected)};
}
};
},
customEqualityFn = jasmine.createSpy("customEqualityFn").and.callFake(function (a, b) {
return a.toString() === b;
});
env.it("spec with expectation", function () {
env.addCustomEqualityTester(customEqualityFn);
env.addMatchers({
toBeArrayWithFirstElement: matcherFactory
});
env.expect([1, 2]).toBeArrayWithFirstElement("1");
});
var specExpectations = function (result) {
expect(customEqualityFn).toHaveBeenCalledWith(1, "1");
expect(result.failedExpectations).toEqual([]);
};
env.addReporter({specDone: specExpectations, jasmineDone: done});
env.execute();
});
});

View File

@@ -0,0 +1,67 @@
describe("Custom object formatters", function() {
var env;
beforeEach(function() {
env = new jasmineUnderTest.Env();
env.configure({random: false});
});
it("scopes custom object formatters to a spec", function(done) {
env.it('a spec with custom pretty-printer', function() {
env.addCustomObjectFormatter(function(obj) { return 'custom(' + obj + ')'; });
env.expect(42).toBeUndefined();
});
env.it('a spec without custom pretty-printer', function() {
env.expect(42).toBeUndefined();
});
var specResults = [];
var specDone = function(result) {
specResults.push(result);
};
var expectations = function() {
expect(specResults[0].failedExpectations[0].message).toEqual("Expected custom(42) to be undefined.");
expect(specResults[1].failedExpectations[0].message).toEqual("Expected 42 to be undefined.");
done();
};
env.addReporter({ specDone:specDone, jasmineDone: expectations});
env.execute();
});
it("scopes custom object formatters to a suite", function(done) {
env.it('a spec without custom pretty-printer', function() {
env.expect(42).toBeUndefined();
});
env.describe('with custom pretty-printer', function() {
env.beforeEach(function() {
env.addCustomObjectFormatter(function(obj) { return 'custom(' + obj + ')'; });
});
env.it('a spec', function() {
env.expect(42).toBeUndefined();
});
});
var specResults = [];
var specDone = function(result) {
specResults.push(result);
};
var expectations = function() {
expect(specResults[0].failedExpectations[0].message).toEqual("Expected 42 to be undefined.");
expect(specResults[1].failedExpectations[0].message).toEqual("Expected custom(42) to be undefined.");
done();
};
env.addReporter({ specDone:specDone, jasmineDone: expectations});
env.execute();
});
it("throws an exception if you try to add a custom object formatter outside a runable", function() {
expect(function() {
env.addCustomObjectFormatter(function() {});
}).toThrowError('Custom object formatters must be added in a before function or a spec')
});
});

View File

@@ -3,7 +3,11 @@ describe('Custom Spy Strategies (Integration)', function() {
beforeEach(function() {
env = new jasmineUnderTest.Env();
env.randomizeTests(false);
env.configure({random: false});
});
afterEach(function() {
env.cleanup_();
});
it('allows adding more strategies local to a suite', function(done) {

View File

@@ -0,0 +1,72 @@
describe('Default Spy Strategy (Integration)', function() {
var env;
beforeEach(function() {
env = new jasmineUnderTest.Env();
env.configure({random: false});
});
afterEach(function() {
env.cleanup_();
});
it('allows defining a default spy strategy', function(done) {
env.describe('suite with default strategy', function() {
env.beforeEach(function() {
env.setDefaultSpyStrategy(function (and) {
and.returnValue(42);
});
});
env.it('spec in suite', function() {
var spy = env.createSpy('something');
expect(spy()).toBe(42);
});
});
env.it('spec not in suite', function() {
var spy = env.createSpy('something');
expect(spy()).toBeUndefined();
});
function jasmineDone(result) {
expect(result.overallStatus).toEqual('passed');
done();
}
env.addReporter({ jasmineDone: jasmineDone });
env.execute();
});
it('uses the default spy strategy defined when the spy is created', function (done) {
env.it('spec', function() {
var a = env.createSpy('a');
env.setDefaultSpyStrategy(function (and) { and.returnValue(42); });
var b = env.createSpy('b');
env.setDefaultSpyStrategy(function (and) { and.stub(); });
var c = env.createSpy('c');
env.setDefaultSpyStrategy();
var d = env.createSpy('d');
expect(a()).toBeUndefined();
expect(b()).toBe(42);
expect(c()).toBeUndefined();
expect(d()).toBeUndefined();
// Check our assumptions about which spies are "configured" (this matters because
// spies that use withArgs() behave differently if they are not configured).
expect(a.and.isConfigured()).toBe(false);
expect(b.and.isConfigured()).toBe(true);
expect(c.and.isConfigured()).toBe(true);
expect(d.and.isConfigured()).toBe(false);
});
function jasmineDone(result) {
expect(result.overallStatus).toEqual('passed');
done();
}
env.addReporter({ jasmineDone: jasmineDone });
env.execute();
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,698 @@
describe('Matchers (Integration)', function() {
var env;
beforeEach(function() {
env = new jasmineUnderTest.Env();
});
afterEach(function() {
env.cleanup_();
});
function verifyPasses(expectations) {
it('passes', function(done) {
env.it('a spec', function() {
expectations(env);
});
var specExpectations = function(result) {
expect(result.status).toEqual('passed');
expect(result.passedExpectations.length)
.withContext('Number of passed expectations')
.toEqual(1);
expect(result.failedExpectations.length)
.withContext('Number of failed expectations')
.toEqual(0);
expect(result.failedExpectations[0] && result.failedExpectations[0].message)
.withContext('Failure message')
.toBeUndefined();
};
env.addReporter({ specDone: specExpectations, jasmineDone: done });
env.execute();
});
}
function verifyFails(expectations) {
it('fails', function(done) {
env.it('a spec', function() {
expectations(env);
});
var specExpectations = function(result) {
expect(result.status).toEqual('failed');
expect(result.failedExpectations.length)
.withContext('Number of failed expectations')
.toEqual(1);
expect(result.failedExpectations[0].message)
.withContext('Failed with a thrown error rather than a matcher failure')
.not.toMatch(/^Error: /);
expect(result.failedExpectations[0].message)
.withContext('Failed with a thrown type error rather than a matcher failure')
.not.toMatch(/^TypeError: /);
expect(result.failedExpectations[0].matcherName).withContext('Matcher name')
.not.toEqual('');
};
env.addReporter({ specDone: specExpectations, jasmineDone: done });
env.execute();
});
}
function verifyFailsWithCustomObjectFormatters(config) {
it('uses custom object formatters', function(done) {
env.it('a spec', function () {
env.addCustomObjectFormatter(config.formatter);
config.expectations(env);
});
var specExpectations = function (result) {
expect(result.status).toEqual('failed');
expect(result.failedExpectations.length)
.withContext('Number of failed expectations')
.toEqual(1);
expect(result.failedExpectations[0].message)
.toEqual(config.expectedMessage);
};
env.addReporter({specDone: specExpectations, jasmineDone: done});
env.execute();
});
}
function verifyPassesAsync(expectations) {
it('passes', function(done) {
jasmine.getEnv().requirePromises();
env.it('a spec', function() {
return expectations(env);
});
var specExpectations = function(result) {
expect(result.status).toEqual('passed');
expect(result.passedExpectations.length)
.withContext('Number of passed expectations')
.toEqual(1);
expect(result.failedExpectations.length)
.withContext('Number of failed expectations')
.toEqual(0);
expect(result.failedExpectations[0] && result.failedExpectations[0].message)
.withContext('Failure message')
.toBeUndefined();
};
env.addReporter({ specDone: specExpectations, jasmineDone: done });
env.execute();
});
}
function verifyFailsAsync(expectations) {
it('fails', function(done) {
jasmine.getEnv().requirePromises();
env.it('a spec', function() {
return expectations(env);
});
var specExpectations = function(result) {
expect(result.status).toEqual('failed');
expect(result.failedExpectations.length)
.withContext('Number of failed expectations')
.toEqual(1);
expect(result.failedExpectations[0].message)
.withContext('Failed with a thrown error rather than a matcher failure')
.not.toMatch(/^Error: /);
expect(result.failedExpectations[0].matcherName).withContext('Matcher name')
.not.toEqual('');
};
env.addReporter({ specDone: specExpectations, jasmineDone: done });
env.execute();
});
}
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);
});
var specExpectations = function (result) {
expect(result.status).toEqual('failed');
expect(result.failedExpectations.length)
.withContext('Number of failed expectations')
.toEqual(1);
expect(result.failedExpectations[0].message)
.toEqual(config.expectedMessage);
};
env.addReporter({specDone: specExpectations, jasmineDone: done});
env.execute();
});
}
describe('nothing', function() {
verifyPasses(function(env) {
env.expect().nothing();
});
});
describe('toBe', function() {
verifyPasses(function(env) {
env.expect(1).toBe(1);
});
verifyFails(function(env) {
env.expect(2).toBe(1);
});
});
describe('toBeCloseTo', function() {
verifyPasses(function(env) {
env.expect(1.001).toBeCloseTo(1, 2);
});
verifyFails(function(env) {
env.expect(1.1).toBeCloseTo(1, 2);
});
});
describe('toBeDefined', function() {
verifyPasses(function(env) {
env.expect({}).toBeDefined();
});
verifyFails(function(env) {
env.expect(undefined).toBeDefined();
});
});
describe('toBeFalse', function() {
verifyPasses(function(env) {
env.expect(false).toBeFalse();
});
verifyFails(function(env) {
env.expect(true).toBeFalse();
});
});
describe('toBeFalsy', function() {
verifyPasses(function(env) {
env.expect(false).toBeFalsy();
});
verifyFails(function(env) {
env.expect(true).toBeFalsy();
});
});
describe('toBeGreaterThan', function() {
verifyPasses(function(env) {
env.expect(2).toBeGreaterThan(1);
});
verifyFails(function(env) {
env.expect(1).toBeGreaterThan(2);
});
});
describe('toBeGreaterThanOrEqual', function() {
verifyPasses(function(env) {
env.expect(2).toBeGreaterThanOrEqual(1);
});
verifyFails(function(env) {
env.expect(1).toBeGreaterThanOrEqual(2);
});
});
describe('toBeInstanceOf', function() {
function Ctor() {}
verifyPasses(function(env) {
env.expect(new Ctor()).toBeInstanceOf(Ctor);
});
verifyFails(function(env) {
env.expect({}).toBeInstanceOf(Ctor);
});
});
describe('toBeLessThan', function() {
verifyPasses(function(env) {
env.expect(1).toBeLessThan(2);
});
verifyFails(function(env) {
env.expect(2).toBeLessThan(1);
});
});
describe('toBeLessThanOrEqual', function() {
verifyPasses(function(env) {
env.expect(1).toBeLessThanOrEqual(2);
});
verifyFails(function(env) {
env.expect(2).toBeLessThanOrEqual(1);
});
});
describe('toBeNaN', function() {
verifyPasses(function(env) {
env.expect(NaN).toBeNaN();
});
verifyFails(function(env) {
env.expect(2).toBeNaN();
});
verifyFailsWithCustomObjectFormatters({
formatter: function(val) {
return '|' + val + '|';
},
expectations: function(env) {
env.expect(1).toBeNaN();
},
expectedMessage: 'Expected |1| to be NaN.'
});
});
describe('toBeNegativeInfinity', function() {
verifyPasses(function(env) {
env.expect(Number.NEGATIVE_INFINITY).toBeNegativeInfinity();
});
verifyFails(function(env) {
env.expect(2).toBeNegativeInfinity();
});
verifyFailsWithCustomObjectFormatters({
formatter: function(val) {
return '|' + val + '|';
},
expectations: function(env) {
env.expect(1).toBeNegativeInfinity();
},
expectedMessage: 'Expected |1| to be -Infinity.'
});
});
describe('toBeNull', function() {
verifyPasses(function(env) {
env.expect(null).toBeNull();
});
verifyFails(function(env) {
env.expect(2).toBeNull();
});
});
describe('toBePositiveInfinity', function() {
verifyPasses(function(env) {
env.expect(Number.POSITIVE_INFINITY).toBePositiveInfinity();
});
verifyFails(function(env) {
env.expect(2).toBePositiveInfinity();
});
verifyFailsWithCustomObjectFormatters({
formatter: function(val) {
return '|' + val + '|';
},
expectations: function(env) {
env.expect(1).toBePositiveInfinity();
},
expectedMessage: 'Expected |1| to be Infinity.'
})
});
describe('toBeResolved', function() {
verifyPassesAsync(function(env) {
return env.expectAsync(Promise.resolve()).toBeResolved(); // eslint-disable-line compat/compat
});
verifyFailsAsync(function(env) {
return env.expectAsync(Promise.reject()).toBeResolved(); // eslint-disable-line compat/compat
});
});
describe('toBeResolvedTo', function() {
verifyPassesAsync(function(env) {
env.addCustomEqualityTester(function(a, b) {
return a.toString() === b.toString();
});
return env.expectAsync(Promise.resolve('5')).toBeResolvedTo(5); // eslint-disable-line compat/compat
});
verifyFailsAsync(function(env) {
return env.expectAsync(Promise.resolve('foo')).toBeResolvedTo('bar'); // eslint-disable-line compat/compat
});
verifyFailsWithCustomObjectFormattersAsync({
formatter: function(val) {
return '|' + val + '|';
},
expectations: function(env) {
return env.expectAsync(Promise.resolve('x')).toBeResolvedTo('y'); // eslint-disable-line compat/compat
},
expectedMessage: 'Expected a promise to be resolved to |y| ' +
'but it was resolved to |x|.'
});
});
describe('toBeRejected', function() {
verifyPassesAsync(function(env) {
return env.expectAsync(Promise.reject('nope')).toBeRejected(); // eslint-disable-line compat/compat
});
verifyFailsAsync(function(env) {
return env.expectAsync(Promise.resolve()).toBeRejected(); // eslint-disable-line compat/compat
});
});
describe('toBeRejectedWith', function() {
verifyPassesAsync(function(env) {
env.addCustomEqualityTester(function(a, b) {
return a.toString() === b.toString();
});
return env.expectAsync(Promise.reject('5')).toBeRejectedWith(5); // eslint-disable-line compat/compat
});
verifyFailsAsync(function(env) {
return env.expectAsync(Promise.resolve()).toBeRejectedWith('nope'); // eslint-disable-line compat/compat
});
verifyFailsWithCustomObjectFormattersAsync({
formatter: function(val) {
return '|' + val + '|';
},
expectations: function(env) {
return env.expectAsync(Promise.reject('x')).toBeRejectedWith('y'); // eslint-disable-line compat/compat
},
expectedMessage: 'Expected a promise to be rejected with |y| ' +
'but it was rejected with |x|.'
});
});
describe('toBeRejectedWithError', function() {
verifyPassesAsync(function(env) {
return env.expectAsync(Promise.reject(new Error())).toBeRejectedWithError(Error); // eslint-disable-line compat/compat
});
verifyFailsAsync(function(env) {
return env.expectAsync(Promise.resolve()).toBeRejectedWithError(Error); // eslint-disable-line compat/compat
});
verifyFailsWithCustomObjectFormattersAsync({
formatter: function(val) {
return '|' + val + '|';
},
expectations: function(env) {
return env.expectAsync(Promise.reject('foo')).toBeRejectedWithError('foo'); // eslint-disable-line compat/compat
},
expectedMessage: 'Expected a promise to be rejected with Error: |foo| ' +
'but it was rejected with |foo|.'
});
});
describe('toBeTrue', function() {
verifyPasses(function(env) {
env.expect(true).toBeTrue();
});
verifyFails(function(env) {
env.expect(false).toBeTrue();
});
});
describe('toBeTruthy', function() {
verifyPasses(function(env) {
env.expect(true).toBeTruthy();
});
verifyFails(function(env) {
env.expect(false).toBeTruthy();
});
});
describe('toBeUndefined', function() {
verifyPasses(function(env) {
env.expect(undefined).toBeUndefined();
});
verifyFails(function(env) {
env.expect(1).toBeUndefined();
});
});
describe('toContain', function() {
verifyPasses(function(env) {
env.addCustomEqualityTester(function(a, b) {
return a.toString() === b.toString();
});
env.expect(['1', '2', '3']).toContain(2);
});
verifyFails(function(env) {
env.expect('bar').toContain('oo');
});
});
describe('toEqual', function() {
verifyPasses(function(env) {
env.addCustomEqualityTester(function(a, b) {
return a.toString() === b.toString();
});
env.expect(5).toEqual('5');
});
verifyFails(function(env) {
env.expect('a').toEqual('b');
});
verifyFailsWithCustomObjectFormatters({
formatter: function(val) {
if (val === 5) {
return 'five';
} else if (val === 4) {
return 'four';
}
},
expectations: function(env) {
env.expect([{foo: 4}]).toEqual([{foo: 5}]);
},
expectedMessage: 'Expected $[0].foo = four to equal five.'
});
});
describe('toHaveSize', function() {
verifyPasses(function(env) {
env.expect(['a','b']).toHaveSize(2);
});
verifyFails(function(env) {
env.expect(['a','b']).toHaveSize(1);
});
});
describe('toHaveBeenCalled', function() {
verifyPasses(function(env) {
var spy = env.createSpy('spy');
spy();
env.expect(spy).toHaveBeenCalled();
});
verifyFails(function(env) {
var spy = env.createSpy('spy');
env.expect(spy).toHaveBeenCalled();
});
});
describe('toHaveBeenCalledBefore', function() {
verifyPasses(function(env) {
var a = env.createSpy('a'), b = env.createSpy('b');
a();
b();
env.expect(a).toHaveBeenCalledBefore(b);
});
verifyFails(function(env) {
var a = env.createSpy('a'), b = env.createSpy('b');
b();
a();
env.expect(a).toHaveBeenCalledBefore(b);
});
});
describe('toHaveBeenCalledTimes', function() {
verifyPasses(function(env) {
var spy = env.createSpy('spy');
spy();
env.expect(spy).toHaveBeenCalledTimes(1);
});
verifyFails(function(env) {
var spy = env.createSpy('spy');
env.expect(spy).toHaveBeenCalledTimes(1);
});
});
describe('toHaveBeenCalledWith', function() {
verifyPasses(function(env) {
var spy = env.createSpy();
spy('5');
env.addCustomEqualityTester(function(a, b) {
return a.toString() === b.toString();
});
env.expect(spy).toHaveBeenCalledWith(5);
});
verifyFails(function(env) {
var spy = env.createSpy();
env.expect(spy).toHaveBeenCalledWith('foo');
});
verifyFailsWithCustomObjectFormatters({
formatter: function(val) {
return '|' + val + '|';
},
expectations: function(env) {
var spy = env.createSpy('foo');
env.expect(spy).toHaveBeenCalledWith('x');
},
expectedMessage: 'Expected spy foo to have been called with:\n' +
' |x|\n' +
'but it was never called.'
});
});
describe('toHaveBeenCalledOnceWith', function() {
verifyPasses(function(env) {
var spy = env.createSpy();
spy('5', 3);
env.addCustomEqualityTester(function(a, b) {
return a.toString() === b.toString();
});
env.expect(spy).toHaveBeenCalledOnceWith(5, 3);
});
verifyFails(function(env) {
var spy = env.createSpy();
env.expect(spy).toHaveBeenCalledOnceWith(5, 3);
});
});
describe('toHaveClass', function() {
beforeEach(function() {
this.domHelpers = jasmine.getEnv().domHelpers();
});
verifyPasses(function(env) {
var domHelpers = jasmine.getEnv().domHelpers();
var el = domHelpers.createElementWithClassName('foo');
env.expect(el).toHaveClass('foo');
});
verifyFails(function(env) {
var domHelpers = jasmine.getEnv().domHelpers();
var el = domHelpers.createElementWithClassName('foo');
env.expect(el).toHaveClass('bar');
});
});
describe('toMatch', function() {
verifyPasses(function(env) {
env.expect('foo').toMatch(/oo$/);
});
verifyFails(function(env) {
env.expect('bar').toMatch(/oo$/);
});
});
describe('toThrow', function() {
verifyPasses(function(env) {
env.addCustomEqualityTester(function(a, b) {
return a.toString() === b.toString();
});
env.expect(function() { throw '5'; }).toThrow(5);
});
verifyFails(function(env) {
env.expect(function() {}).toThrow();
});
verifyFailsWithCustomObjectFormatters({
formatter: function(val) {
return '|' + val + '|';
},
expectations: function(env) {
var spy = env.createSpy('foo');
env.expect(function() {
throw 'x'
}).not.toThrow();
},
expectedMessage: 'Expected function not to throw, but it threw |x|.'
});
});
describe('toThrowError', function() {
verifyPasses(function(env) {
env.expect(function() { throw new Error(); }).toThrowError();
});
verifyFails(function(env) {
env.expect(function() { }).toThrowError();
});
verifyFailsWithCustomObjectFormatters({
formatter: function(val) {
return '|' + val + '|';
},
expectations: function(env) {
var spy = env.createSpy('foo');
env.expect(function() {
throw 'x'
}).toThrowError();
},
expectedMessage: 'Expected function to throw an Error, but it threw |x|.'
});
});
describe('toThrowMatching', function() {
function throws() {
throw new Error('nope');
}
verifyPasses(function(env) {
env.expect(throws).toThrowMatching(function() { return true; });
});
verifyFails(function(env) {
env.expect(throws).toThrowMatching(function() { return false; });
});
verifyFailsWithCustomObjectFormatters({
formatter: function(val) {
return '|' + val + '|';
},
expectations: function(env) {
var spy = env.createSpy('foo');
env.expect(function() {
throw new Error('nope')
}).toThrowMatching(function() {
return false;
});
},
expectedMessage: 'Expected function to throw an exception matching ' +
'a predicate, but it threw Error with message |nope|.'
});
});
});

View File

@@ -4,7 +4,11 @@ describe("spec running", function () {
beforeEach(function() {
jasmine.getEnv().registerIntegrationMatchers();
env = new jasmineUnderTest.Env();
env.randomizeTests(false);
env.configure({random: false});
});
afterEach(function() {
env.cleanup_();
});
it('should assign spec ids sequentially', function() {
@@ -740,8 +744,7 @@ describe("spec running", function () {
it("should run the tests in a consistent order when a seed is supplied", function(done) {
var actions = [];
env.seed('123456');
env.randomizeTests(true);
env.configure({random: true, seed: '123456'});
env.beforeEach(function () {
actions.push('topSuite beforeEach');
@@ -865,7 +868,7 @@ describe("spec running", function () {
});
});
env.throwOnExpectationFailure(true);
env.configure({oneFailurePerSpec: true});
var assertions = function() {
expect(actions).toEqual([
@@ -900,7 +903,7 @@ describe("spec running", function () {
});
});
env.throwOnExpectationFailure(true);
env.configure({oneFailurePerSpec: true});
var assertions = function() {
expect(actions).toEqual([
@@ -932,6 +935,89 @@ describe("spec running", function () {
});
});
env.configure({oneFailurePerSpec: true});
var assertions = function() {
expect(actions).toEqual([
'beforeEach',
'afterEach'
]);
done();
};
env.addReporter({jasmineDone: assertions});
env.execute();
});
it("skips to cleanup functions after an error with deprecations", function(done) {
var actions = [];
spyOn(env, 'deprecated');
env.describe('Something', function() {
env.beforeEach(function() {
actions.push('outer beforeEach');
throw new Error("error");
});
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');
});
});
});
env.throwOnExpectationFailure(true);
var assertions = function() {
expect(actions).toEqual([
'outer beforeEach',
'inner afterEach',
'outer afterEach'
]);
expect(env.deprecated).toHaveBeenCalled();
done();
};
env.addReporter({jasmineDone: assertions});
env.execute();
});
it("skips to cleanup functions after done.fail is called with deprecations", function(done) {
var actions = [];
spyOn(env, 'deprecated');
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.throwOnExpectationFailure(true);
var assertions = function() {
@@ -939,6 +1025,42 @@ describe("spec running", function () {
'beforeEach',
'afterEach'
]);
expect(env.deprecated).toHaveBeenCalled();
done();
};
env.addReporter({jasmineDone: assertions});
env.execute();
});
it("skips to cleanup functions when an async function times out with deprecations", function(done) {
var actions = [];
spyOn(env, 'deprecated');
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.throwOnExpectationFailure(true);
var assertions = function() {
expect(actions).toEqual([
'beforeEach',
'afterEach'
]);
expect(env.deprecated).toHaveBeenCalled();
done();
};
@@ -965,8 +1087,7 @@ describe("spec running", function () {
});
});
env.randomizeTests(false);
env.stopOnSpecFailure(true);
env.configure({random: false, failFast: true});
var assertions = function() {
expect(actions).toEqual(['fails']);
@@ -976,5 +1097,36 @@ describe("spec running", function () {
env.addReporter({ jasmineDone: assertions });
env.execute();
});
it("does not run further specs when one fails when configured with deprecated option", function(done) {
var actions = [];
spyOn(env, 'deprecated');
env.describe('wrapper', function() {
env.it('fails', function() {
actions.push('fails');
env.expect(1).toBe(2);
});
});
env.describe('holder', function() {
env.it('does not run', function() {
actions.push('does not run');
});
});
env.configure({random: false});
env.stopOnSpecFailure(true);
var assertions = function() {
expect(actions).toEqual(['fails']);
expect(env.deprecated).toHaveBeenCalled();
done();
};
env.addReporter({ jasmineDone: assertions });
env.execute();
});
});
});

View File

@@ -1,47 +1,182 @@
describe("DiffBuilder", function() {
it("records the actual and expected objects", function() {
describe("DiffBuilder", function () {
it("records the actual and expected objects", function () {
var diffBuilder = jasmineUnderTest.DiffBuilder();
diffBuilder.record({x: 'actual'}, {x: 'expected'});
diffBuilder.setRoots({x: 'actual'}, {x: 'expected'});
diffBuilder.recordMismatch();
expect(diffBuilder.getMessage()).toEqual("Expected Object({ x: 'actual' }) to equal Object({ x: 'expected' }).");
});
it("prints the path at which the difference was found", function() {
it("prints the path at which the difference was found", function () {
var diffBuilder = jasmineUnderTest.DiffBuilder();
diffBuilder.setRoots({foo: {x: 'actual'}}, {foo: {x: 'expected'}});
diffBuilder.withPath('foo', function() {
diffBuilder.record({x: 'actual'}, {x: 'expected'});
diffBuilder.withPath('foo', function () {
diffBuilder.recordMismatch();
});
expect(diffBuilder.getMessage()).toEqual("Expected $.foo = Object({ x: 'actual' }) to equal Object({ x: 'expected' }).");
});
it("prints multiple messages, separated by newlines", function() {
it("prints multiple messages, separated by newlines", function () {
var diffBuilder = jasmineUnderTest.DiffBuilder();
diffBuilder.setRoots({foo: 1, bar: 3}, {foo: 2, bar: 4});
diffBuilder.withPath('foo', function() {
diffBuilder.record(1, 2);
diffBuilder.withPath('foo', function () {
diffBuilder.recordMismatch();
});
diffBuilder.withPath('bar', function () {
diffBuilder.recordMismatch();
});
var message =
"Expected $.foo = 1 to equal 2.\n" +
"Expected 3 to equal 4.";
"Expected $.bar = 3 to equal 4.";
diffBuilder.record(3, 4);
expect(diffBuilder.getMessage()).toEqual(message);
});
it("allows customization of the message", function() {
it("allows customization of the message", function () {
var diffBuilder = jasmineUnderTest.DiffBuilder();
diffBuilder.setRoots({x: 'bar'}, {x: 'foo'});
function darthVaderFormatter(actual, expected, path) {
return "I find your lack of " + expected + " disturbing. (was " + actual + ", at " + path + ")"
}
diffBuilder.withPath('x', function() {
diffBuilder.record('bar', 'foo', darthVaderFormatter);
diffBuilder.withPath('x', function () {
diffBuilder.recordMismatch(darthVaderFormatter);
});
expect(diffBuilder.getMessage()).toEqual("I find your lack of foo disturbing. (was bar, at $.x)");
});
it("uses the injected pretty-printer", function () {
var prettyPrinter = function (val) {
return '|' + val + '|';
},
diffBuilder = jasmineUnderTest.DiffBuilder({prettyPrinter: prettyPrinter});
prettyPrinter.customFormat_ = function () {
};
diffBuilder.setRoots({foo: 'actual'}, {foo: 'expected'});
diffBuilder.withPath('foo', function () {
diffBuilder.recordMismatch();
});
expect(diffBuilder.getMessage()).toEqual("Expected $.foo = |actual| to equal |expected|.");
});
it("passes the injected pretty-printer to the diff formatter", function () {
var diffFormatter = jasmine.createSpy('diffFormatter'),
prettyPrinter = function () {
},
diffBuilder = jasmineUnderTest.DiffBuilder({prettyPrinter: prettyPrinter});
prettyPrinter.customFormat_ = function () {
};
diffBuilder.setRoots({x: 'bar'}, {x: 'foo'});
diffBuilder.withPath('x', function () {
diffBuilder.recordMismatch(diffFormatter);
});
diffBuilder.getMessage();
expect(diffFormatter).toHaveBeenCalledWith('bar', 'foo', jasmine.anything(), prettyPrinter);
});
it("uses custom object formatters on leaf nodes", function() {
var formatter = function(x) {
if (typeof x === 'number') {
return '[number:' + x + ']';
}
};
prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]);
var diffBuilder = new jasmineUnderTest.DiffBuilder({prettyPrinter: prettyPrinter});
diffBuilder.setRoots(5, 4);
diffBuilder.recordMismatch();
expect(diffBuilder.getMessage()).toEqual('Expected [number:5] to equal [number:4].');
});
it("uses custom object formatters on non leaf nodes", function () {
var formatter = function (x) {
if (x.hasOwnProperty('a')) {
return '[thing with a=' + x.a + ', b=' + JSON.stringify(x.b) + ']';
}
};
prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]);
var diffBuilder = new jasmineUnderTest.DiffBuilder({prettyPrinter: prettyPrinter});
var expectedMsg = 'Expected $[0].foo = [thing with a=1, b={"x":42}] to equal [thing with a=1, b={"x":43}].\n' +
"Expected $[0].bar = 'yes' to equal 'no'.";
diffBuilder.setRoots(
[{foo: {a: 1, b: {x: 42}}, bar: 'yes'}],
[{foo: {a: 1, b: {x: 43}}, bar: 'no'}]
);
diffBuilder.withPath(0, function () {
diffBuilder.withPath('foo', function () {
diffBuilder.withPath('b', function () {
diffBuilder.withPath('x', function () {
diffBuilder.recordMismatch();
});
});
});
diffBuilder.withPath('bar', function () {
diffBuilder.recordMismatch();
});
});
expect(diffBuilder.getMessage()).toEqual(expectedMsg);
});
it('builds diffs involving asymmetric equality testers that implement valuesForDiff_ at the root', function() {
var prettyPrinter = jasmineUnderTest.makePrettyPrinter([]),
diffBuilder = new jasmineUnderTest.DiffBuilder({prettyPrinter: prettyPrinter}),
expectedMsg = 'Expected $.foo = 1 to equal 2.\n' +
"Expected $.baz = undefined to equal 3.";
diffBuilder.setRoots(
{foo: 1, bar: 2},
jasmine.objectContaining({foo: 2, baz: 3})
);
diffBuilder.withPath('foo', function() {
diffBuilder.recordMismatch();
});
diffBuilder.withPath('baz', function() {
diffBuilder.recordMismatch();
});
expect(diffBuilder.getMessage()).toEqual(expectedMsg);
});
it('builds diffs involving asymmetric equality testers that implement valuesForDiff_ below the root', function() {
var prettyPrinter = jasmineUnderTest.makePrettyPrinter([]),
diffBuilder = new jasmineUnderTest.DiffBuilder({prettyPrinter: prettyPrinter}),
expectedMsg = 'Expected $.x.foo = 1 to equal 2.\n' +
"Expected $.x.baz = undefined to equal 3.";
diffBuilder.setRoots(
{x: {foo: 1, bar: 2}},
{x: jasmine.objectContaining({foo: 2, baz: 3})}
);
diffBuilder.withPath('x', function() {
diffBuilder.withPath('foo', function () {
diffBuilder.recordMismatch();
});
diffBuilder.withPath('baz', function () {
diffBuilder.recordMismatch();
});
});
expect(diffBuilder.getMessage()).toEqual(expectedMsg);
});
});

View File

@@ -0,0 +1,136 @@
describe('MismatchTree', function () {
describe('#add', function () {
describe('When the path is empty', function () {
it('flags the root node as mismatched', function () {
var tree = new jasmineUnderTest.MismatchTree();
tree.add(new jasmineUnderTest.ObjectPath([]));
expect(tree.isMismatch).toBe(true);
});
});
describe('When the path is not empty', function () {
it('flags the node as mismatched', function () {
var tree = new jasmineUnderTest.MismatchTree();
tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']));
expect(tree.child('a').child('b').isMismatch).toBe(true);
});
it('does not flag ancestors as mismatched', function () {
var tree = new jasmineUnderTest.MismatchTree();
tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']));
expect(tree.isMismatch).toBe(false);
expect(tree.child('a').isMismatch).toBe(false);
});
});
it('stores the formatter on only the target node', function () {
var tree = new jasmineUnderTest.MismatchTree();
tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']), formatter);
expect(tree.formatter).toBeFalsy();
expect(tree.child('a').formatter).toBeFalsy();
expect(tree.child('a').child('b').formatter).toBe(formatter);
});
it('stores the path to the node', function () {
var tree = new jasmineUnderTest.MismatchTree();
tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']), formatter);
expect(tree.child('a').child('b').path.components).toEqual(['a', 'b']);
});
});
describe('#traverse', function () {
it('calls the callback for all nodes that are or contain mismatches', function () {
var tree = new jasmineUnderTest.MismatchTree();
tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']), formatter);
tree.add(new jasmineUnderTest.ObjectPath(['c']));
var visit = jasmine.createSpy('visit').and.returnValue(true);
tree.traverse(visit);
expect(visit).toHaveBeenCalledWith(
new jasmineUnderTest.ObjectPath([]), false, undefined
);
expect(visit).toHaveBeenCalledWith(
new jasmineUnderTest.ObjectPath(['a']), false, undefined
);
expect(visit).toHaveBeenCalledWith(
new jasmineUnderTest.ObjectPath(['a', 'b']), true, formatter
);
expect(visit).toHaveBeenCalledWith(
new jasmineUnderTest.ObjectPath(['c']), true, undefined
);
});
it('does not call the callback if there are no mismatches', function () {
var tree = new jasmineUnderTest.MismatchTree();
var visit = jasmine.createSpy('visit');
tree.traverse(visit);
expect(visit).not.toHaveBeenCalled();
});
it('visits parents before children', function () {
var tree = new jasmineUnderTest.MismatchTree();
tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']));
var visited = [];
tree.traverse(function (path) {
visited.push(path);
return true;
});
expect(visited).toEqual([
new jasmineUnderTest.ObjectPath([]),
new jasmineUnderTest.ObjectPath(['a']),
new jasmineUnderTest.ObjectPath(['a', 'b'])
]);
});
it('visits children in the order they were recorded', function() {
var tree = new jasmineUnderTest.MismatchTree();
tree.add(new jasmineUnderTest.ObjectPath(['length']));
tree.add(new jasmineUnderTest.ObjectPath([1]));
var visited = [];
tree.traverse(function (path) {
visited.push(path);
return true;
});
expect(visited).toEqual([
new jasmineUnderTest.ObjectPath([]),
new jasmineUnderTest.ObjectPath(['length']),
new jasmineUnderTest.ObjectPath([1])
]);
});
it('does not visit children if the callback returns falsy', function() {
var tree = new jasmineUnderTest.MismatchTree();
tree.add(new jasmineUnderTest.ObjectPath(['a', 'b']));
var visited = [];
tree.traverse(function (path) {
visited.push(path);
return path.depth() === 0;
});
expect(visited).toEqual([
new jasmineUnderTest.ObjectPath([]),
new jasmineUnderTest.ObjectPath(['a'])
]);
});
});
function formatter() {
}
});

View File

@@ -1,13 +1,8 @@
describe('NullDiffBuilder', function() {
it('responds to withPath() by calling the passed function', function() {
describe('NullDiffBuilder', function () {
it('responds to withPath() by calling the passed function', function () {
var spy = jasmine.createSpy('callback');
jasmineUnderTest.NullDiffBuilder().withPath('does not matter', spy);
expect(spy).toHaveBeenCalled();
});
it('responds to record()', function() {
expect(function() {
jasmineUnderTest.NullDiffBuilder().record('does not matter');
}).not.toThrow();
})
});

View File

@@ -39,5 +39,5 @@ describe('ObjectPath', function() {
expect(path.toString()).toEqual('$.foo');
expect(root.toString()).toEqual('');
})
});
});

View File

@@ -0,0 +1,52 @@
/* 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() {});
return matcher.compare(actual).then(function(result) {
expect(result).toEqual(jasmine.objectContaining({pass: true}));
});
});
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();
return matcher.compare(actual).then(function(result) {
expect(result).toEqual(jasmine.objectContaining({pass: false}));
});
});
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'));
return matcher.compare(actual).then(function(result) {
expect(result).toEqual(jasmine.objectContaining({pass: false}));
});
});
it('fails if actual is not a promise', function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = jasmineUnderTest.asyncMatchers.toBePending(matchersUtil),
actual = 'not a promise';
function f() {
return matcher.compare(actual);
}
expect(f).toThrowError(
'Expected toBePending to be called on a promise.'
);
});
});

View File

@@ -0,0 +1,40 @@
/* 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');
return matcher.compare(actual).then(function(result) {
expect(result).toEqual(jasmine.objectContaining({pass: true}));
});
});
it('fails if the actual is resolved', function() {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = jasmineUnderTest.asyncMatchers.toBeRejected(matchersUtil),
actual = Promise.resolve();
return matcher.compare(actual).then(function(result) {
expect(result).toEqual(jasmine.objectContaining({pass: false}));
});
});
it('fails if actual is not a promise', function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = jasmineUnderTest.asyncMatchers.toBeRejected(matchersUtil),
actual = 'not a promise';
function f() {
return matcher.compare(actual);
}
expect(f).toThrowError(
'Expected toBeRejected to be called on a promise.'
);
});
});

View File

@@ -0,0 +1,182 @@
/* 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()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new TypeError('foo'));
return matcher.compare(actual, TypeError).then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: true,
message: 'Expected a promise not to be rejected with TypeError, but it was.'
}));
});
});
it('passes when Error type and message matches', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new TypeError('foo'));
return matcher.compare(actual, TypeError, 'foo').then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: true,
message: 'Expected a promise not to be rejected with TypeError: \'foo\', but it was.'
}));
});
});
it('passes when Error matches and is exactly Error', function() {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error());
return matcher.compare(actual, Error).then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: true,
message: 'Expected a promise not to be rejected with Error, but it was.'
}));
});
});
it('passes when Error message matches a string', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error('foo'));
return matcher.compare(actual, 'foo').then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: true,
message: 'Expected a promise not to be rejected with Error: \'foo\', but it was.'
}));
});
});
it('passes when Error message matches a RegExp', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error('foo'));
return matcher.compare(actual, /foo/).then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: true,
message: 'Expected a promise not to be rejected with Error: /foo/, but it was.'
}));
});
});
it('passes when Error message is empty', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error());
return matcher.compare(actual, '').then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: true,
message: 'Expected a promise not to be rejected with Error: \'\', but it was.'
}));
});
});
it('passes when no arguments', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error());
return matcher.compare(actual, void 0).then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: true,
message: 'Expected a promise not to be rejected with Error, but it was.'
}));
});
});
it('fails when resolved', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.resolve(new Error('foo'));
return matcher.compare(actual, 'foo').then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: false,
message: 'Expected a promise to be rejected but it was resolved.'
}));
});
});
it('fails when rejected with non Error type', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject('foo');
return matcher.compare(actual, 'foo').then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: false,
message: 'Expected a promise to be rejected with Error: \'foo\' but it was rejected with \'foo\'.'
}));
});
});
it('fails when Error type mismatches', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error('foo'));
return matcher.compare(actual, TypeError, 'foo').then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: false,
message: 'Expected a promise to be rejected with TypeError: \'foo\' but it was rejected with type Error.'
}));
});
});
it('fails when Error message mismatches', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error('foo'));
return matcher.compare(actual, 'bar').then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: false,
message: 'Expected a promise to be rejected with Error: \'bar\' but it was rejected with Error: foo.'
}));
});
});
it('fails if actual is not a promise', function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = 'not a promise';
function f() {
return matcher.compare(actual);
}
expect(f).toThrowError(
'Expected toBeRejectedWithError to be called on a promise.'
);
});
});

View File

@@ -0,0 +1,83 @@
/* 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'});
return matcher.compare(actual, {error: 'PEBCAK'}).then(function (result) {
expect(result).toEqual(jasmine.objectContaining({ pass: true }));
});
});
it('should fail if the promise resolves', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.resolve();
return matcher.compare(actual, '').then(function (result) {
expect(result).toEqual(jasmine.objectContaining({ pass: false }));
});
});
it('should fail if the promise is rejected with a different value', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.reject('A Bad Apple');
return matcher.compare(actual, 'Some Cool Thing').then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: false,
message: "Expected a promise to be rejected with 'Some Cool Thing' but it was rejected with 'A Bad Apple'.",
}));
});
});
it('should build its error correctly when negated', function () {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.reject(true);
return matcher.compare(actual, true).then(function (result) {
expect(result).toEqual(jasmine.objectContaining({
pass: true,
message: 'Expected a promise not to be rejected with true.'
}));
});
});
it('should support custom equality testers', function () {
jasmine.getEnv().requirePromises();
var customEqualityTesters = [function() { return true; }],
matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: customEqualityTesters}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.reject('actual');
return matcher.compare(actual, 'expected').then(function(result) {
expect(result).toEqual(jasmine.objectContaining({pass: true}));
});
});
it('fails if actual is not a promise', function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = 'not a promise';
function f() {
return matcher.compare(actual);
}
expect(f).toThrowError(
'Expected toBeRejectedWith to be called on a promise.'
);
});
});

View File

@@ -0,0 +1,40 @@
/* 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();
return matcher.compare(actual).then(function(result) {
expect(result).toEqual(jasmine.objectContaining({pass: true}));
});
});
it('fails if the actual is rejected', function() {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = jasmineUnderTest.asyncMatchers.toBeResolved(matchersUtil),
actual = Promise.reject('AsyncExpectationSpec rejection');
return matcher.compare(actual).then(function(result) {
expect(result).toEqual(jasmine.objectContaining({pass: false}));
});
});
it('fails if actual is not a promise', function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = jasmineUnderTest.asyncMatchers.toBeResolved(matchersUtil),
actual = 'not a promise';
function f() {
return matcher.compare(actual);
}
expect(f).toThrowError(
'Expected toBeResolved to be called on a promise.'
);
});
});

View File

@@ -0,0 +1,89 @@
/* 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});
return matcher.compare(actual, {foo: 42}).then(function(result) {
expect(result).toEqual(jasmine.objectContaining({pass: true}));
});
});
it('fails if the promise is rejected', function() {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.reject('AsyncExpectationSpec error');
return matcher.compare(actual, '').then(function(result) {
expect(result).toEqual(jasmine.objectContaining({
pass: false,
message: "Expected a promise to be resolved to '' but it was rejected.",
}));
});
});
it('fails if the promise is resolved to a different value', function() {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.resolve({foo: 17});
return matcher.compare(actual, {foo: 42}).then(function(result) {
expect(result).toEqual(jasmine.objectContaining({
pass: false,
message: 'Expected a promise to be resolved to Object({ foo: 42 }) but it was resolved to Object({ foo: 17 }).',
}));
});
});
it('builds its message correctly when negated', function() {
jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.resolve(true);
return matcher.compare(actual, true).then(function(result) {
expect(result).toEqual(jasmine.objectContaining({
pass: true,
message: 'Expected a promise not to be resolved to true.'
}));
});
});
it('supports custom equality testers', function() {
jasmine.getEnv().requirePromises();
var customEqualityTesters = [function() { return true; }],
matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: customEqualityTesters,
pp: jasmineUnderTest.makePrettyPrinter()
}),
matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.resolve('actual');
return matcher.compare(actual, 'expected').then(function(result) {
expect(result).toEqual(jasmine.objectContaining({pass: true}));
});
});
it('fails if actual is not a promise', function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = 'not a promise';
function f() {
return matcher.compare(actual);
}
expect(f).toThrowError(
'Expected toBeResolvedTo to be called on a promise.'
);
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -90,4 +90,18 @@ describe("toBeCloseTo", function() {
result = matcher.compare(1.23, 1.234);
expect(result.pass).toBe(true);
});
it("handles edge cases with rounding", function () {
var matcher = jasmineUnderTest.matchers.toBeCloseTo(),
result;
// these cases resulted in false negatives in version of V8
// included in Node.js 12 and Chrome 74 (and Edge Chromium)
result = matcher.compare(4.030904708957288, 4.0309, 5);
expect(result.pass).toBe(true);
result = matcher.compare(4.82665525779431,4.82666, 5);
expect(result.pass).toBe(true);
result = matcher.compare(-2.82665525779431, -2.82666, 5);
expect(result.pass).toBe(true);
});
});

View File

@@ -0,0 +1,25 @@
describe("toBeFalse", function() {
it("passes for false", function() {
var matcher = jasmineUnderTest.matchers.toBeFalse(),
result;
result = matcher.compare(false);
expect(result.pass).toBe(true);
});
it("fails for non-false", function() {
var matcher = jasmineUnderTest.matchers.toBeFalse(),
result;
result = matcher.compare('foo');
expect(result.pass).toBe(false);
});
it("fails for falsy", function() {
var matcher = jasmineUnderTest.matchers.toBeFalse(),
result;
result = matcher.compare(undefined);
expect(result.pass).toBe(false);
});
});

View File

@@ -0,0 +1,234 @@
describe('toBeInstanceOf', function() {
describe('when expecting Number', function() {
it('passes for literal number', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(3, Number);
expect(result).toEqual({
pass: true,
message: 'Expected instance of Number not to be an instance of Number'
});
});
it('passes for NaN', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf({
pp: jasmineUnderTest.makePrettyPrinter()
});
var result = matcher.compare(NaN, Number);
expect(result).toEqual({
pass: true,
message: 'Expected instance of NaN not to be an instance of Number'
});
});
it('passes for Infinity', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(Infinity, Number);
expect(result).toEqual({
pass: true,
message: 'Expected instance of Number not to be an instance of Number'
});
});
it('fails for a non-number', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare('foo', Number);
expect(result).toEqual({
pass: false,
message: 'Expected instance of String to be an instance of Number'
});
});
});
describe('when expecting String', function() {
it('passes for a string', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare('foo', String);
expect(result).toEqual({
pass: true,
message: 'Expected instance of String not to be an instance of String'
});
});
it('fails for a non-string', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare({}, String);
expect(result).toEqual({
pass: false,
message: 'Expected instance of Object to be an instance of String'
});
});
});
describe('when expecting Boolean', function() {
it('passes for a boolean', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(true, Boolean);
expect(result).toEqual({
pass: true,
message: 'Expected instance of Boolean not to be an instance of Boolean'
});
});
it('fails for a non-boolean', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare('false', Boolean);
expect(result).toEqual({
pass: false,
message: 'Expected instance of String to be an instance of Boolean'
});
});
});
describe('when expecting RegExp', function() {
it('passes for a literal regular expression', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(/foo/, RegExp);
expect(result).toEqual({
pass: true,
message: 'Expected instance of RegExp not to be an instance of RegExp'
});
});
});
describe('when expecting Function', function() {
it('passes for a function', function() {
var fn = function() { };
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(fn, Function);
expect(result).toEqual({
pass: true,
message: 'Expected instance of Function not to be an instance of Function'
});
});
it('passes for an async function', function() {
jasmine.getEnv().requireAsyncAwait();
var fn = eval("(async function fn() { return 'foo'; })");
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(fn, Function);
expect(result).toEqual({
pass: true,
message: 'Expected instance of AsyncFunction not to be an instance of Function'
});
});
});
describe('when expecting Object', function() {
function Animal() { }
it('passes for any object', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare({ foo: 'bar' }, Object);
expect(result).toEqual({
pass: true,
message: 'Expected instance of Object not to be an instance of Object'
});
});
it('passes for an Error object', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(new Error('example'), Object);
expect(result).toEqual({
pass: true,
message: 'Expected instance of Error not to be an instance of Object'
});
});
it('passes for a user-defined class', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(new Animal(), Object);
expect(result).toEqual({
pass: true,
message: 'Expected instance of Animal not to be an instance of Object'
});
});
it('fails for a non-object', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare('foo', Object);
expect(result).toEqual({
pass: false,
message: 'Expected instance of String to be an instance of Object'
});
});
it('passes for objects with no constructor', function() {
var object = Object.create(null);
var matcher = jasmineUnderTest.matchers.toBeInstanceOf({
pp: jasmineUnderTest.makePrettyPrinter()
});
var result = matcher.compare(object, Object);
expect(result).toEqual({
pass: true,
message: 'Expected instance of null({ }) not to be an instance of Object'
});
});
});
describe('when expecting a user-defined class', function() {
// Base class
function Animal() { }
// Subclasses, defined using syntax that is as old as possible
function Dog() {
Animal.call(this);
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
function Cat() {
Animal.call(this);
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
it('passes for instances of that class', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(new Animal(), Animal);
expect(result).toEqual({
pass: true,
message: 'Expected instance of Animal not to be an instance of Animal'
});
});
it('passes for instances of a subclass', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(new Cat(), Animal);
expect(result).toEqual({
pass: true,
message: 'Expected instance of Cat not to be an instance of Animal'
});
});
it('does not pass for sibling classes', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
var result = matcher.compare(new Dog(), Cat);
expect(result).toEqual({
pass: false,
message: 'Expected instance of Dog to be an instance of Cat'
});
});
});
it('raises an error if passed an invalid expected value', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf();
expect(function() {
matcher.compare({}, 'Error');
}).toThrowError('<toBeInstanceOf> : Expected value is not a constructor function\n' +
'Usage: expect(value).toBeInstanceOf(<ConstructorFunction>)');
});
it('raises an error if missing an expected value', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf({
pp: jasmineUnderTest.makePrettyPrinter()
});
expect(function() {
matcher.compare({}, undefined);
}).toThrowError('<toBeInstanceOf> : Expected value is not a constructor function\n' +
'Usage: expect(value).toBeInstanceOf(<ConstructorFunction>)');
});
});

View File

@@ -29,7 +29,9 @@ describe("toBeNaN", function() {
});
it("has a custom message on failure", function() {
var matcher = jasmineUnderTest.matchers.toBeNaN(),
var matcher = jasmineUnderTest.matchers.toBeNaN({
pp: jasmineUnderTest.makePrettyPrinter()
}),
result = matcher.compare(0);
expect(result.message()).toEqual("Expected 0 to be NaN.");

View File

@@ -14,10 +14,12 @@ describe("toBeNegativeInfinity", function() {
});
it("has a custom message on failure", function() {
var matcher = jasmineUnderTest.matchers.toBeNegativeInfinity(),
var matcher = jasmineUnderTest.matchers.toBeNegativeInfinity({
pp: jasmineUnderTest.makePrettyPrinter()
}),
result = matcher.compare(0);
expect(result.message()).toEqual("Expected 0 not to be -Infinity.")
expect(result.message()).toEqual("Expected 0 to be -Infinity.")
});
it("succeeds for -Infinity", function() {
@@ -25,7 +27,7 @@ describe("toBeNegativeInfinity", function() {
result = matcher.compare(Number.NEGATIVE_INFINITY);
expect(result.pass).toBe(true);
expect(result.message).toEqual("Expected actual to be -Infinity.")
expect(result.message).toEqual("Expected actual not to be -Infinity.")
});
});

View File

@@ -14,10 +14,12 @@ describe("toBePositiveInfinity", function() {
});
it("has a custom message on failure", function() {
var matcher = jasmineUnderTest.matchers.toBePositiveInfinity(),
var matcher = jasmineUnderTest.matchers.toBePositiveInfinity({
pp: jasmineUnderTest.makePrettyPrinter()
}),
result = matcher.compare(0);
expect(result.message()).toEqual("Expected 0 not to be Infinity.")
expect(result.message()).toEqual("Expected 0 to be Infinity.")
});
it("succeeds for Infinity", function() {
@@ -25,7 +27,7 @@ describe("toBePositiveInfinity", function() {
result = matcher.compare(Number.POSITIVE_INFINITY);
expect(result.pass).toBe(true);
expect(result.message).toEqual("Expected actual to be Infinity.")
expect(result.message).toEqual("Expected actual not to be Infinity.")
});
});

View File

@@ -1,17 +1,74 @@
describe("toBe", function() {
it("passes when actual === expected", function() {
var matcher = jasmineUnderTest.matchers.toBe(),
it("passes with no message when actual === expected", function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = jasmineUnderTest.matchers.toBe(matchersUtil),
result;
result = matcher.compare(1, 1);
expect(result.pass).toBe(true);
});
it("fails when actual !== expected", function() {
var matcher = jasmineUnderTest.matchers.toBe(),
it("passes with a custom message when expected is an array", function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.matchers.toBe(matchersUtil),
result,
array = [1];
result = matcher.compare(array, array);
expect(result.pass).toBe(true);
expect(result.message).toBe("Expected [ 1 ] not to be [ 1 ]. Tip: To check for deep equality, use .toEqual() instead of .toBe().")
});
it("passes with a custom message when expected is an object", function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.matchers.toBe(matchersUtil),
result,
obj = {foo: "bar"};
result = matcher.compare(obj, obj);
expect(result.pass).toBe(true);
expect(result.message).toBe("Expected Object({ foo: 'bar' }) not to be Object({ foo: 'bar' }). Tip: To check for deep equality, use .toEqual() instead of .toBe().")
});
it("fails with no message when actual !== expected", function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil(),
matcher = jasmineUnderTest.matchers.toBe(matchersUtil),
result;
result = matcher.compare(1, 2);
expect(result.pass).toBe(false);
expect(result.message).toBeUndefined();
});
it("fails with a custom message when expected is an array", function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.matchers.toBe(matchersUtil),
result;
result = matcher.compare([1], [1]);
expect(result.pass).toBe(false);
expect(result.message).toBe("Expected [ 1 ] to be [ 1 ]. Tip: To check for deep equality, use .toEqual() instead of .toBe().")
});
it("fails with a custom message when expected is an object", function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.matchers.toBe(matchersUtil),
result;
result = matcher.compare({foo: "bar"}, {foo: "bar"});
expect(result.pass).toBe(false);
expect(result.message).toBe("Expected Object({ foo: 'bar' }) to be Object({ foo: 'bar' }). Tip: To check for deep equality, use .toEqual() instead of .toBe().")
});
it("works with custom object formatters when expected is an object", function() {
var formatter = function(x) { return '<' + x.foo + '>'; },
prettyPrinter = jasmineUnderTest.makePrettyPrinter([formatter]),
matchersUtil = new jasmineUnderTest.MatchersUtil({pp: prettyPrinter}),
matcher = jasmineUnderTest.matchers.toBe(matchersUtil),
result;
result = matcher.compare({foo: "bar"}, {foo: "bar"});
expect(result.pass).toBe(false);
expect(result.message).toBe("Expected <bar> to be <bar>. Tip: To check for deep equality, use .toEqual() instead of .toBe().")
});
});

View File

@@ -0,0 +1,17 @@
describe("toBeTrue", function() {
it("passes for true", function() {
var matcher = jasmineUnderTest.matchers.toBeTrue(),
result;
result = matcher.compare(true);
expect(result.pass).toBe(true);
});
it("fails for non-true", function() {
var matcher = jasmineUnderTest.matchers.toBeTrue(),
result;
result = matcher.compare('foo');
expect(result.pass).toBe(false);
});
});

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