forked from asyncapi/website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadAndWriteJson.test.js
75 lines (59 loc) · 2.25 KB
/
readAndWriteJson.test.js
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
const fs = require('fs/promises');
const { convertToJson } = require('../scripts/utils.ts');
const { writeJSON } = require('../scripts/utils/readAndWriteJson.ts');
const { yamlString, jsonObject } = require('./fixtures/utilsData');
jest.mock('fs/promises', () => ({
readFile: jest.fn(),
writeFile: jest.fn()
}));
jest.mock('../scripts/utils', () => ({
convertToJson: jest.fn()
}));
describe('writeJSON', () => {
const readPath = 'config/testInput.yaml';
const writePath = 'config/testOutput.json';
const error = new Error('Test error');
beforeEach(() => {
jest.clearAllMocks();
});
test('should read a file, convert it to JSON, and write the JSON to another file', async () => {
fs.readFile.mockResolvedValue(yamlString);
convertToJson.mockReturnValue(jsonObject);
await writeJSON(readPath, writePath);
expect(fs.readFile).toHaveBeenCalledWith(readPath, 'utf-8');
expect(convertToJson).toHaveBeenCalledWith(yamlString);
expect(fs.writeFile).toHaveBeenCalledWith(writePath, JSON.stringify(jsonObject));
});
test('should throw an error if reading the file fails', async () => {
fs.readFile.mockRejectedValue(error);
try {
await writeJSON(readPath, writePath);
} catch (err) {
expect(err.message).toBe(`Error while reading file\nError: ${error}`);
}
expect(fs.readFile).toHaveBeenCalledWith(readPath, 'utf-8');
});
test('should throw an error if converting the file content to JSON fails', async () => {
fs.readFile.mockResolvedValue(yamlString);
convertToJson.mockImplementation(() => {
throw error;
});
try {
await writeJSON(readPath, writePath);
} catch (err) {
expect(err.message).toBe(`Error while conversion\nError: ${error}`);
}
expect(convertToJson).toHaveBeenCalledWith(yamlString);
});
test('should throw an error if writing the file fails', async () => {
fs.readFile.mockResolvedValue(yamlString);
convertToJson.mockReturnValue(jsonObject);
fs.writeFile.mockRejectedValue(error);
try {
await writeJSON(readPath, writePath);
} catch (err) {
expect(err.message).toBe(`Error while writing file\nError: ${error}`);
}
expect(fs.writeFile).toHaveBeenCalledWith(writePath, JSON.stringify(jsonObject));
});
});