{"name":"chai-as-promised","version":"8.0.2","keywords":["chai","chai-plugin","browser","async","testing","assertions","promises","promises-aplus"],"author":{"url":"https://domenic.me","name":"Domenic Denicola","email":"d@domenic.me"},"license":"MIT","_id":"chai-as-promised@8.0.2","maintainers":[{"name":"domenic","email":"d@domenic.me"},{"name":"chaijs","email":"chaijs@keithcirkel.co.uk"}],"homepage":"https://github.com/chaijs/chai-as-promised#readme","bugs":{"url":"https://github.com/chaijs/chai-as-promised/issues"},"dist":{"shasum":"cd9b77afaa976383eb4cbef9463ac5230f7a1cba","tarball":"http://registry-npm.ywwl.com/chai-as-promised/download/chai-as-promised-8.0.2.tgz","fileCount":4,"integrity":"sha512-1GadL+sEJVLzDjcawPM4kjfnL+p/9vrxiEUonowKOAzvVg0PixJUdtuDzdkDeQhK3zfOE76GqGkZIQ7/Adcrqw==","signatures":[{"sig":"MEUCIQCgeOs41h1hnkVAJfts30cwnUQo095MDBiDuvrgObHKcwIgIqqO/k9zKSpl5q7+LSxZkPMZDipg5PGwoqUJFupDg1Q=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/chai-as-promised@8.0.2","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":27940,"size":8757,"noattachment":false,"key":"/chai-as-promised/-/chai-as-promised-8.0.2.tgz"},"main":"./lib/chai-as-promised.js","type":"module","exports":{".":"./lib/chai-as-promised.js"},"gitHead":"726c0e0af014bdabce9660c3a56cd9b62ef75ca4","scripts":{"lint":"eslint .","test":"c8 mocha","format":"prettier --write lib test"},"_npmUser":{"name":"chaijs","email":"chaijs@keithcirkel.co.uk"},"repository":{"url":"git+https://github.com/chaijs/chai-as-promised.git","type":"git"},"_npmVersion":"10.9.3","description":"Extends Chai with assertions about promises.","directories":{},"_nodeVersion":"22.18.0","dependencies":{"check-error":"^2.1.1"},"_hasShrinkwrap":false,"devDependencies":{"c8":"^10.0.0","chai":"^6.0.1","mocha":"^11.0.0","eslint":"^9.0.0","globals":"^16.0.0","prettier":"^3.2.5","@eslint/js":"^9.19.0"},"peerDependencies":{"chai":">= 2.1.2 < 7"},"_npmOperationalInternal":{"tmp":"tmp/chai-as-promised_8.0.2_1755883650047_0.8627387813446585","host":"s3://npm-registry-packages-npm-production"},"readme":"<a href=\"http://promisesaplus.com/\">\n    <img src=\"https://promises-aplus.github.io/promises-spec/assets/logo-small.png\"\n         align=\"right\" valign=\"top\" alt=\"Promises/A+ logo\" />\n</a>\n\n# Chai Assertions for Promises\n\n**Chai as Promised** extends [Chai](http://chaijs.com/) with a fluent language for asserting facts about [promises](http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript).\n\nInstead of manually wiring up your expectations to a promise's fulfilled and rejected handlers:\n\n```javascript\ndoSomethingAsync().then(\n    function (result) {\n        result.should.equal(\"foo\");\n        done();\n    },\n    function (err) {\n       done(err);\n    }\n);\n```\n\nyou can write code that expresses what you really mean:\n\n```javascript\nreturn doSomethingAsync().should.eventually.equal(\"foo\");\n```\n\nor if you have a case where `return` is not preferable (e.g. style considerations) or not possible (e.g. the testing framework doesn't allow returning promises to signal asynchronous test completion), then you can use the following workaround (where `done()` is supplied by the test framework):\n\n```javascript\ndoSomethingAsync().should.eventually.equal(\"foo\").notify(done);\n```\n\n*Notice*: either `return` or `notify(done)` _must_ be used with promise assertions. This can be a slight departure from the existing format of assertions being used on a project or by a team. Those other assertions are likely synchronous and thus do not require special handling.\n\n## How to Use\n\n### `should`/`expect` Interface\n\nThe most powerful extension provided by Chai as Promised is the `eventually` property. With it, you can transform any existing Chai assertion into one that acts on a promise:\n\n```javascript\n(2 + 2).should.equal(4);\n\n// becomes\nreturn Promise.resolve(2 + 2).should.eventually.equal(4);\n\n\nexpect({ foo: \"bar\" }).to.have.property(\"foo\");\n\n// becomes\nreturn expect(Promise.resolve({ foo: \"bar\" })).to.eventually.have.property(\"foo\");\n```\n\nThere are also a few promise-specific extensions (with the usual `expect` equivalents also available):\n\n```javascript\nreturn promise.should.be.fulfilled;\nreturn promise.should.eventually.deep.equal(\"foo\");\nreturn promise.should.become(\"foo\"); // same as `.eventually.deep.equal`\nreturn promise.should.be.rejected;\nreturn promise.should.be.rejectedWith(Error); // other variants of Chai's `throw` assertion work too.\n```\n\n### `assert` Interface\n\nAs with the `should`/`expect` interface, Chai as Promised provides an `eventually` extender to `chai.assert`, allowing any existing Chai assertion to be used on a promise:\n\n```javascript\nassert.equal(2 + 2, 4, \"This had better be true\");\n\n// becomes\nreturn assert.eventually.equal(Promise.resolve(2 + 2), 4, \"This had better be true, eventually\");\n```\n\nAnd there are, of course, promise-specific extensions:\n\n```javascript\nreturn assert.isFulfilled(promise, \"optional message\");\n\nreturn assert.becomes(promise, \"foo\", \"optional message\");\nreturn assert.doesNotBecome(promise, \"foo\", \"optional message\");\n\nreturn assert.isRejected(promise, Error, \"optional message\");\nreturn assert.isRejected(promise, /error message regex matcher/, \"optional message\");\nreturn assert.isRejected(promise, \"substring to search error message for\", \"optional message\");\n```\n\n### Progress Callbacks\n\nChai as Promised does not have any intrinsic support for testing promise progress callbacks. The properties you would want to test are probably much better suited to a library like [Sinon.JS](http://sinonjs.org/), perhaps in conjunction with [Sinon–Chai](https://github.com/domenic/sinon-chai):\n\n```javascript\nvar progressSpy = sinon.spy();\n\nreturn promise.then(null, null, progressSpy).then(function () {\n    progressSpy.should.have.been.calledWith(\"33%\");\n    progressSpy.should.have.been.calledWith(\"67%\");\n    progressSpy.should.have.been.calledThrice;\n});\n```\n\n### Customizing Output Promises\n\nBy default, the promises returned by Chai as Promised's assertions are regular Chai assertion objects, extended with a single `then` method derived from the input promise. To change this behavior, for instance to output a promise with more useful sugar methods such as are found in most promise libraries, you can override `chaiAsPromised.transferPromiseness`. Here's an example that transfer's Q's `finally` and `done` methods:\n\n```js\nimport {setTransferPromiseness} from 'chai-as-promised';\n\nsetTransferPromiseness(function (assertion, promise) {\n    assertion.then = promise.then.bind(promise); // this is all you get by default\n    assertion.finally = promise.finally.bind(promise);\n    assertion.done = promise.done.bind(promise);\n});\n```\n\n### Transforming Arguments to the Asserters\n\nAnother advanced customization hook Chai as Promised allows is if you want to transform the arguments to the asserters, possibly asynchronously. Here is a toy example:\n\n```js\nimport {transformAsserterArgs} from 'chai-as-promised';\n\nsetTransformAsserterArgs(function (args) {\n    return args.map(function (x) { return x + 1; });\n});\n\nPromise.resolve(2).should.eventually.equal(2); // will now fail!\nPromise.resolve(3).should.eventually.equal(2); // will now pass!\n```\n\nThe transform can even be asynchronous, returning a promise for an array instead of an array directly. An example of that might be using `Promise.all` so that an array of promises becomes a promise for an array. If you do that, then you can compare promises against other promises using the asserters:\n\n```js\n// This will normally fail, since within() only works on numbers.\nPromise.resolve(2).should.eventually.be.within(Promise.resolve(1), Promise.resolve(6));\n\nsetTransformAsserterArgs(function (args) {\n    return Promise.all(args);\n});\n\n// But now it will pass, since we transformed the array of promises for numbers into\n// (a promise for) an array of numbers\nPromise.resolve(2).should.eventually.be.within(Promise.resolve(1), Promise.resolve(6));\n```\n\n### Compatibility\n\nChai as Promised is compatible with all promises following the [Promises/A+ specification](http://promisesaplus.com/).\n\nNotably, jQuery's promises were not up to spec before jQuery 3.0, and Chai as Promised will not work with them. In particular, Chai as Promised makes extensive use of the standard [transformation behavior](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_2) of `then`, which jQuery<3.0 does not support.\n\nAngular promises have a special digest cycle for their processing, and [need extra setup code to work with Chai as Promised](http://stackoverflow.com/a/37374041/3191).\n\n### Working with Non-Promise–Friendly Test Runners\n\nSome test runners (e.g. Jasmine, QUnit, or tap/tape) do not have the ability to use the returned promise to signal asynchronous test completion. If possible, I'd recommend switching to ones that do, such as [Mocha](http://mochajs.org/#asynchronous-code), [Buster](http://docs.busterjs.org/en/latest/modules/buster-test/spec/#returning-a-promise), or [blue-tape](https://github.com/spion/blue-tape). But if that's not an option, Chai as Promised still has you covered. As long as your test framework takes a callback indicating when the asynchronous test run is over, Chai as Promised can adapt to that situation with its `notify` method, like so:\n\n```javascript\nit(\"should be fulfilled\", function (done) {\n    promise.should.be.fulfilled.and.notify(done);\n});\n\nit(\"should be rejected\", function (done) {\n    otherPromise.should.be.rejected.and.notify(done);\n});\n```\n\nIn these examples, if the conditions are not met, the test runner will receive an error of the form `\"expected promise to be fulfilled but it was rejected with [Error: error message]\"`, or `\"expected promise to be rejected but it was fulfilled.\"`\n\nThere's another form of `notify` which is useful in certain situations, like doing assertions after a promise is complete. For example:\n\n```javascript\nit(\"should change the state\", function (done) {\n    otherState.should.equal(\"before\");\n    promise.should.be.fulfilled.then(function () {\n        otherState.should.equal(\"after\");\n    }).should.notify(done);\n});\n```\n\nNotice how `.notify(done)` is hanging directly off of `.should`, instead of appearing after a promise assertion. This indicates to Chai as Promised that it should pass fulfillment or rejection directly through to the testing framework. Thus, the above code will fail with a Chai as Promised error (`\"expected promise to be fulfilled…\"`) if `promise` is rejected, but will fail with a simple Chai error (`expected \"before\" to equal \"after\"`) if `otherState` does not change.\n\n### Working with `async`/`await` and Promise-Friendly Test Runners\n\nSince any assertion that must wait on a promise returns a promise itself, if you're able to use `async`/`await` and your test runner supports returning a promise from test methods, you can await assertions in tests.  In many cases you can avoid using Chai as Promised at all by performing a synchronous assertion after an `await`, but awaiting `rejectedWith` is often more convenient than using `try`/`catch` blocks without Chai as Promised:\n\n```javascript\nit('should work well with async/await', async () => {\n  (await Promise.resolve(42)).should.equal(42)\n  await Promise.reject(new Error()).should.be.rejectedWith(Error);\n});\n```\n\n### Multiple Promise Assertions\n\nTo perform assertions on multiple promises, use `Promise.all` to combine multiple Chai as Promised assertions:\n\n```javascript\nit(\"should all be well\", function () {\n    return Promise.all([\n        promiseA.should.become(\"happy\"),\n        promiseB.should.eventually.have.property(\"fun times\"),\n        promiseC.should.be.rejectedWith(TypeError, \"only joyful types are allowed\")\n    ]);\n});\n```\n\nThis will pass any failures of the individual promise assertions up to the test framework, instead of wrapping them in an `\"expected promise to be fulfilled…\"` message as would happen if you did `return Promise.all([…]).should.be.fulfilled`. If you can't use `return`, then use `.should.notify(done)`, similar to the previous examples.\n\n## Installation and Setup\n\n### Node\n\nDo an `npm install chai-as-promised` to get up and running. Then:\n\n```javascript\nimport * as chai from 'chai';\nimport chaiAsPromised from 'chai-as-promised';\n\nchai.use(chaiAsPromised);\n\n// Then either:\nconst expect = chai.expect;\n// or:\nconst assert = chai.assert;\n// or:\nchai.should();\n// according to your preference of assertion style\n```\n\nYou can of course put this code in a common test fixture file; for an example using [Mocha](http://mochajs.org), see [the Chai as Promised tests themselves](https://github.com/domenic/chai-as-promised/tree/master/test/).\n\n**Note when using other Chai plugins:** Chai as Promised finds all currently-registered asserters and promisifies them, at the time it is installed. Thus, you should install Chai as Promised _last_, after any other Chai plugins, if you expect their asserters to be promisified.\n\n### Karma\n\nIf you're using [Karma](https://karma-runner.github.io/), check out the accompanying [karma-chai-as-promised](https://github.com/vlkosinov/karma-chai-as-promised) plugin.\n\n### Browser/Node Compatibility\n\nChai as Promised requires support for ES modules and modern JavaScript syntax.\nIf your browser doesn't support this, you will need to transpile it down using\na tool like [Babel](https://babeljs.io/).\n","publish_time":1755883650232,"_cnpm_publish_time":1755883650232,"dist-tags":{"latest":"8.0.2","next":"8.0.0-beta.1"}}