Search code examples
unit-testingjestjsvuejs3vue-test-utils

Vue3 with Jest stub functionality does not stub


Component:

<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>

Test:

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()
  })

})

Does not work for me as per the docs. No special installations. Instead, The framework wants to do the 'import' statements for the child components and then fails because I do not want to mock out 'fetch' for this one component. Any Ideas?

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

Thanks for help.


Solution

  • I. If you want to stub all child components automatically you just can use shallowMount instead of mount.

    II. If you want so use mount anyway try to fix your stubs like that:

    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>'
        }
      }
    }
    
    
    

    Or you can define your stubs before tests as I always do. For example:

    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>'
    }
    

    And then use stubs in mount or shallowMount:

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