[英]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" |
'"consentGiven"' 类型的参数不可分配给 '"prototype" 类型的参数 | "contextType"'.ts(2345) Argument of type 'true' is not assignable to parameter of type 'ReissueButton |
"contextType"'.ts(2345) 'true' 类型的参数不可分配给'ReissueButton | 类型的参数Context |
上下文 | PromiseLike<ReissueButton |
PromiseLike<重发按钮 | Context |
上下文 | undefined> |
未定义> | undefined'.ts(2345)
未定义'.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选项1
const mock = jest.spyOn(ReissueButton.prototype, 'consentGiven').mockResolvedValue(true);
Option 2选项 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.