简体   繁体   中英

Argument not assignable when mocking method with Jest

I tried t mock a method as follows:

const mock = jest.spyOn(ReissueButton, 'consentGiven').mockResolvedValue(true);

It gives me these errors:

Argument of type '"consentGiven"' is not assignable to parameter of type '"prototype" | "contextType"'.ts(2345) Argument of type 'true' is not assignable to parameter of type 'ReissueButton | Context | PromiseLike<ReissueButton | Context | undefined> | undefined'.ts(2345)

The method returns a true or false value.

This is the method:

consentGiven = () => {        
    const ref = crypto.createHash('sha1').update(this.props.policy).digest('hex');
    const consented = Cookies.get('CONSENT_' + ref) || null;

    if (consented === null) {
        return false;
    } else {
        return true;
    }
}

What am I doing wrong?

That error is probably because you are trying to spy on a non-static method of a class without creating a new instance. You can either spy on the class prototype or make the method static:

Option 1

const mock = jest.spyOn(ReissueButton.prototype, 'consentGiven').mockResolvedValue(true);

Option 2

static consentGiven = () => {        
    const ref = crypto.createHash('sha1').update(this.props.policy).digest('hex');
    const consented = Cookies.get('CONSENT_' + ref) || null;

    if (consented === null) {
        return false;
    } else {
        return true;
    }
}

const mock = jest.spyOn(ReissueButton, 'consentGiven').mockResolvedValue(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM