Gathering detailed insights and metrics for chai-as-promised
Gathering detailed insights and metrics for chai-as-promised
Gathering detailed insights and metrics for chai-as-promised
Gathering detailed insights and metrics for chai-as-promised
@types/chai-as-promised
TypeScript definitions for chai-as-promised
karma-chai-as-promised
Chai-as-promised plugin for karma
@fintechstudios/eslint-plugin-chai-as-promised
Prevent common problems when using chai-as-promised
chai-as-promised-also-chain
Adding .also chain in base library of chai-as-promised
npm install chai-as-promised
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,421 Stars
202 Commits
109 Forks
17 Watching
2 Branches
33 Contributors
Updated on 15 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-8%
295,859
Compared to previous day
Last week
7.4%
1,908,473
Compared to previous week
Last month
38.6%
7,159,752
Compared to previous month
Last year
4.4%
61,857,617
Compared to previous year
Chai as Promised extends Chai with a fluent language for asserting facts about promises.
Instead of manually wiring up your expectations to a promise's fulfilled and rejected handlers:
1doSomethingAsync().then( 2 function (result) { 3 result.should.equal("foo"); 4 done(); 5 }, 6 function (err) { 7 done(err); 8 } 9);
you can write code that expresses what you really mean:
1return doSomethingAsync().should.eventually.equal("foo");
or 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):
1doSomethingAsync().should.eventually.equal("foo").notify(done);
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.
should
/expect
InterfaceThe 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:
1(2 + 2).should.equal(4); 2 3// becomes 4return Promise.resolve(2 + 2).should.eventually.equal(4); 5 6 7expect({ foo: "bar" }).to.have.property("foo"); 8 9// becomes 10return expect(Promise.resolve({ foo: "bar" })).to.eventually.have.property("foo");
There are also a few promise-specific extensions (with the usual expect
equivalents also available):
1return promise.should.be.fulfilled; 2return promise.should.eventually.deep.equal("foo"); 3return promise.should.become("foo"); // same as `.eventually.deep.equal` 4return promise.should.be.rejected; 5return promise.should.be.rejectedWith(Error); // other variants of Chai's `throw` assertion work too.
assert
InterfaceAs 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:
1assert.equal(2 + 2, 4, "This had better be true"); 2 3// becomes 4return assert.eventually.equal(Promise.resolve(2 + 2), 4, "This had better be true, eventually");
And there are, of course, promise-specific extensions:
1return assert.isFulfilled(promise, "optional message"); 2 3return assert.becomes(promise, "foo", "optional message"); 4return assert.doesNotBecome(promise, "foo", "optional message"); 5 6return assert.isRejected(promise, Error, "optional message"); 7return assert.isRejected(promise, /error message regex matcher/, "optional message"); 8return assert.isRejected(promise, "substring to search error message for", "optional message");
Chai 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, perhaps in conjunction with Sinon–Chai:
1var progressSpy = sinon.spy(); 2 3return promise.then(null, null, progressSpy).then(function () { 4 progressSpy.should.have.been.calledWith("33%"); 5 progressSpy.should.have.been.calledWith("67%"); 6 progressSpy.should.have.been.calledThrice; 7});
By 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:
1import {setTransferPromiseness} from 'chai-as-promised'; 2 3setTransferPromiseness(function (assertion, promise) { 4 assertion.then = promise.then.bind(promise); // this is all you get by default 5 assertion.finally = promise.finally.bind(promise); 6 assertion.done = promise.done.bind(promise); 7});
Another 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:
1import {transformAsserterArgs} from 'chai-as-promised'; 2 3setTransformAsserterArgs(function (args) { 4 return args.map(function (x) { return x + 1; }); 5}); 6 7Promise.resolve(2).should.eventually.equal(2); // will now fail! 8Promise.resolve(3).should.eventually.equal(2); // will now pass!
The 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:
1// This will normally fail, since within() only works on numbers. 2Promise.resolve(2).should.eventually.be.within(Promise.resolve(1), Promise.resolve(6)); 3 4setTransformAsserterArgs(function (args) { 5 return Promise.all(args); 6}); 7 8// But now it will pass, since we transformed the array of promises for numbers into 9// (a promise for) an array of numbers 10Promise.resolve(2).should.eventually.be.within(Promise.resolve(1), Promise.resolve(6));
Chai as Promised is compatible with all promises following the Promises/A+ specification.
Notably, 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 of then
, which jQuery<3.0 does not support.
Angular promises have a special digest cycle for their processing, and need extra setup code to work with Chai as Promised.
Some 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, Buster, or 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:
1it("should be fulfilled", function (done) { 2 promise.should.be.fulfilled.and.notify(done); 3}); 4 5it("should be rejected", function (done) { 6 otherPromise.should.be.rejected.and.notify(done); 7});
In 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."
There's another form of notify
which is useful in certain situations, like doing assertions after a promise is complete. For example:
1it("should change the state", function (done) { 2 otherState.should.equal("before"); 3 promise.should.be.fulfilled.then(function () { 4 otherState.should.equal("after"); 5 }).should.notify(done); 6});
Notice 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.
async
/await
and Promise-Friendly Test RunnersSince 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:
1it('should work well with async/await', async () => { 2 (await Promise.resolve(42)).should.equal(42) 3 await Promise.reject(new Error()).should.be.rejectedWith(Error); 4});
To perform assertions on multiple promises, use Promise.all
to combine multiple Chai as Promised assertions:
1it("should all be well", function () { 2 return Promise.all([ 3 promiseA.should.become("happy"), 4 promiseB.should.eventually.have.property("fun times"), 5 promiseC.should.be.rejectedWith(TypeError, "only joyful types are allowed") 6 ]); 7});
This 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.
Do an npm install chai-as-promised
to get up and running. Then:
1import * as chai from 'chai'; 2import chaiAsPromised from 'chai-as-promised'; 3 4chai.use(chaiAsPromised); 5 6// Then either: 7const expect = chai.expect; 8// or: 9const assert = chai.assert; 10// or: 11chai.should(); 12// according to your preference of assertion style
You can of course put this code in a common test fixture file; for an example using Mocha, see the Chai as Promised tests themselves.
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.
If you're using Karma, check out the accompanying karma-chai-as-promised plugin.
Chai as Promised requires support for ES modules and modern JavaScript syntax. If your browser doesn't support this, you will need to transpile it down using a tool like Babel.
No vulnerabilities found.
No security vulnerabilities found.