Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: write tests and refactor scripts #3012

Merged
merged 20 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ cypress/screenshots
cypress/videos
/config/finance/json-data/*
*.mdx
coverage
6 changes: 6 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
verbose: true, // display individual test results with the test suite hierarchy
collectCoverage: true, // collect test coverage information\
collectCoverageFrom: ['scripts/**/*.js']
};

7,329 changes: 5,539 additions & 1,790 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"private": true,
"scripts": {
"dev": "npm run build-scripts && next -p 3000",
"test":"jest",
"build": "npm run build-scripts && next build",
"build:pages": "node scripts/build-pages.js && npm run format:mdx",
"build:posts": "node scripts/index.js",
Expand Down Expand Up @@ -131,6 +132,7 @@
"eslint-plugin-tailwindcss": "^3.14.2",
"eslint-plugin-unused-imports": "^3.1.0",
"inquirer": "^9.2.14",
"jest": "^29.7.0",
"postcss-import": "^16.0.1",
"remark-cli": "^12.0.1",
"remark-lint": "^10.0.0",
Expand Down
16 changes: 2 additions & 14 deletions scripts/adopters/index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
const { promises: { readFile, writeFile } } = require('fs');
const { convertToJson } = require('../utils');
const { resolve } = require('path');
const writeJSON = require('../utils/readAndWriteJson.js')

module.exports = async function buildAdoptersList() {
try {
const AdoptersContent = await readFile('config/adopters.yml', 'utf-8');
const jsonContent = convertToJson(AdoptersContent);

await writeFile(
resolve(__dirname, '../../config', 'adopters.json'),
JSON.stringify(jsonContent)
);
} catch (err) {
console.error(err);
throw err;
}
writeJSON('config/adopters.yml',resolve(__dirname, '../../config', 'adopters.json'));
};
23 changes: 8 additions & 15 deletions scripts/finance/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { promises: { readFile, writeFile, mkdir } } = require('fs');
const { convertToJson } = require('../utils');
const { resolve, dirname } = require('path');
const { promises: { mkdir } } = require('fs');
const { resolve } = require('path');
const writeJSON = require('../utils/readAndWriteJson.js')

module.exports = async function buildFinanceInfoList() {
try {
Expand All @@ -9,25 +9,18 @@ module.exports = async function buildFinanceInfoList() {
const expensesPath = resolve(currentDir, 'config', 'finance', '2024', 'Expenses.yml');
const expensesLinkPath = resolve(currentDir, 'config', 'finance', '2024', 'ExpensesLink.yml');

const ExpensesContent = await readFile(expensesPath, 'utf-8');
const ExpensesLinkContent = await readFile(expensesLinkPath, 'utf-8');

const Expenses = convertToJson(ExpensesContent);
const ExpensesLink = convertToJson(ExpensesLinkContent);

// Ensure the directory exists before writing the files
const jsonDirectory = resolve(currentDir, 'config', 'finance', 'json-data', '2024');
await mkdir(jsonDirectory, { recursive: true });

// Write Expenses to a JSON files
// Write Expenses and ExpensesLink to JSON files
const expensesJsonPath = resolve(jsonDirectory, 'Expenses.json');
await writeFile(expensesJsonPath, JSON.stringify(Expenses, null, 2));
await writeJSON(expensesPath, expensesJsonPath);

const expensesLinkJsonPath = resolve(jsonDirectory, 'ExpensesLink.json');
await writeFile(expensesLinkJsonPath, JSON.stringify(ExpensesLink, null, 2));
await writeJSON(expensesLinkPath, expensesLinkJsonPath);

} catch (err) {
console.error(err);
throw err;
throw new Error(err);
}
};
};
5 changes: 2 additions & 3 deletions scripts/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@ function convertToJson(contentYAMLorJSON) {
const yamlContent = yaml.parse(contentYAMLorJSON);
return yamlContent;
} catch (yamlError) {
// If parsing as YAML also fails, return null or handle the error as needed
console.error('Error parsing content as JSON or YAML:', jsonError.message, yamlError.message);
return null;
// If parsing as YAML also fails, throw an error
throw new Error(`Invalid content format:\nJSON Parse Error: ${jsonError}\nYAML Parse Error: ${yamlError}`);
}
}
}
Expand Down
28 changes: 28 additions & 0 deletions scripts/utils/readAndWriteJson.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const { promises: { readFile, writeFile } } = require('fs');
const { convertToJson } = require("../utils");

module.exports = async function writeJSON(readPath, writePath) {
let readContent;
let jsonContent;

// Attempt to read the file
try {
readContent = await readFile(readPath, 'utf-8');
} catch (err) {
throw new Error(`Error while reading file\nError: ${err}`);
}

// Attempt to convert content to JSON
try {
jsonContent = convertToJson(readContent);
} catch (err) {
throw new Error(`Error while conversion\nError: ${err}`);
}

// Attempt to write the JSON content to file
try {
await writeFile(writePath, JSON.stringify(jsonContent));
} catch (err) {
throw new Error(`Error while writing file\nError: ${err}`);
}
};
18 changes: 18 additions & 0 deletions tests/adopters/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { resolve } = require('path');
const writeJSON = require('../../scripts/utils/readAndWriteJson.js');
const buildAdoptersList = require('../../scripts/adopters/index');

jest.mock('../../scripts/utils/readAndWriteJson.js');

describe('buildAdoptersList', () => {

test('should call writeJSON with correct arguments', async () => {
const expectedReadPath = 'config/adopters.yml';
const expectedWritePath = resolve(__dirname, '../../config', 'adopters.json');

await buildAdoptersList();

expect(writeJSON).toHaveBeenCalledWith(expectedReadPath, expectedWritePath);
});

});
7 changes: 7 additions & 0 deletions tests/fixtures/utilsData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
jsonString: '{"name": "AsyncAPI", "age": 5}',
yamlString: 'name: AsyncAPI\nage: 5',
jsonObject: { name: "AsyncAPI", age: 5 },
invalidString: 'name: AsyncAPI, age: five'
};

78 changes: 78 additions & 0 deletions tests/readAndWriteJson.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
const { promises: fs } = require('fs');
const { convertToJson } = require('../scripts/utils');
const writeJSON = require("../scripts/utils/readAndWriteJson");
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));
});

});
25 changes: 25 additions & 0 deletions tests/utils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const { convertToJson } = require("../scripts/utils");
const { jsonString, yamlString, jsonObject, invalidString } = require("./fixtures/utilsData")

describe('convertToJson', () => {
test('should return JSON object if input is valid JSON string', () => {
expect(convertToJson(jsonString)).toEqual(jsonObject);
});

test('should return JavaScript object if input is valid YAML string', () => {
expect(convertToJson(yamlString)).toEqual(jsonObject);
});

test('should return input if input is already an object', () => {
expect(convertToJson(jsonObject)).toBe(jsonObject);
});

test('should throw an error if input is invalid JSON and invalid YAML', () => {
try {
convertToJson(invalidString);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also check that there shouldn't be any value returned from the function.

expect(convertToJson(invalidString)).toBeUndefined();
} catch (error) {
expect(error.message.includes("Invalid content format")).toBeTruthy();
}
});
});
Loading