TypeError: Method Promise.prototype.then called on incompatible receiver Proxy

Viewed 1935

to perform integration testing I used jasmine and puppeteer and since I am passing an educational course ,according to that ,I decided to use a js Proxy to encapsulate testing functionality but when I do my test I will encounter with the following error

TypeError: Method Promise.prototype.then called on incompatible receiver [object Object] 

here is my CustomPage class which is going to represent a chrome tab : const puppeteer = require('puppeteer');

class CustomPage{
    static async build(){
        const browser =await  puppeteer.launch({headless:false});
        const page = browser.newPage();

        var customPage = new CustomPage(page);
        console.log("harchi run mishe")
        return new Proxy(customPage,{
            get:function(target,property){
                return (customPage[property]||page[property]||browser[property])
            }
        })
        //return proxy;
    }

    constructor(page){
        this.page = page
    }
}


module.exports=CustomPage;

and here is my header.spec.js file which is my test file.

const Page = require('./helpers/page');
var tab;

describe('header representation',()=>{
    beforeEach(async(done)=>{
        tab =await Page.build();****here is the problem********
        await tab.goto('localhost:3000');
    })

    it('should show header logo',async()=>{
        const text = await tab.$eval('a.brand-logo',(el)=>el.innerHTML);
        expect(text).toEqual('Blogster');
        //done()
    })
})

I have actually convicted that my problem is with the specified line .it seems that js can't treat proxy as a Promise however I couldn't find any solution to that.

1 Answers

For posterity, I discovered that with Proxies you need to rebind javascript's this keyword. Example:

function validator(promise, prop) {
    if (prop in promise || promise.hasOwnProperty(prop)) {
        if (typeof promise[prop] === 'function') {
            return promise[prop].bind(promise); // << Important part!
        }
        return promise[prop];
    }

    return 'Fake!';
}

const proxy = new Proxy(
    Promise.resolve('Testing 1 2 3'),
    validator
);

console.log(proxy.someFakeThing); // prints 'Fake!'

proxy.then(console.log); // Prints 'Testing 1 2 3'
Related