file-parser.test.js
2.53 KB
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
65
66
67
68
69
70
71
72
73
/**
* Unit Tests — file-parser.js
*/
import { describe, it, expect } from 'vitest';
import fs from 'fs';
import path from 'path';
const { parseFileContent } = require('../../services/file-parser');
describe('file-parser', () => {
const TMP = '/tmp/test-file-parser';
beforeAll(() => fs.mkdirSync(TMP, { recursive: true }));
afterAll(() => { try { fs.rmSync(TMP, { recursive: true }); } catch {} });
it('should parse a .txt file', async () => {
const f = path.join(TMP, 'hello.txt');
fs.writeFileSync(f, 'Hello World');
const result = await parseFileContent(f);
expect(result.text).toBe('Hello World');
expect(result.mimeType).toBe('text/plain');
expect(result.truncated).toBe(false);
});
it('should parse a .json file', async () => {
const f = path.join(TMP, 'data.json');
fs.writeFileSync(f, '{"key":"value"}');
const result = await parseFileContent(f);
expect(result.text).toContain('"key"');
expect(result.mimeType).toBe('application/json');
});
it('should parse a .md file', async () => {
const f = path.join(TMP, 'readme.md');
fs.writeFileSync(f, '# Title\nContent here');
const result = await parseFileContent(f);
expect(result.text).toContain('# Title');
expect(result.mimeType).toBe('text/markdown');
});
it('should truncate large files', async () => {
const f = path.join(TMP, 'large.txt');
fs.writeFileSync(f, 'x'.repeat(60000));
const result = await parseFileContent(f);
expect(result.truncated).toBe(true);
expect(result.text.length).toBeLessThan(60000);
});
it('should handle image files', async () => {
const f = path.join(TMP, 'photo.png');
fs.writeFileSync(f, Buffer.from([0x89, 0x50, 0x4e, 0x47])); // PNG header
const result = await parseFileContent(f);
expect(result.text).toContain('photo.png');
expect(result.mimeType).toBe('image/png');
expect(result.truncated).toBe(false);
});
it('should fallback for unknown extensions', async () => {
const f = path.join(TMP, 'data.xyz');
fs.writeFileSync(f, 'some text content');
const result = await parseFileContent(f);
expect(result.text).toContain('some text content');
expect(result.mimeType).toBe('application/octet-stream');
});
it('should handle binary file gracefully', async () => {
const f = path.join(TMP, 'binary.bin');
fs.writeFileSync(f, Buffer.from([0x00, 0x01, 0x02, 0xff]));
const result = await parseFileContent(f);
expect(result).toBeDefined();
expect(result.mimeType).toBe('application/octet-stream');
});
});