如何让Object.defineProperty的get方法返回实际设置的值?
解决方案
你的测试用例存在几个关键问题,导致无法正确捕获被测方法设置的hash值:
问题点分析
- 拼写错误:代码中
global.indow.location是笔误,应为global.window.location,这会导致你定义的getter/setter根本没有挂载到正确的window对象上,自然无法拦截hash的读写。 - 固定返回的getter:
getHashSpy硬编码返回#/someHash,没有跟踪setter设置的实际值,所以无论被测方法怎么修改hash,get操作都会返回固定值。 - 语法错误:
if(node.text()) === 'Go to Profile')多了一个括号,会导致条件判断失效,点击事件根本不会触发。
修正后的测试用例
test('changeHash works correctly', () => { // 用变量存储hash的实际值,模拟真实的location.hash行为 let currentHash = '#/someHash'; const getHashSpy = jest.fn(() => currentHash); const setHashSpy = jest.fn(hash => { currentHash = hash; // setter更新存储的hash值 return hash; }); delete global.window.location; global.window = Object.create(window); global.window.location = {}; // 修正拼写错误:global.window.location Object.defineProperty(global.window.location, 'hash', { get: getHashSpy, set: setHashSpy, }); const wrapper = mount(component); const links = wrapper.find('.link'); links.forEach((node) => { // 修正语法错误:去掉多余的括号 if(node.text() === 'Go to Profile') { node.simulate('click'); // 断言hash值被正确修改 expect(global.window.location.hash).toBe('#/settings'); // 也可以直接断言setter被调用了正确的参数 expect(setHashSpy).toHaveBeenCalledWith('#/settings'); } }); });
关键修改说明
- 新增
currentHash变量来维护hash的实际状态,让getter返回该变量,setter更新该变量,完全模拟真实浏览器中window.location.hash的读写逻辑。 - 修正了
global.indow的拼写错误,确保拦截器生效。 - 修复了条件判断的语法错误,保证点击事件能被正确触发。
- 新增了对
setHashSpy的调用断言,双重验证被测方法的行为是否符合预期。
内容的提问来源于stack exchange,提问作者user17485523
相关产品推荐
相关产品推荐

