how to mock navigator.clipboard.writeText in vue test utils

。_饼干妹妹 提交于 2020-06-29 04:08:10

问题


I'm trying to test copy to clipboard in nuxt, but test case can't cover navigator.clipboard.writeText, how to test navigator stuff, i also have tried shallowMount and mount but both not working,

<template>
  <span v-b-tooltip.hover class="url" title="Copy" data-test="copyUrl" @click="handleCopy(listing.url)">
    <i class="fa fa-copy" aria-hidden="true"/>
  </span>
</template>

<script>
export default {
  ............
  methods: {
    ..............
    handleCopy(url) {
      navigator.clipboard.writeText(url);
    }
    ...............
  }
  ........
};
</script>


// test case
import Vuex from 'vuex';
import { shallowMount, createLocalVue } from '@vue/test-utils';

// componenet
import Table from '@/components/Listings/Layouts/Table.vue';

const wrapper = shallowMount(Table, {
  attachToDocument: true,
});

describe('Table.vue', () => {
  it('check handleCopy', () => {
    wrapper.find('[data-test="copyUrl"]').trigger('click');
  });
});

回答1:


window.__defineGetter__('navigator', function() {
  return {
    clipboard: {
      writeText: jest.fn(x => x)
    }
  }
})

Try this



来源:https://stackoverflow.com/questions/59640985/how-to-mock-navigator-clipboard-writetext-in-vue-test-utils

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!