1
+ import Vue from 'vue'
2
+ import { mount } from '@vue/test-utils'
3
+ import CopyButton from '@/components/CopyButton.vue'
4
+ import { doesNotThrow } from 'assert' ;
5
+
6
+ const DOM_SOURCE_ID = 'el-test' ;
7
+ const DOM_SOURCE_VALUE = 'test clipboard value' ;
8
+
9
+ const slots = { default : 'Copy button' } ;
10
+ const propsData = { id : 'copy-button' , el : `#${ DOM_SOURCE_ID } ` }
11
+ const defaults = {
12
+ slots,
13
+ propsData,
14
+ attachToDocument : true ,
15
+ }
16
+
17
+ let wrapper
18
+
19
+ // mock dom source
20
+ function _mockDOMSource ( value ) {
21
+ // creates the span and append to JSDOM
22
+ const span = document . createElement ( 'span' )
23
+ span . setAttribute ( 'id' , DOM_SOURCE_ID ) ;
24
+ span . textContent = value ;
25
+ document . body . appendChild ( span )
26
+ }
27
+
28
+ // mock dom methods
29
+ function _mockDomMethodsForClipboardJS ( value ) {
30
+ window . getSelection = ( ) => ( {
31
+ addRange : ( ) => { } ,
32
+ removeAllRanges : ( ) => { } ,
33
+ toString : ( ) => value ,
34
+ } ) ;
35
+
36
+ document . execCommand = ( ) => value ;
37
+ document . createRange = ( ) => ( { selectNodeContents : ( ) => { } } ) ;
38
+ }
39
+
40
+ beforeEach ( ( ) => {
41
+ _mockDOMSource ( DOM_SOURCE_VALUE )
42
+ _mockDomMethodsForClipboardJS ( DOM_SOURCE_VALUE )
43
+ wrapper = mount ( CopyButton , defaults )
44
+ } )
45
+
46
+ afterEach ( ( ) => {
47
+ wrapper . destroy ( )
48
+ } )
49
+
50
+ describe ( 'CopyButton.vue' , ( ) => {
51
+ it ( 'should render the right content text' , ( ) => {
52
+ expect ( wrapper . text ( ) ) . toBe ( slots . default ) ;
53
+ } )
54
+
55
+ it ( 'should change the text when clicked to \'Copied!\' and 2 secs later swich back to the original text' , done => {
56
+ wrapper . trigger ( 'click' ) ;
57
+ expect ( wrapper . text ( ) ) . toBe ( 'Copied!' ) ;
58
+ setTimeout ( ( ) => {
59
+ expect ( wrapper . text ( ) ) . toBe ( slots . default ) ;
60
+ done ( ) ;
61
+ } , 2000 ) ;
62
+ } )
63
+
64
+ it ( 'should emit only the \'copied\' event with a valid value' , ( ) => {
65
+ wrapper . trigger ( 'click' ) ;
66
+
67
+ const emittedEvents = wrapper . emitted ( )
68
+ expect ( emittedEvents ) . toHaveProperty ( 'copied' ) ;
69
+ expect ( emittedEvents . copied ) . toBeTruthy ( ) ;
70
+ expect ( emittedEvents . copied . length ) . toBe ( 1 ) ;
71
+ expect ( emittedEvents . copied [ 0 ] . length ) . toBe ( 1 ) ;
72
+ expect ( emittedEvents . copied [ 0 ] [ 0 ] . content ) . toBe ( DOM_SOURCE_VALUE ) ;
73
+ expect ( emittedEvents . copyFailed ) . toBeFalsy ( ) ;
74
+ } )
75
+
76
+ it ( 'should emit only the \'copyFailed\' event' , ( ) => {
77
+ document . execCommand = ( ) => false // force error on clipboard.js
78
+ wrapper . trigger ( 'click' ) ;
79
+
80
+ const emittedEvents = wrapper . emitted ( )
81
+ expect ( emittedEvents ) . toHaveProperty ( 'copyFailed' ) ;
82
+ expect ( emittedEvents . copied ) . toBeFalsy ( ) ;
83
+ } )
84
+ } )
0 commit comments