Javascript 如何用 Jest 模拟/替换对象的 getter 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43697455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mock/replace getter function of object with Jest?
提问by I_like_foxes
In Sinon I can do the following:
在诗浓我可以做到以下几点:
var myObj = {
prop: 'foo'
};
sinon.stub(myObj, 'prop').get(function getterFn() {
return 'bar';
});
myObj.prop; // 'bar'
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
但是我怎么能用 Jest 做同样的事情呢?我不能只是用类似的东西覆盖函数jest.fn(),因为它不会取代吸气剂
"can't set the value of get"
“无法设置get的值”
回答by Franey
For anyone else stumbling across this answer, Jest 22.1.0 introduced the ability to spy on getter and setter methods.
对于遇到此答案的任何其他人,Jest 22.1.0 引入了监视 getter 和 setter 方法的能力。
Edit: like in scieslak's answerbelow, because you can spy on getter and setter methods, you can use Jest mocks with them, just like with any other function:
编辑:就像下面scieslak 的回答一样,因为您可以监视 getter 和 setter 方法,所以您可以对它们使用 Jest 模拟,就像使用任何其他函数一样:
class MyClass {
get something() {
return 'foo'
}
}
jest.spyOn(MyClass, 'something', 'get').mockReturnValue('bar')
const something = new MyClass().something
expect(something).toEqual('bar')
回答by Alex Robertson
You could use Object.defineProperty
Object.defineProperty(myObj, 'prop', {
get: jest.fn(() => 'bar'),
set: jest.fn()
});
回答by scieslak
OMG I've been here so many times. Finally figure out the proper solution for this. If you care about spying only. Go for @Franey 's answer. However if you actually need to stub a value for the getter this is how you can do it
天哪,我来过这里很多次了。最后找出正确的解决方案。如果您只关心间谍活动。寻找@Franey 的答案。但是,如果您确实需要为 getter 存根一个值,那么您可以这样做
class Awesomeness {
get isAwesome() {
return true
}
}
describe('Awesomeness', () => {
it('is not always awesome', () => {
const awesomeness = new Awesomeness
jest.spyOn(awesomeness, 'isAwesome', 'get').mockReturnValue(false)
expect(awesomeness.isAwesome).toEqual(false)
})
})

