Skip to content

Commit

Permalink
Merge pull request #1 from aslakhellesoy/install-as-native-promise
Browse files Browse the repository at this point in the history
FinishedPromise.install() replaces native Promise
  • Loading branch information
joshski committed May 19, 2017
2 parents 0ac96b5 + 9f1a805 commit 7571c1a
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 1 deletion.
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)
})
})

0 comments on commit 7571c1a

Please sign in to comment.