刘光辉
10 小时以前 cf11e63b659afcc9792ab3e395f1b45d844431a8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { mount } from '@vue/test-utils';
import { nextTick } from 'vue';
 
import { afterEach, describe, expect, it, vi } from 'vitest';
 
import ImagePreview from './Functional.vue';
 
describe('functional image preview', () => {
  afterEach(() => {
    document.body.innerHTML = '';
    vi.restoreAllMocks();
  });
 
  it('closes on Escape and removes its keydown listener', async () => {
    const removeEventListener = vi.spyOn(window, 'removeEventListener');
    const underlyingKeydown = vi.fn();
    document.addEventListener('keydown', underlyingKeydown);
    const wrapper = mount(ImagePreview, {
      attachTo: document.body,
      props: {
        imageList: ['https://example.test/image.png'],
        show: true,
      },
    });
 
    expect(wrapper.find('.img-preview').exists()).toBe(true);
 
    document.body.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'Escape' }));
    await nextTick();
 
    expect(wrapper.find('.img-preview').exists()).toBe(false);
    expect(underlyingKeydown).not.toHaveBeenCalled();
    expect(removeEventListener).toHaveBeenCalledWith('keydown', expect.any(Function), true);
 
    document.removeEventListener('keydown', underlyingKeydown);
    wrapper.unmount();
  });
 
  it('ignores other keys', async () => {
    const wrapper = mount(ImagePreview, {
      attachTo: document.body,
      props: {
        imageList: ['https://example.test/image.png'],
        show: true,
      },
    });
 
    document.body.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));
    await nextTick();
 
    expect(wrapper.find('.img-preview').exists()).toBe(true);
 
    wrapper.unmount();
  });
});