-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathcfgStore.test.ts
79 lines (63 loc) · 2.71 KB
/
cfgStore.test.ts
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
74
75
76
77
78
79
import fs from 'node:fs/promises';
import path from 'node:path';
import ConfigStoreExport from 'configstore';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { defaultConfigFileName, GlobalConfigStore, legacyLocationDir } from './cfgStore.js';
const fsData = new Map<string, string>();
vi.mock('node:fs/promises', async (_importOriginal) => ({
// default: (await _importOriginal<{ default: object }>()).default,
default: {
readFile: vi.fn(async (filename) => fsData.get(filename)),
writeFile: vi.fn(async (filename, data) => fsData.set(filename, data)),
mkdir: vi.fn(async () => undefined),
},
}));
const sc = (m: string) => expect.stringContaining(m);
const oc = <T>(obj: T) => expect.objectContaining(obj);
describe('GlobalConfigStore', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
fsData.clear();
vi.restoreAllMocks();
});
test('GlobalConfigStore', () => {
expect(GlobalConfigStore.defaultLocation).toEqual(sc('cspell.json'));
});
test('legacyLocation', () => {
const configStoreLocation = new ConfigStoreExport('cspell').path;
const legacyLocation = path.join(legacyLocationDir || '', defaultConfigFileName);
expect(legacyLocation).toBe(configStoreLocation);
});
test('readConfigFile found', async () => {
fsData.set(GlobalConfigStore.defaultLocation, JSON.stringify({ imports: [] }));
const cfgStore = GlobalConfigStore.create();
const cfg = await cfgStore.readConfigFile();
expect(cfg).toEqual(oc({ filename: sc(defaultConfigFileName), config: { imports: [] } }));
});
test('readConfigFile not found', async () => {
const mockedFsReadFile = vi.mocked(fs.readFile);
mockedFsReadFile.mockImplementation(async () => {
throw new Error();
});
const cfgStore = GlobalConfigStore.create();
const cfg = await cfgStore.readConfigFile();
expect(cfg).toEqual(undefined);
});
test('writeConfigFile', async () => {
const mockedFsWriteFile = vi.mocked(fs.writeFile);
const mockedFsMkdir = vi.mocked(fs.mkdir);
const cfgStore = GlobalConfigStore.create();
const data = { name: 'cfg' };
await cfgStore.writeConfigFile(data);
expect(mockedFsMkdir).toHaveBeenCalled();
expect(mockedFsWriteFile).toHaveBeenCalledWith(
sc(defaultConfigFileName),
JSON.stringify(data, undefined, 2) + '\n',
);
const cfg = await cfgStore.readConfigFile();
expect(mockedFsMkdir).toHaveBeenCalled();
expect(cfg).toEqual(oc({ filename: cfgStore.location, config: data }));
});
});