• Stars
    star
    1,417
  • Rank 32,082 (Top 0.7 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 12 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Extends Chai with assertions about promises.
Promises/A+ logo

Chai Assertions for Promises

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:

doSomethingAsync().then(
    function (result) {
        result.should.equal("foo");
        done();
    },
    function (err) {
       done(err);
    }
);

you can write code that expresses what you really mean:

return 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):

doSomethingAsync().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.

How to Use

should/expect Interface

The 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:

(2 + 2).should.equal(4);

// becomes
return Promise.resolve(2 + 2).should.eventually.equal(4);


expect({ foo: "bar" }).to.have.property("foo");

// becomes
return 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):

return promise.should.be.fulfilled;
return promise.should.eventually.deep.equal("foo");
return promise.should.become("foo"); // same as `.eventually.deep.equal`
return promise.should.be.rejected;
return promise.should.be.rejectedWith(Error); // other variants of Chai's `throw` assertion work too.

assert Interface

As 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:

assert.equal(2 + 2, 4, "This had better be true");

// becomes
return assert.eventually.equal(Promise.resolve(2 + 2), 4, "This had better be true, eventually");

And there are, of course, promise-specific extensions:

return assert.isFulfilled(promise, "optional message");

return assert.becomes(promise, "foo", "optional message");
return assert.doesNotBecome(promise, "foo", "optional message");

return assert.isRejected(promise, Error, "optional message");
return assert.isRejected(promise, /error message regex matcher/, "optional message");
return assert.isRejected(promise, "substring to search error message for", "optional message");

Progress Callbacks

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:

var progressSpy = sinon.spy();

return promise.then(null, null, progressSpy).then(function () {
    progressSpy.should.have.been.calledWith("33%");
    progressSpy.should.have.been.calledWith("67%");
    progressSpy.should.have.been.calledThrice;
});

Customizing Output Promises

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:

chaiAsPromised.transferPromiseness = function (assertion, promise) {
    assertion.then = promise.then.bind(promise); // this is all you get by default
    assertion.finally = promise.finally.bind(promise);
    assertion.done = promise.done.bind(promise);
};

Transforming Arguments to the Asserters

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:

chaiAsPromised.transformAsserterArgs = function (args) {
    return args.map(function (x) { return x + 1; });
}

Promise.resolve(2).should.eventually.equal(2); // will now fail!
Promise.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:

// This will normally fail, since within() only works on numbers.
Promise.resolve(2).should.eventually.be.within(Promise.resolve(1), Promise.resolve(6));

chaiAsPromised.transformAsserterArgs = function (args) {
    return Promise.all(args);
};

// But now it will pass, since we transformed the array of promises for numbers into
// (a promise for) an array of numbers
Promise.resolve(2).should.eventually.be.within(Promise.resolve(1), Promise.resolve(6));

Compatibility

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.

Working with Non-Promiseโ€“Friendly Test Runners

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:

it("should be fulfilled", function (done) {
    promise.should.be.fulfilled.and.notify(done);
});

it("should be rejected", function (done) {
    otherPromise.should.be.rejected.and.notify(done);
});

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:

it("should change the state", function (done) {
    otherState.should.equal("before");
    promise.should.be.fulfilled.then(function () {
        otherState.should.equal("after");
    }).should.notify(done);
});

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.

Working with async/await and Promise-Friendly Test Runners

Since 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:

it('should work well with async/await', async () => {
  (await Promise.resolve(42)).should.equal(42)
  await Promise.reject(new Error()).should.be.rejectedWith(Error);
});

Multiple Promise Assertions

To perform assertions on multiple promises, use Promise.all to combine multiple Chai as Promised assertions:

it("should all be well", function () {
    return Promise.all([
        promiseA.should.become("happy"),
        promiseB.should.eventually.have.property("fun times"),
        promiseC.should.be.rejectedWith(TypeError, "only joyful types are allowed")
    ]);
});

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.

