刘光辉
7 小时以前 0dfe84494048ce27ba8449831782128412d3eb13
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
56
57
58
59
60
61
62
63
64
/* @vitest-environment happy-dom */
 
import { describe, expect, it, vi } from 'vitest';
 
import { onlineUtils } from '#/utils/jnpf';
 
import { normalizeOfficeDocumentConfig, resolveFileName, validateOfficeDocumentConfig } from '../helpers/officeDocument';
 
vi.mock('#/router', () => ({ router: { push: vi.fn() } }));
vi.mock('#/api/request', () => ({ defHttp: { get: vi.fn() } }));
 
const FILE = { fileId: 'file_001', name: '检验报告.docx' };
 
describe('onlineUtils.openOfficeDocument', () => {
  it('emits OPEN_OFFICE_DOCUMENT with config', () => {
    const emitter = onlineUtils.getEmitter();
    const listener = vi.fn();
    emitter.on('OPEN_OFFICE_DOCUMENT', listener);
 
    const config = { file: FILE, mode: 'view' as const };
    onlineUtils.openOfficeDocument(config);
 
    expect(listener).toHaveBeenCalledWith(config);
    emitter.off('OPEN_OFFICE_DOCUMENT', listener);
  });
 
  it('does not emit when fileId is missing', () => {
    const emitter = onlineUtils.getEmitter();
    const listener = vi.fn();
    const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    emitter.on('OPEN_OFFICE_DOCUMENT', listener);
 
    onlineUtils.openOfficeDocument({ file: { name: '无 id.docx' } as any });
 
    expect(listener).not.toHaveBeenCalled();
    expect(errorSpy).toHaveBeenCalledWith('[onlineUtils.openOfficeDocument] file.fileId is required');
    emitter.off('OPEN_OFFICE_DOCUMENT', listener);
    errorSpy.mockRestore();
  });
});
 
describe('officeDocument helpers', () => {
  it('文件名缺失时从 url 兜底截取(后端靠扩展名定 documentType,丢了就打不开)', () => {
    expect(resolveFileName({ file: { fileId: 'f1', name: '' } } as any)).toBe('');
    expect(resolveFileName({ file: { fileId: 'f1', name: '', url: '/api/file/annex/a.docx?s=k' } } as any)).toBe('a.docx');
    expect(resolveFileName({ file: { fileId: 'f1', name: '', url: '/api/file/annex/noext' } } as any)).toBe('');
  });
 
  it('校验必填项', () => {
    expect(() => validateOfficeDocumentConfig({ file: { name: 'a.docx' } } as any)).toThrow('file.fileId is required');
    expect(() => validateOfficeDocumentConfig({ file: { fileId: 'f1', name: '' } } as any)).toThrow('file.name is required');
    expect(() => validateOfficeDocumentConfig({ file: FILE })).not.toThrow();
  });
 
  it('归一化:mode 默认 edit,标题默认取文件名', () => {
    expect(normalizeOfficeDocumentConfig({ file: FILE })).toMatchObject({ mode: 'edit', title: '检验报告.docx' });
    expect(normalizeOfficeDocumentConfig({ file: FILE, mode: 'view', title: ' 自定义 ' })).toMatchObject({
      mode: 'view',
      title: '自定义',
    });
    // 非法 mode 一律按 edit(最终以后端返回的模式为准,前端不做权限判断)
    expect(normalizeOfficeDocumentConfig({ file: FILE, mode: 'readonly' as any }).mode).toBe('edit');
  });
});