Skip to content

Commit

Permalink
fix: fix promise check to accept any spec conform object (#1424)
Browse files Browse the repository at this point in the history
An instanceof check only accept promises which are created using the `Promise`
constructor. But there are other libraries which their own contructors. These
promises should also work as long as they adhere to the spec.
  • Loading branch information
micha149 authored and mleguen committed Sep 18, 2019
1 parent afaf6d3 commit 0be43d2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/is-promise.js
@@ -1,3 +1,3 @@
module.exports = function isPromise (maybePromise) {
return maybePromise instanceof Promise
return !!maybePromise && !!maybePromise.then && (typeof maybePromise.then === 'function')
}
34 changes: 34 additions & 0 deletions test/is-promise.js
@@ -0,0 +1,34 @@
'use strict'
/* global describe, it */

const { expect } = require('chai')
const isPromise = require('../lib/is-promise')

describe('isPromise', () => {
it('returns `false` on non promise value', () => {
expect(isPromise('hello there.')).to.be.equal(false)
})

it('returns `true` on es6 promise', () => {
const esPromise = new Promise(() => {})
expect(isPromise(esPromise)).to.be.equal(true)
})

it('returns `true` on some other thenable', () => {
const thenable = { then: () => {} }
expect(isPromise(thenable)).to.be.equal(true)
})

it('returns `false` if some falsy value is passed', () => {
expect(isPromise(null)).to.be.equal(false)
})

it('returns `false` if passed object has no `then` property', () => {
expect(isPromise({})).to.be.equal(false)
})

it('returns `false` if `then` is not a function', () => {
const obj = { then: 4711 }
expect(isPromise(obj)).to.be.equal(false)
})
})

0 comments on commit 0be43d2

Please sign in to comment.