使用Vitest搞单元测试踩坑日记

624 阅读1分钟

最近公司内部私有业务组件库要搞单元测试,,记录一下在使用的过程中踩的一些坑。目前就有这么多,后续踩到了会继续更。同时也希望和各位搞单元测试的同学多多交流 增加增加经验~

测试antd-vue二次封装组件遇到的问题

直接上demo 简单明了

// demo.vue
<template>
    <a-drawer v-model:visible="visible" title="test demo" class="demo-drawer" placement="right">
        <div class="test-demo">hhh</div>
    </a-drawer>
</template>

<script setup>
import { ref, watch } from 'vue';

const props = defineProps({
    visible: {
        type: Boolean
    }
});

</script>
<style scoped></style>
//demo.test.ts
/**
 * @vitest-environment jsdom
 */
import { describe, expect, test, it } from "vitest";
import { mount, shallowMount } from "@vue/test-utils";
import { ref, nextTick } from "vue";
import Demo from "../demo.vue";

describe("", () => {
const wrapper = mount(Demo as any, {
        props: { visible: true },
        shallow: true
    });
})
it("render Drawer", () => {
  expect(wrapper.find('.ant-drawer')).toBeTruthy()
  expect(wrapper.find('.test-demo')).toBeTruthy()
  expect(wrapper.find('.test-demo').text()).toBe("hhh")
 })

写完运行之后立马就是当头一棒

image.png

WTF? 上面一行代码已经判断.test-demotrue了 怎么拿不到里面的内容呢?之后wrapper.html()打印一下dom元素 发现什么也没有 简直就是一个大震惊

后来翻了翻@vue/test-utils这个包的文档,发现了global的renderStubDefaultSlot这个属性,文档上写的是Renders the default slot content, even when useing shallow or shallowMount翻译来就是即使在使用shallow或shallowMount时,也会呈现默认的插槽内容

我又跑去看了下antd-vue的源码 发现写在内部的元素确实是被放进了默认插槽里
image.png

真相大白了 在加上这个属性后 html确实也能打印出dom元素了 看下图

const wrapper = mount(Demo as any, {
        props: { visible: true },
        global: {
            renderStubDefaultSlot: true
        },
        shallow: true
});

image.png

目前就这一个 但我预测不会止于这一个 踩坑后会继续更新~