-
-
Notifications
You must be signed in to change notification settings - Fork 769
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add a how-to guide for speeding up time with lolex #1931
Merged
fatso83
merged 8 commits into
sinonjs:master
from
orlangure:testing-promises-with-lolex
Jun 28, 2019
Merged
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
feb09d1
Add vim swp files to .gitignore
cb722ac
Add a how-to on speeding up time with lolex
2f00e49
Reword guide title
5bb69f1
Write a second draft for fake timers guide
29bb8e1
Remove swp from gitignore
bb18bf2
Merge branch 'master' of https://github.com/sinonjs/sinon into testin…
6264595
Fix a typo in lolex async promises docs
beaaff3
Explain weird setTimeoutPromise usage in comments
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,108 @@ | ||||||
--- | ||||||
layout: page | ||||||
title: How to test async functions with fake timers | ||||||
--- | ||||||
|
||||||
With fake timers (lolex), testing code that depends on timers is easier, as it sometimes | ||||||
becomes possible to skip the waiting part and trigger scheduled callbacks | ||||||
synchronously. Consider the following function of a maker module (a module | ||||||
that makes things): | ||||||
|
||||||
```js | ||||||
// maker.js | ||||||
module.exports.callAfterOneSecond = callback => { | ||||||
setTimeout(callback, 1000); | ||||||
}; | ||||||
``` | ||||||
|
||||||
We can use Mocha with lolex to verify that `callAfterOneSecond` works as expected, but | ||||||
skipping that part where the test takes one second: | ||||||
|
||||||
```js | ||||||
// test.js | ||||||
before( | ||||||
lolex.install(); | ||||||
); | ||||||
// ... | ||||||
|
||||||
it('should call after one second', () => { | ||||||
const spy = sinon.spy(); | ||||||
maker.callAfterOneSecond(spy); | ||||||
|
||||||
// callback is not called immediately | ||||||
assert.ok(!spy.called); | ||||||
|
||||||
// but it is called synchronously after the clock is fast forwarded | ||||||
clock.tick(1000); | ||||||
assert.ok(spy.called); // PASS | ||||||
}); | ||||||
``` | ||||||
|
||||||
The same approach can be used to test an `async` function: | ||||||
|
||||||
```js | ||||||
module.exports.asyncReturnAfterOneSecond = async () => { | ||||||
// util.promisify is not used deliberately | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
const setTimeoutPromise = timeout => { | ||||||
return new Promise(resolve => setTimeout(resolve, timeout)); | ||||||
}; | ||||||
await setTimeoutPromise(1000); | ||||||
return 42; | ||||||
}; | ||||||
``` | ||||||
|
||||||
The following test uses Mocha's [support for promises](https://mochajs.org/#working-with-promises): | ||||||
|
||||||
```js | ||||||
// test.js | ||||||
it('should return 42 after one second', () => { | ||||||
const promise = maker.asyncReturnAfterOneSecond(); | ||||||
clock.tick(1000); | ||||||
return promise.then(result => assert.equal(result, 42)); // PASS | ||||||
}); | ||||||
``` | ||||||
|
||||||
While returning a Promise from the Mocha’s test, we can still progress the timers | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
using lolex, so the test passes almost instantly, and not in 1 second. | ||||||
|
||||||
Since `async` functions behave the same way as functions that return promises | ||||||
explicitly, the following code can be tested using the same approach: | ||||||
|
||||||
```js | ||||||
// maker.js | ||||||
module.exports.fulfillAfterOneSecond = () => { | ||||||
return new Promise(resolve => { | ||||||
setTimeout(() => fulfill(42), 1000); | ||||||
}); | ||||||
}; | ||||||
``` | ||||||
|
||||||
```js | ||||||
// test.js | ||||||
it('should be fulfilled after one second', () => { | ||||||
orlangure marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
const promise = maker.fulfillAfterOneSecond(); | ||||||
clock.tick(1000); | ||||||
return promise.then(result => assert.equal(result, 42)); // PASS | ||||||
}); | ||||||
``` | ||||||
|
||||||
Knowing that `async` functions return promises under the hood, | ||||||
we can write another test using `async/await`: | ||||||
|
||||||
```js | ||||||
// test.js | ||||||
it('should return 42 after 1000ms', async () => { | ||||||
const promise = maker.asyncReturnAfterOneSecond(); | ||||||
clock.tick(1000); | ||||||
const result = await promise; | ||||||
assert.equal(result, 42); // PASS | ||||||
}); | ||||||
``` | ||||||
|
||||||
A callback in the above test still returns a Promise, but for a user it looks | ||||||
like some straightforward synchronous code. | ||||||
|
||||||
Although these tests pass almost instantly, they are still asynchronous. Note | ||||||
that they return promises instead of running the assertions right after the | ||||||
`clock.tick(1000)` call, like in the first example. **Promises' `then()` | ||||||
function always runs asynchronously**, but we can still speed up the tests. |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I need your help here. I think this comment should not be in a guide, but without it it looks like a mistake to not use
util.promisify
.When it is used though, the test fails.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Make it a proxy to
util.promisify
or call clock.install() beforeutil.promisify
is called (because then it holds a reference to the original setTimeout):There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nope, even with
lolex.install
call beforeutil.promisify
, tests of this function fail.What did you mean by proxying somehting to
util.promisify
? I'll check it as well.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this needs to be fixed in lolex. I'll make an issue.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For reference, the issue is sinonjs/fake-timers#227