Search code examples
javascriptunit-testingvue.jsjestjsvue-test-utils

Mocking vue component dependencies


I'm trying to run a unit test in which I make an axios call and this returns an error. I have managed to mock the call successfully but on error I call an dependency on an external library (vue-toasted) to display an error message.

When my unit test hits toasted it is 'undefined':

TypeError: Cannot read property 'error' of undefined

    this.$toasted.error('Search ' + this.searchString + ' returned no results', etc.....

I have attempted to register this dependancy in my test wrapper as such

import Toasted from 'vue-toasted';

jest.mock(Toasted);

these don't seem to provide the wrapper with the correct dependency. Here is my test:

it('searches users via axios and returns 404', async () => {
    mock.onPost(process.env.VUE_APP_IDENTITY_API_URL + 'user/search').reply(404);

    await wrapper.vm.searchUsers(1);
    expect(mock.history.post.length).toBe(1);
    expect(wrapper.vm.users).toBeNull();
    expect(wrapper.vm.pagingInfo).toBeNull();
})

this is how my component wrapper is mocked up:

const wrapper =  shallowMount(Users, {
  stubs: {
    RouterLink: RouterLinkStub
  }
});

does anyone know what the correct syntax would be to register this syntax?


Solution

  • Try add it:

    const wrapper = shallowMount(Users, {
      mocks: {
         $toasted: {
             error: () => {},
         }
      }
    });
    

    Of course you can add more functionality to your mocks.