0

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');
  });
});
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Tapan Bavaliya
  • 135
  • 2
  • 12

2 Answers2

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

Try this

AdiechaHK
  • 456
  • 3
  • 13
1

This method allows you to test readText and writeText, as well as allowing your tests to check what was written to the clipboard. This will also work in TypeScript, whereas window.__defineGetter__ will throw an error.

let clipboardContents = "";

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

If you are using jest, use the correct methods:

let clipboardContents = "";

Object.assign(navigator, {
    clipboard: {
        writeText: jest.fn(text => { clipboardContents = text; }),
        readText: jest.fn(() => clipboardContents),
    },
});
MacroMan
  • 2,335
  • 1
  • 27
  • 36