如何解决Vue 单元测试调整屏幕大小并更新 DOM
我有一个组件,如果屏幕是桌面,它会显示图像,如果屏幕是用于移动设备,它会隐藏图像:
<script>
export default {
name: 'MyComponentApp',}
</script>
<template>
<div class="my-component">
<div class="my-component__image-container">
<img class="my-component__image-container--img" />
</div>
</div>
</template>
<style lang="scss" scoped>
.my-component {
&__image-container {
overflow: hidden;
width: 50%;
&--img {
width: 100%;
height: 100%;
object-fit: cover;
}
}
}
@media (max-width: 600px) {
.my-component {
&__image-container {
&--img {
display: none;
}
}
}
}
</style>
当我尝试执行单元测试用例并测试当 window.width
低于 600px
时图像是否隐藏时,它不会更新 DOM 并且图像仍然可见:>
import MyComponentApp from './MyComponentApp.vue';
import { shallowMount } from '@vue/test-utils';
const factory = () => {
return shallowMount(MyComponentApp,{});
};
describe('DownloadApp.vue',() => {
let wrapper;
beforeEach(() => {
wrapper = factory();
});
describe('Check Items on Mobile Devices',() => {
it('Img on div.my-component__image-container shouldn\'t be displayed',async () => {
jest.spyOn(screen,'height','get').mockReturnValue(500);
jest.spyOn(screen,'width','get').mockReturnValue(500);
await wrapper.vm.$nextTick();
const image = wrapper.find('div.my-component__image-container > img');
expect(image.isVisible()).toBe(false);
});
});
});
但是,测试失败了:
DownloadApp.vue › Check Items on Mobile Devices › Img on div.my-component__image-container shouldn\'t be displayed
expect(received).toBe(expected) // Object.is equality
Expected: false
Received: true
有谁知道如何更新 DOM 或让测试用例意识到屏幕宽度已经改变并且应该显示图像?
解决方法
CSS @media
查询依赖于视口大小,目前无法单独从 Jest 进行操作,在这种情况下,在 Jest 中设置 window.innerWidth
不会有任何影响.
或者,您可以在 Cypress 测试中调整视口的大小。在 Vue CLI 项目中,您可以通过从项目的根目录运行以下命令来添加 Cypress plugin:
vue add e2e-cypress
然后在 <root>/tests/e2e/test.js
中插入以下测试,在检查 img
元素的可见性之前使用 cy.viewport()
设置视口大小:
describe('My img component',() => {
it('should show image for wide viewport',() => {
cy.visit('/') // navigate to page where test component exists
cy.viewport(800,600)
cy.get('.my-component__image-container--img').should('be.visible')
})
it('should hide image for narrow viewport',() => {
cy.visit('/') // navigate to page where test component exists
cy.viewport(500,600)
cy.get('.my-component__image-container--img').should('not.be.visible')
})
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。