首页 > 解决方案 > 具有 Jest 存根功能的 Vue3 不会存根

问题描述

零件:

<template>
  <div id="fileviewer" class="min-h-full">
    <section class="gap-4 mt-4">
      <div class="bg-medium-50 w-1/3 p-4">
        <FileUpload ></FileUpload>
      </div>
      <div class="bg-medium-50 w-2/3 p-4">
        <FileViewer></FileViewer>
      </div>
    </section>
  </div>
</template>

<script>
import FileUpload from "@/components/FileUpload";
import FileViewer from "@/components/FileViewer";

export default {
  name: "FileManager",
  components: { FileUpload, FileViewer },
};
</script>

测试:

import { mount } from "@vue/test-utils";
import FileManager from '@/views/FileManager';

describe('FileManager.vue', () =>{

  it('should mount', () => {
    const wrapper = mount(FileManager, {
      global: {
        stubs: {
          FileUpload: true,
          FileViewer: true
        }
      }
    })

    expect(wrapper).toBeDefined()
  })

})

根据文档对我不起作用。无特殊装置。相反,框架想要为子组件执行“导入”语句,然后失败,因为我不想为这个组件模拟“获取”。有任何想法吗?

"vue-jest": "^5.0.0-alpha.9"
"@vue/test-utils": "^2.0.0-rc.6"
"vue": "^3.0.0",

感谢帮助。

标签: unit-testingjestjsvuejs3vue-test-utils

解决方案


。如果您想自动存根所有子组件,您可以使用shallowMount而不是mount.

.如果您想这样使用mount,请尝试像这样修复您的存根:

global: {
  stubs: {
    FileUpload: {
      template: '<div class="file-upload-or-any-class-you-want">You can put there anything you want</div>'
    },
    FileViewer: {
      template: '<div class="file-viewer-or-any-class-you-want">You can put there anything you want</div>'
    }
  }
}


或者您可以像往常一样在测试之前定义存根。例如:

const FileUploadStub = {
  template: '<div class="file-upload-or-any-class-you-want">You can put there anything you want</div>'
}

const FileViewerStub: {
  template: '<div class="file-viewer-or-any-class-you-want">You can put there anything you want</div>'
}

mount然后在or中使用存根shallowMount

global: {
  stubs: {
    FileUpload: FileUploadStub,
    FileViewer: FileViewerStub
  }
}

推荐阅读