Skip to content
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
merged 8 commits into from
Jun 28, 2019
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
108 changes: 108 additions & 0 deletions docs/_howto/lolex-async-promises.md
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
Copy link
Contributor Author

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.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When it is used though, the test fails.

Make it a proxy to util.promisify or call clock.install() before util.promisify is called (because then it holds a reference to the original setTimeout):

module.exports. asyncReturnAfterOneSecond = async () => {
  const setTimeoutPromise = util.promisify(setTimeout); //
  // ...
}

Copy link
Contributor Author

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 before util.promisify, tests of this function fail.

What did you mean by proxying somehting to util.promisify? I'll check it as well.

Copy link
Member

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.

Copy link
Contributor

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

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// util.promisify is not used deliberately
// Using util.promisify would look nicer, but there is a lolex issue blocking this at the moment: https://github.com/sinonjs/lolex/pull/227

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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
While returning a Promise from the Mocha’s test, we can still progress the timers
While returning a Promise from Mocha’s test, we can still progress the timers

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.