Use native promise in protractor

Viewed 662

Is there way to use protractor filter which accepts a function that returns protractor's own Promise type, with my own function that returns native Promise?

const myFilter = async(e: ElementFinder): Promise<boolean> => {
...
}
myElements.filter(myFilter)

This raises TypeScript compilation error

TS2345:Argument of type '(e: ElementFinder) => >Promise' is not assignable to parameter of type '(element: >ElementFinder, index?: number) => boolean | Promise'. Type 'Promise' is not assignable to type 'boolean | Promise'. Type 'Promise' is not assignable to type 'promise.Promise'. Property 'cancel' is missing in type 'Promise'.

BTW, I cannot create protractor's Promise myself, because of deprecaion (https://github.com/SeleniumHQ/selenium/issues/2969)

1 Answers

Ok, If this is still relevant, I got to working with tests again and this time I found a solution right away.

These helpers open the bridge between protractor.promise.Promise and native Promise.

const toNativePromise = <T = void>(p: protractor.promise.Promise<T>): Promise<T> => { 
    return new Promise((res, rej) => {
        p.then(res).catch(rej)
    })
}
const toProtractorPromise = <T = void>(native_promise: Promise<T>): protractor.promise.Promise<T> => {
    const deferred = protractor.promise.defer<T>();
    const protractorPromise = deferred.promise;
    native_promise.then(deferred.fulfill).catch(deferred.reject)
    return protractorPromise
}

Anyways, For solving your initial problem, you can write something like this:

const myFilter = async(e: ElementFinder): Promise<boolean> => { ... }
const myFilterForProtractor = (e) => toProtractorPromise(myFilter(e))

Related