如何在vue测试工具中模拟navigator.clipboard.writeText [英] how to mock navigator.clipboard.writeText in vue test utils

查看:264
本文介绍了如何在vue测试工具中模拟navigator.clipboard.writeText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在nuxt中测试复制到剪贴板,但是测试用例无法覆盖navigator.clipboard.writeText,如何测试导航器内容,我也尝试过 shallowMount 安装,但都无法正常工作,

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

推荐答案

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

尝试一下

这篇关于如何在vue测试工具中模拟navigator.clipboard.writeText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