如何用Jest模拟/替换对象的getter函数? [英] How to mock/replace getter function of object with Jest?
本文介绍了如何用Jest模拟/替换对象的getter函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Sinon中,我可以执行以下操作:
In Sinon I can do the following:
var myObj = {
prop: 'foo'
};
sinon.stub(myObj, 'prop').get(function getterFn() {
return 'bar';
});
myObj.prop; // 'bar'
但是我如何对Jest做同样的事情?
我不能只使用jest.fn()
之类的函数覆盖该函数,因为它不会替代getter
But how can I do the same with Jest?
I can't just overwrite the function with something like jest.fn()
, because it won't replace the getter
无法设置get的值"
"can't set the value of get"
推荐答案
You could use Object.defineProperty
Object.defineProperty(myObj, 'prop', {
get: jest.fn(() => 'bar'),
set: jest.fn()
});
这篇关于如何用Jest模拟/替换对象的getter函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文