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

FinishedPromise.install() replaces native Promise #1

Merged
merged 4 commits into from May 19, 2017
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 12 additions & 0 deletions README.md
Expand Up @@ -32,3 +32,15 @@ describe('FinishedPromise', () => {
})
})
```

## async / await

Overriding `global.Promise` has no effect on `async` functions - they will use
the native v8 `Promise` regardless.

To circumvent this limitation we can transpile the source code prior to running
it. Babel can do this, although rather slowly, which would defeat the purpose
of this library - fast tests!

Instead we can use [async-to-gen](https://github.com/leebyron/async-to-gen) which
is actually very fast. See `./mocha` for an example.
10 changes: 10 additions & 0 deletions index.js
Expand Up @@ -100,4 +100,14 @@ FinishedPromise.reject = function(error) {
})
}

const nativePromise = Promise

FinishedPromise.install = function() {
Promise = FinishedPromise
}

FinishedPromise.uninstall = function() {
Promise = nativePromise
}

module.exports = FinishedPromise
2 changes: 2 additions & 0 deletions mocha
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
node_modules/.bin/async-node node_modules/.bin/_mocha "$@"
3 changes: 2 additions & 1 deletion package.json
Expand Up @@ -4,11 +4,12 @@
"description": "Synchronous implementation of Promise for use in tests",
"main": "index.js",
"scripts": {
"test": "./node_modules/.bin/mocha"
"test": "./mocha"
},
"author": "Josh Chisholm <joshuachisholm@gmail.com>",
"license": "MIT",
"devDependencies": {
"async-to-gen": "^1.3.3",
"mocha": "^3.2.0"
},
"repository": {
Expand Down
40 changes: 40 additions & 0 deletions test/_globalPromiseTest.js
@@ -0,0 +1,40 @@
const assert = require('assert')
const FinishedPromise = require('..')

describe('Promise', () => {
before(() => {
FinishedPromise.install()
})

after(() => {
FinishedPromise.uninstall()
})

it('is replaced with FinishedPromise', () => {
let result

function f1(v) {
return Promise.resolve(v)
}
function f2(v) {
result = v
}

Promise.resolve(123).then(f1).then(f2)
assert.equal(result, 123)
})

it('is replaced with FinishedPromise in async functions', () => {
let result

async function f1(v) {
return v
}
async function f2(v) {
result = v
}

Promise.resolve(123).then(f1).then(f2)
assert.equal(result, 123)
})
})