Installation and Setup

Node

Do an npm install chai-as-promised to get up and running. Then:

var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");

chai.use(chaiAsPromised);

// Then either:
var expect = chai.expect;
// or:
var assert = chai.assert;
// or:
chai.should();
// 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.

In the Browser

To use Chai as Promised in environments that don't support Node.js-like CommonJS modules, you'll need to use a bundling tool like browserify. See also the note below about browser compatibility.

Karma

If you're using Karma, check out the accompanying karma-chai-as-promised plugin.

Browser/Node Compatibility

Chai as Promised requires Node v4+ or a browser with equivalent support for modern JavaScript syntax. If your browser doesn't support modern JavaScript syntax, you'll need to transpile it down using a tool like Babel.

More Repositories

1

promises-unwrapping

The ES6 promises spec, as per September 2013 TC39 meeting
JavaScript
1,219
star
2

sinon-chai

Extends Chai with assertions for the Sinon.JS mocking framework.
JavaScript
1,087
star
3

svg2png

Converts SVGs to PNGs, using PhantomJS
JavaScript
573
star
4

count-to-6

An intro to some ES6 features via a set of self-guided workshops.
JavaScript
326
star
5

restify-oauth2

A simple OAuth 2 endpoint for Restify
CoffeeScript
295
star
6

opener

Opens stuff, like webpages and files and executables, cross-platform
JavaScript
293
star
7

html-as-custom-elements

HTML as Custom Elements
CSS
260
star
8

proposal-blocks

Former home of a proposal for a new syntactic construct for serializable blocks of JavaScript code
215
star
9

zones

Former home of the zones proposal for JavaScript
204
star
10

worm-scraper

Scrapes the web serial Worm and its sequel Ward into an eBook format
JavaScript
179
star
11

jadeify

A simple browserify transform for turning .jade files into template functions
JavaScript
162
star
12

mocha-as-promised

Adds โ€œthenableโ€ promise support to the Mocha test runner.
JavaScript
132
star
13

especially

Abstract operations and other functions drawn from the ECMAScript specification
JavaScript
91
star
14

dict

A lightweight but safe dictionary, for when Object won't cut it
CoffeeScript
75
star
15

infinite-list-study-group

Moved to WICG/virtual-scroller
72
star
16

understanding-node

Material for the "Understanding the Node.js Platform" class at General Assembly
JavaScript
66
star
17

promise-tests

DEPRECATED: use https://github.com/promises-aplus/promises-tests instead!
JavaScript
61
star
18

proposal-arraybuffer-transfer

Former home of the now-withdrawn ArrayBuffer.prototype.transfer() proposal for JavaScript
60
star
19

path-is-inside

Tests whether one path is inside another path
JavaScript
40
star
20

streams-demo

Demo for Fetch + Streams
HTML
40
star
21

sorted-object

Returns a copy of an object with its keys sorted
JavaScript
35
star
22

traceur-runner

Runs JavaScript.next code in Node by compiling it with Traceur on the fly, seamlessly
JavaScript
35
star
23

last

A small helper for getting only the latest result of an asynchronous operation you perform multiple times in a row.
JavaScript
31
star
24

get-originals

A web platform API that allows access to the "original" versions of the global built-in objects' properties and methods
28
star
25

webidl-class-generator

Generates classes from WebIDL plus implementation code
JavaScript
28
star
26

pubit

Responsible publish/subscribe. Hide the event publisher, only exposing the event emitter.
CoffeeScript
28
star
27

browserify-deoptimizer

Transforms browserify bundles into a collection of single files
CoffeeScript
26
star
28

unhandled-rejections-browser-spec

Spec patches for HTML and ES for tracking unhandled promise rejections with events
22
star
29

wpt-runner

Runs web platform tests in Node.js using jsdom
JavaScript
21
star
30

template-parts

Brainstorming a <template> parts proposal
20
star
31

cooperatively-sized-iframes

