Update: This is no longer the best answer. Please vote up my other answer instead.
obj instanceof Promise
should do it. Note that this may only work reliably with native es6 promises.
If you're using a shim, a promise library or anything else pretending to be promise-like, then it may be more appropriate to test for a "thenable" (anything with a .then method), as shown in other answers here.
it('should return a promise', function() {
var result = testedFunctionThatReturnsPromise();
expect(result).toBeDefined();
// 3 slightly different ways of verifying a promise
expect(typeof result.then).toBe('function');
expect(result instanceof Promise).toBe(true);
expect(result).toBe(Promise.resolve(result));
});
In case you are using Typescript, I'd like to add that you can use the "type predicate" feature. Just should wrap the logical verification in a function that returns x is Promise<any> and you won't need to do typecasts. Below on my example, c is either a promise or one of my types which I want to convert into a promise by calling the c.fetch() method.
export function toPromise(c: Container<any> | Promise<any>): Promise<any> {
if (c == null) return Promise.resolve();
return isContainer(c) ? c.fetch() : c;
}
export function isContainer(val: Container<any> | Promise<any>): val is Container<any> {
return val && (<Container<any>>val).fetch !== undefined;
}
export function isPromise(val: Container<any> | Promise<any>): val is Promise<any> {
return val && (<Promise<any>>val).then !== undefined;
}
Update: This is no longer the best answer. Please vote up my other answer instead.
should do it. Note that this may only work reliably with native es6 promises.
If you're using a shim, a promise library or anything else pretending to be promise-like, then it may be more appropriate to test for a "thenable" (anything with a
.then
method), as shown in other answers here.after searching for a reliable way to detect Async functions or even Promises, i ended up using the following test :
Checking if something is promise unnecessarily complicates the code, just use
Promise.resolve
If you are in an async method you can do this and avoid any ambiguity.
If the function returns promise, it will await and return with the resolved value. If the function returns a value, it will be treated as resolved.
In case you are using Typescript, I'd like to add that you can use the "type predicate" feature. Just should wrap the logical verification in a function that returns
x is Promise<any>
and you won't need to do typecasts. Below on my example,c
is either a promise or one of my types which I want to convert into a promise by calling thec.fetch()
method.More info: https://www.typescriptlang.org/docs/handbook/advanced-types.html