如何在Vue Jest测试用例中设置screen.height与screen.width
解决Vue Utils-Jest中screen.width/height的测试覆盖率问题
看起来你在测试Vue组件时遇到了screen对象模拟的问题,导致代码覆盖率不达标。先帮你指出之前测试代码的核心问题:你错误地把screen挂载到了HTMLElement.prototype上,但实际上screen是全局window对象的属性,不是DOM元素的原型属性。
接下来我会给你正确的测试方案,覆盖代码的所有分支,解决覆盖率问题:
核心思路
你的组件逻辑有两个分支:
- 当组件自身的
clientWidth/clientHeight有值时,优先使用这些值 - 当这些值不存在时,回退到
screen.width/screen.height
要达标覆盖率,必须为这两个分支分别编写测试用例,同时正确模拟window.screen的属性。
正确的测试用例代码
假设你的组件文件是YourComponent.vue,测试文件如下:
import { mount } from '@vue/test-utils'; import YourComponent from '@/components/YourComponent.vue'; describe('YourComponent', () => { // 每次测试前重置window.screen,避免测试间状态污染 beforeEach(() => { // 配置可修改的screen.width和height Object.defineProperty(window.screen, 'width', { value: 1920, configurable: true, // 允许后续修改 writable: true }); Object.defineProperty(window.screen, 'height', { value: 1080, configurable: true, writable: true }); }); // 测试分支1:使用组件自身的clientWidth/clientHeight it('should prioritize component\'s clientWidth/clientHeight when provided', () => { const wrapper = mount(YourComponent, { data() { return { clientWidth: 800, clientHeight: 600 }; } }); // 根据组件实际使用这些值的逻辑断言,比如组件把值存在viewportSize中 expect(wrapper.vm.viewportSize.width).toBe(800); expect(wrapper.vm.viewportSize.height).toBe(600); }); // 测试分支2:回退到screen的默认值 it('should fallback to screen dimensions when clientWidth/clientHeight are missing', () => { // 临时修改screen的值,验证是否能正确获取 window.screen.width = 1366; window.screen.height = 768; const wrapper = mount(YourComponent, { data() { return { clientWidth: null, clientHeight: undefined }; } }); // 断言使用了screen的数值 expect(wrapper.vm.viewportSize.width).toBe(1366); expect(wrapper.vm.viewportSize.height).toBe(768); }); });
关键说明
- 正确模拟window.screen:Jest的测试环境基于jsdom,
screen是window的属性,所以直接修改window.screen即可,不需要操作DOM元素原型。 - configurable: true:必须设置这个属性,这样每次测试都可以重新赋值
screen.width/height,避免测试用例之间的状态污染。 - 覆盖所有分支:两个测试用例分别覆盖了
clientWidth存在和不存在的情况,确保代码的每一行都被执行,解决覆盖率问题。
如果你的组件中是在created或mounted钩子中执行这段逻辑,那么在mount组件前设置好screen的值就可以正常触发逻辑了。
内容的提问来源于stack exchange,提问作者ramprakash jagadeesan
相关产品推荐
相关产品推荐

