【问题标题】:how to mock navigator.clipboard.writeText in vue test utils如何在 vue 测试工具中模拟 navigator.clipboard.writeText
【发布时间】:2020-04-25 16:50:31
【问题描述】:

我正在尝试在nuxt中测试复制到剪贴板,但测试用例无法覆盖navigator.clipboard.writeText,如何测试导航器的东西,我也尝试过shallowMountmount 但都不起作用,

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

【问题讨论】:

  • 有时答案可能离你只有 2 英尺远... :-P

标签: vue.js jestjs nuxt.js vue-test-utils


【解决方案1】:
window.__defineGetter__('navigator', function() {
  return {
    clipboard: {
      writeText: jest.fn(x => x)
    }
  }
})

试试这个

【讨论】:

    【解决方案2】:

    此方法允许您测试readTextwriteText,并允许您的测试检查写入剪贴板的内容。这也适用于 TypeScript,而 window.__defineGetter__ 会抛出错误。

    let clipboardContents = "";
    
    Object.assign(navigator, {
        clipboard: {
            writeText: text => { clipboardContents = text; },
            readText: () => clipboardContents,
        },
    });
    

    如果您使用的是 jest,请使用正确的方法:

    let clipboardContents = "";
    
    Object.assign(navigator, {
        clipboard: {
            writeText: jest.fn(text => { clipboardContents = text; }),
            readText: jest.fn(() => clipboardContents),
        },
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-02
      • 2020-03-07
      • 2022-07-13
      • 2022-11-11
      • 1970-01-01
      • 2021-09-30
      • 2018-11-04
      • 2021-03-20
      相关资源
      最近更新 更多