如何用 Jest 模拟/替换对象的 getter 函数? [英] How to mock/replace getter function of object with Jest?
本文介绍了如何用 Jest 模拟/替换对象的 getter 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在诗浓我可以做到以下几点:
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的值"
推荐答案
你可以使用 Object.defineProperty
Object.defineProperty(myObj, 'prop', {
get: jest.fn(() => 'bar'),
set: jest.fn()
});
这篇关于如何用 Jest 模拟/替换对象的 getter 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文