Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a custom directive from another module in a component

I have a UI library that we import into our app. In the UI library is a custom directive, toggle, that we use for opening and closing a modal. When I run unit tests, I get this error:

[Vue warn]: Failed to resolve directive: toggle

      (found in <Identity>)

In my Identity component, I'm using a component from the UI library, checkbox, that incorporates this directive:

<checkbox
      :value="rememberMe"
      :label="$t('identity.rememberMeHeading')"
      name="rememberMe"
      data-test="remember-me"
      @input="toggleRememberMe()">
  <span slot="subtext"> {{ $t('identity.rememberMeSubheading') }}
    <a v-toggle:a-modal="'learn-more-modal'"
       @click.prevent="() => {}">{{ $t('identity.learnMore') }}</a>
  </span>
</checkbox>

How do I fix this error in my Identity.spec.js? After my imports, I have:

const localVue = createLocalVue()

localVue.use(Vuex)
localVue.use('toggle') 
like image 940
Kevin T. Avatar asked Jun 07 '19 19:06

Kevin T.


1 Answers

In @vue/test-utils 1.x, the second parameter of shallowMount and mount accepts a directives option that defines directives to use in the component. In 2.x, the option is global.directives. You could use this option to declare the v-toggle directive:

shallowMount(MyComponent, {
  // @vue/test-utils @1.x
  directives: {
    toggle() { /* stub */ }
  },

  // @vue/test-utils @2.x
  global: {
    directives: {
      toggle() { /* stub */ }
    }
  }
})

For example, to ensure the directive is used in a component:

const toggle = jest.fn()

shallowMount(MyComponent, {
  // @vue/test-utils @1.x
  directives: {
    toggle
  },

  // @vue/test-utils @2.x
  global: {
    directives: {
      toggle
    }
  }
})

expect(toggle).toHaveBeenCalled()
like image 100
tony19 Avatar answered Nov 15 '22 04:11

tony19