Skip to content

Commit 3fd809c

Browse files
committedMar 11, 2016
Merge pull request #80 from sambostock/add-done-to-documentation
Document asynchronous caveat
2 parents e3b766c + fac5372 commit 3fd809c

File tree

1 file changed

+38
-3
lines changed

1 file changed

+38
-3
lines changed
 

‎README.md

+38-3
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ json, or even file attachments added to it, all with a simple API:
8080
chai.request(app)
8181
.put('/user/me')
8282
.set('X-API-Key', 'foobar')
83-
.send({ passsword: '123', confirmPassword: '123' })
83+
.send({ password: '123', confirmPassword: '123' })
8484
```
8585

8686
```js
@@ -120,13 +120,48 @@ To make the request and assert on its response, the `end` method can be used:
120120
```js
121121
chai.request(app)
122122
.put('/user/me')
123-
.send({ passsword: '123', confirmPassword: '123' })
123+
.send({ password: '123', confirmPassword: '123' })
124124
.end(function (err, res) {
125125
expect(err).to.be.null;
126126
expect(res).to.have.status(200);
127127
});
128128
```
129129

130+
##### Caveat
131+
132+
Because the `end` function is passed a callback, assertions are run
133+
asynchronously. Therefore, a mechanism must be used to notify the testing
134+
framework that the callback has completed. Otherwise, the test will pass before
135+
the assertions are checked.
136+
137+
For example, in the [Mocha test framework](http://mochajs.org/), this is
138+
accomplished using the
139+
[`done` callback](https://mochajs.org/#asynchronous-code), which signal that the
140+
callback has completed, and the assertions can be verified:
141+
142+
```js
143+
it('fails, as expected', function(done) { // <= Pass in done callback
144+
chai.request('http://localhost:8080')
145+
.get('/')
146+
.end(function(err, res) {
147+
expect(res).to.have.status(123);
148+
done(); // <= Call done to signal callback end
149+
});
150+
}) ;
151+
152+
it('succeeds silently!', function() { // <= No done callback
153+
chai.request('http://localhost:8080')
154+
.get('/')
155+
.end(function(err, res) {
156+
expect(res).to.have.status(123); // <= Test completes before this runs
157+
});
158+
}) ;
159+
```
160+
161+
When `done` is passed in, Mocha will wait until the call to `done()`, or until
162+
the [timeout](http://mochajs.org/#timeouts) expires. `done` also accepts an
163+
error parameter when signaling completion.
164+
130165
#### Dealing with the response - Promises
131166

132167
If `Promise` is available, `request()` becomes a Promise capable library -
@@ -135,7 +170,7 @@ and chaining of `then`s becomes possible:
135170
```js
136171
chai.request(app)
137172
.put('/user/me')
138-
.send({ passsword: '123', confirmPassword: '123' })
173+
.send({ password: '123', confirmPassword: '123' })
139174
.then(function (res) {
140175
expect(res).to.have.status(200);
141176
})

0 commit comments

Comments
 (0)
Please sign in to comment.