Ben
Ben

Reputation: 353

vue test utils v2 : cannot mock a global function

Brand new to vue testing and I'm trying to test a component that calls a global function this is imported in my app.js

A simplified version of the component ConversationStatus:

<script setup>
    import { computed, ref } from 'vue';
    import { router } from '@inertiajs/vue3';
    import ArchiveIcon from '@/Components/Media/Icons/ArchiveIcon.vue';
    import ButtonStandard from '@/Components/ButtonStandard.vue';

    ///

    const methods = {

        toggleArchive(){
            router.visit(route('conversation.toggleArchive',props.conversation.id));
        },

        ///
 
    }

</script>
<template>

  ///

  <ButtonStandard  @click="methods.toggleArchive" dusk="inbox_archive_invite">
        <ArchiveIcon class="w-5 fill-red-500"/>
   </ButtonStandard>
        

</template>

My Test:

 it("should call toggle_archive route when clicked", async () => {


    const wrapper = mount(ConversationStatus, {
        mocks: {
          route: (r) => r
        }
    });

    expect(wrapper.find('[dusk="inbox_toggle_archive"]').exists()).toBe(true);

    await wrapper.find('[dusk="inbox_toggle_archive"]').trigger('click');

    expect(methods.toggleArchive).toHaveBeenCalled();

  })

This gives me the error

 ReferenceError: route is not defined

     56|         toggleArchive(){
     57|             router.visit(route('conversation.toggleArchive',props.conversation.id));
       |                    ^
     58|         },

I've tried various methods of mocking I have found in the docs and articles

const route = vi.fn((r) => r) from vitest

config.global.mocks.route = (r) => r; from vitest

I was going to try stubbing in vue test utils, but I think you can only stub components or directives but not functions?

I'm a bit lost and stabbing in the dark at solutions now.

Upvotes: 0

Views: 191

Answers (1)

Ben
Ben

Reputation: 353

So it seems it's a scoping issue and my misunderstanding of the scope for mocks in the test.

If I create the mock as global in the test itself then it runs fine:

it("should call toggle_archive route when clicked", async () => {

    global.route = vi.fn();

    const wrapper = mount(ConversationStatus);

    expect(wrapper.find('[dusk="inbox_toggle_archive"]').exists()).toBe(true);

    await wrapper.find('[dusk="inbox_toggle_archive"]').trigger('click');

    expect(methods.toggleArchive).toHaveBeenCalled();
    expect(global.route.mock.calls[0]).toContain('conversation.toggleArchive');

  })

However, I'm still unclear how to add this is as a global to my config file

Upvotes: 0

Related Questions