A proposal for iframes which can resize according to their content
19
star
32

client-side-packages-demo

A demo application that shows recent commits to npm, using npm packages on the client side via browserify
JavaScript
18
star
33

es6isnigh

A presentation on the future of the JavaScript language.
JavaScript
17
star
34

specgo

A command-line tool for opening web specifications
JavaScript
16
star
35

element-constructors

Some ideas for how to implement constructors for Element, HTMLElement, etc.
JavaScript
15
star
36

html-dashboard

A dashboard for issue and pull request management in whatwg/html
JavaScript
14
star
37

dynamo-as-promised

A promise-based client for Amazon's DynamoDB.
CoffeeScript
11
star
38

amd-wrap

Wraps CommonJS files in `define(function (require, exports, module) { ... })`.
JavaScript
11
star
39

domains-tragedy

An illustration of how Node.js domains can fail you when EventEmitters get involved.
JavaScript
10
star
40

rewrapper

A web application for rewrapping text to fit a column limit
HTML
9
star
41

chromiumizer

Convert an image into the Chromium color pallette
JavaScript
9
star
42

webidl-html-reflector

Implements the algorithms to reflect HTML content attributes as WebIDL attributes
JavaScript
8
star
43

grunt-amd-wrap

Grunt task to wrap CommonJS files in `define(function (require, exports, module) { ... })`.
JavaScript
8
star
44

extensions

Useful extension methods from my own projects
C#
8
star
45

remember-to-eat

My personal meal/calorie/protein tracker
JavaScript
6
star
46

global-wrap

Exposes your CommonJS-based libraries as a global.
JavaScript
6
star
47

origin-agent-cluster-demo.dev

Some Origin-Agent-Cluster demos
HTML
6
star
48

v8-extras-geometry

An exploration of using V8 extras to implement the Geometry spec
JavaScript
6
star
49

jake-diagram-generator

Generates "Jake diagrams", i.e. browser session history timeline diagrams
JavaScript
6
star
50

blog.domenic.me

Hidden Variables: my infrequently-updated blog
Nunjucks
6
star
51

eslint-config

My personal base ESLint config
JavaScript
6
star
52

jsdom-proxy-benchmark

Benchmark for proxies that uses jsdom to build the ECMAScript spec
JavaScript
6
star
53

unownbot-filtered

A daemon that will filter @UnownBot to specific areas and text you about it
JavaScript
6
star
54

cs4h

Homework for General Assembly's CS for Hackers course (Summer 2012)
JavaScript
5
star
55

wk-scripts

My userscripts for WaniKani
JavaScript
4
star
56

gmify

A simple interface to GraphicsMagick for streaming image processing.
JavaScript
4
star
57

emu-algify

Use Ecmarkup's <emu-alg> elements in your HTML
JavaScript
3
star
58

warmup-reps

Initial work on an algorithmically-sound warmup rep calculator
JavaScript
3
star
59

grunt-global-wrap

Grunt task to expose your CommonJS-based libraries as a global.
JavaScript
3
star
60

domains-romance

An illustration of how domains can catch errors on your Node.js server
JavaScript
3
star
61

corrigibility

Corrigibility with Utility Preservation, in TypeScript
TypeScript
3
star
62

throw-catch-cancel-syntax

SweetJS macros for throw cancel and catch cancel
JavaScript
2
star
63

streaming-mediastreams

A spec for extracting the contents of a MediaStream object as a ReadableStream
Shell
2
star
64

whatwg-participant-data-test

A dumping ground test repository for developing whatwg/participate.whatwg.org
1
star
65

test262-to-mjsunit

Converts test262 tests to mjsunit tests
JavaScript
1
star
66

baseline-tester

Runs a function against given inputs and tests the result against baseline outputs
JavaScript
1
star
67

pidgey-calc

A progressive web app that calculates how many Pidgeys you need for your next evolution spree in in Pokรฉmon Go.
HTML
1
star