Home > Blockchain >  Argument not assignable when mocking method with Jest
Argument not assignable when mocking method with Jest

Time:07-14

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?

CodePudding user response:

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);
  • Related