-
-
Notifications
You must be signed in to change notification settings - Fork 602
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: add test for combine tools script #3136
base: master
Are you sure you want to change the base?
Conversation
✅ Deploy Preview for asyncapi-website ready!Built without sensitive environment variables
To edit notification comments on pull requests, go to your Netlify site configuration. |
⚡️ Lighthouse report for the changes in this PR:
Lighthouse ran on https://deploy-preview-3136--asyncapi-website.netlify.app/ |
@@ -106,7 +105,7 @@ const getFinalTool = async (toolObject) => { | |||
|
|||
// Combine the automated tools and manual tools list into single JSON object file, and | |||
// lists down all the language and technology tags in one JSON file. | |||
const combineTools = async (automatedTools, manualTools) => { | |||
const combineTools = async (automatedTools, manualTools, toolsPath, tagsPath) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what does tagspath
signify??
JSON.stringify({ languages: languageList, technologies: technologyList }), | ||
) | ||
fs.writeFileSync(toolsPath,JSON.stringify(finalTools)); | ||
fs.writeFileSync(tagsPath,JSON.stringify({ languages: languageList, technologies: technologyList }),) | ||
} | ||
|
||
module.exports = { combineTools } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fix this linter error
tests/tools/combine-tools.test.js
Outdated
const tagsData = readJSON(tagsPath); | ||
expect(tagsData.languages).toContainEqual(expect.objectContaining({ name: 'NewLanguage' })); | ||
}); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fix this one also
scripts/build-tools.js
Outdated
@@ -14,7 +14,7 @@ const buildTools = async () => { | |||
resolve(__dirname, '../config', 'tools-automated.json'), | |||
JSON.stringify(automatedTools, null, ' ') | |||
); | |||
await combineTools(automatedTools, manualTools); | |||
await combineTools(automatedTools, manualTools, resolve(__dirname, '../../config', 'tools.json'), resolve(__dirname, '../../config', 'all-tags.json')); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we do it in a more better way, instead of passing filePath here? Try to refactor tools scripts instead of manually passing filePaths for tags file.
}); | ||
|
||
it('should combine tools and create correct JSON files', async () => { | ||
await combineTools(automatedTools, manualTools, toolsPath, tagsPath); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
try to add this function call in a try/catch
block here to monitor if we are receiving any error or not.
}); | ||
|
||
|
||
it('should log validation errors to console.error', async () => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Errors shouldn't be validated via console messages. You should formally return a error using Promise.reject
.
scripts/build-tools.js
Outdated
@@ -6,15 +6,19 @@ const manualTools = require('../config/tools-manual.json') | |||
const fs = require('fs'); | |||
const { resolve } = require('path'); | |||
|
|||
let toolsPath = resolve(__dirname, '../../config', 'tools.json') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is using let
a good option here?
…ebsite into combineToolsTest
WalkthroughThe changes in this pull request involve modifications to several JavaScript files related to the handling and processing of tools. The Changes
Sequence Diagram(s)sequenceDiagram
participant A as User
participant B as buildTools
participant C as combineTools
A->>B: Call buildTools()
B->>C: Call combineTools(automatedTools, manualTools)
C->>C: Process tools
C->>C: Try-Catch for error handling
C-->>B: Return combined tools
B-->>A: Return result
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Outside diff range and nitpick comments (20)
tests/fixtures/tools/manual-tools.json (1)
1-12
: LGTM! Well-structured JSON for tool metadata.The JSON structure is well-formed and provides a clear representation of tool metadata. It includes essential information such as the tool's name, associated programming language, technology, and repository URL. This structure seems suitable for use as a test fixture for the combine tools script.
Consider the following suggestions for potential improvements:
- Add a "description" field to provide a brief overview of the tool's functionality.
- Include a "version" field to track the tool's current version.
- Consider adding a "categories" array to classify the tool's primary uses or features.
These additions could enhance the test fixture's comprehensiveness without overcomplicating the structure.
tests/fixtures/tools/automated-tools.json (5)
1-17
: Consider using a more descriptive category name.While the overall structure is valid, using "category1" as the category name might not be ideal, even for a test fixture. A more descriptive name would make the purpose of this fixture clearer and could better represent real-world scenarios.
Consider changing "category1" to a more meaningful name, such as "backendTools" or "pythonFrameworks", depending on the intended use of this fixture in tests.
{ - "category1": { + "backendTools": { "description": "Sample Category", "toolsList": [ { "title": "Tool B", "filters": { "language": "Python", "technology": ["Flask"] }, "links": { "repoUrl": "https://github.com/asyncapi/tool-b" } } ] } }
3-3
: Enhance the category description for clarity.The current description "Sample Category" is quite generic. Even for a test fixture, a more specific description could make the purpose of this category clearer and the fixture more self-documenting.
Consider updating the description to something more specific, like:
- "description": "Sample Category", + "description": "Tools for Python backend development",This change would provide more context about the type of tools included in this category.
5-14
: Improve tool naming and commend filter usage.The structure for representing tools is well-designed, particularly the use of filters for language and technology. However, the tool name "Tool B" is not descriptive.
The use of filters for language and technology is excellent, as it allows for easy categorization and searching of tools.
Consider using a more descriptive name for the tool, preferably one that reflects its purpose or functionality. For example:
- "title": "Tool B", + "title": "Flask AsyncAPI Generator",This change would make the fixture more realistic and potentially more useful in tests.
11-13
: Align repository URL with tool name.The repository URL follows the correct pattern for AsyncAPI GitHub repositories, which is good for consistency. However, the "tool-b" part of the URL doesn't align with typical repository naming conventions.
Consider updating the repository URL to match the tool name (once updated as suggested earlier). This would make the fixture more realistic:
"links": { - "repoUrl": "https://github.com/asyncapi/tool-b" + "repoUrl": "https://github.com/asyncapi/flask-asyncapi-generator" }This change assumes you've updated the tool name to "Flask AsyncAPI Generator" as suggested earlier. Aligning the repository name with the tool name increases the realism of this test fixture.
1-17
: Well-structured fixture with room for enhancement.Overall, this JSON file provides a good structure for representing categories of tools, which is valuable for testing purposes. The use of nested objects for categories and tools, along with specific fields like filters and links, allows for comprehensive testing scenarios.
The basic structure and schema of the JSON are well-designed and appropriate for a test fixture.
To further enhance this fixture:
- Consider adding more tools to the
toolsList
to test handling of multiple tools within a category.- You might want to create additional category objects to test scenarios with multiple categories.
- Think about including edge cases, such as tools with missing fields or empty arrays, to ensure robust handling in your tests.
These enhancements would make the fixture more comprehensive and useful for various testing scenarios, ensuring that your code can handle a wide range of potential data structures and content.
tests/fixtures/combineToolsData.js (9)
1-26
: LGTM! Consider using consistent color formats.The structure of
expectedDataT1
is well-organized and provides a clear representation of languages and technologies with their associated colors.For consistency, consider using the same color format for all entries. For example, 'Python' uses a 6-character hex code, while 'JavaScript' uses an 8-character hex code. Standardizing to either 6 or 8 characters would improve consistency.
28-52
: LGTM! Consider adding comments for test case clarity.The structures of
manualToolsWithMissingData
andmanualToolsToSort
are well-defined and represent different scenarios for manual tools.To improve clarity, consider adding brief comments above each constant explaining the specific test case it represents. This would make it easier for other developers to understand the purpose of each fixture.
54-68
: LGTM! Consider standardizing array usage in filters.The structures of
toolWithMultipleLanguages
andautomatedToolsT5
are well-defined and demonstrate support for multiple languages and technologies.For consistency, consider using arrays for all filter values, even when there's only one item. For example, change
technology: ['Node.js']
totechnology: ['Node.js']
intoolWithMultipleLanguages
. This would make the structure more uniform and easier to process.
70-82
: LGTM! Consider adding comments for invalid tool scenarios.The constants
invalidToolT4
,automatedToolsT4
, andmanualToolsT4
effectively represent different scenarios for invalid tools and empty tool lists.To improve clarity, consider adding brief comments explaining why each tool or list is considered invalid or empty. This would help other developers understand the purpose of these test cases more quickly.
84-114
: LGTM! Consider standardizing filter value types.The constants
toolWithNewTagsT6
,automatedToolsT6
,toolWithNewLanguageT7
, andautomatedToolsT7
effectively represent scenarios with new tags and languages.For consistency, consider standardizing the data types used in the
filters
object. For example, intoolWithNewTagsT6
,language
is a string whiletechnology
is an array. Keeping these consistent (preferably as arrays) across all tool definitions would improve uniformity and ease of processing.
138-158
: LGTM! Consider adding a comment about the missing repo URL.The constants
toolWithoutRepoUrlT9
,automatedToolsT9
, andmanualToolsT9
effectively represent scenarios with tools missing repository URLs.To improve clarity, consider adding a brief comment above
toolWithoutRepoUrlT9
explaining that this test case is specifically for tools without a repository URL. This would make the purpose of the test case immediately clear to other developers.
160-165
: LGTM! Consider clarifying the invalid aspect of the category.The constant
invalidAutomatedToolsT10
effectively represents a scenario with an invalid category in automated tools.To improve clarity, consider adding a comment explaining why this category is considered invalid. Is it the category name, the empty tool list, or something else? This would help other developers understand the specific aspect being tested.
167-177
: LGTM! Consider using a more realistic invalid URL.The constant
manualToolsWithInvalidURLT11
effectively represents a scenario with a tool having an invalid repository URL.To make the test case more robust, consider using a more realistic invalid URL, such as "http://invalid-url.com" instead of "invalid-url". This would better simulate real-world scenarios where URLs might be malformed but still look like URLs.
195-212
: LGTM! Consider organizing exports for better maintainability.The module exports are comprehensive, including all defined constants.
To improve maintainability, consider organizing the exports to match the order of definition in the file. This would make it easier to find and manage exports as the file grows. Additionally, you might want to group related constants together in the exports, such as keeping all "T4" related constants adjacent.
scripts/tools/combine-tools.js (2)
109-142
: Improved error handling with try-catch block.The addition of the try-catch block is a good practice for error handling. It will help catch and report any errors that occur during the execution of the
combineTools
function.However, we can further improve the code:
- Consider using the optional chaining operator on line 117:
- if (manualTools[key] && manualTools[key].toolsList.length) { + if (manualTools[key]?.toolsList?.length) {This change will make the code more concise and safer by avoiding potential "cannot read property 'toolsList' of undefined" errors.
- For better error reporting, you might want to include more context in the error message. For example:
throw new Error(`Error combining tools for key "${key}": ${err}`);This would provide more specific information about where the error occurred.
Would you like me to propose any additional error handling improvements or logging mechanisms?
🧰 Tools
🪛 Biome
[error] 117-117: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
108-108
: Improve function documentation for clarity.To address a previous comment about the significance of
tagsPath
, consider adding JSDoc comments to thecombineTools
function. This will provide clear documentation for all parameters, includingtagsPath
.Example:
/** * Combines automated and manual tools into a single JSON object file and lists all language and technology tags in another JSON file. * @param {Object} automatedTools - The automated tools object. * @param {Object} manualTools - The manual tools object. * @param {string} toolsPath - The file path where the combined tools JSON will be written. * @param {string} tagsPath - The file path where the language and technology tags JSON will be written. */ const combineTools = async (automatedTools, manualTools, toolsPath, tagsPath) => { // ... function body ... }This documentation will clarify the purpose of each parameter, including
tagsPath
, making the code more maintainable and easier to understand for other developers.tests/tools/combine-tools.test.js (3)
105-105
: Useconst
for variables that are not reassignedThe variable
consoleErrorMock
is not reassigned after its initial declaration. Usingconst
instead oflet
enhances code readability and indicates that the variable is immutable.Change the declaration to:
-let consoleErrorMock = jest.spyOn(console, 'error').mockImplementation(() => { }); +const consoleErrorMock = jest.spyOn(console, 'error').mockImplementation(() => { });
212-212
: Preferconst
overlet
for constantsThe variable
invalidPath
is not reassigned and can be declared withconst
for clarity.Modify the declaration:
-let invalidPath = "this/is/not/valid" +const invalidPath = "this/is/not/valid";
224-224
: Remove unused variableerror
after refactoringAfter refactoring to use
.rejects.toThrow()
, the variableerror
becomes unnecessary and can be removed.Remove the variable declaration:
-let error;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (6)
- scripts/build-tools.js (2 hunks)
- scripts/tools/combine-tools.js (1 hunks)
- tests/fixtures/combineToolsData.js (1 hunks)
- tests/fixtures/tools/automated-tools.json (1 hunks)
- tests/fixtures/tools/manual-tools.json (1 hunks)
- tests/tools/combine-tools.test.js (1 hunks)
🧰 Additional context used
🪛 Biome
scripts/tools/combine-tools.js
[error] 117-117: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
🔇 Additional comments (11)
tests/fixtures/tools/manual-tools.json (1)
1-12
: 🛠️ Refactor suggestionConsider expanding test fixtures for comprehensive coverage.
While this fixture provides a good starting point for testing the combine tools script, consider expanding it to include more diverse test cases. This would ensure more robust testing of the script's functionality.
Suggestions for additional test cases:
- Add a tool entry with multiple technologies.
- Include a tool with additional optional fields (e.g., "description", "version").
- Add an entry with missing optional fields to test the script's handling of incomplete data.
To ensure proper test coverage, let's check for the existence of related test files:
This will help verify if the test for the combine tools script exists and if it's using this fixture file appropriately.
✅ Verification successful
Test coverage appears to be comprehensive with multiple fixture files.
The presence of both
manual-tools.json
andautomated-tools.json
fixtures indicates that multiple test cases are already in place for the combine tools script. Therefore, expanding the test fixtures further may not be necessary.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for related test files and their content # Test 1: Check if there's a test file for the combine tools script echo "Checking for combine tools script test file:" fd -e js -e ts "combine.*tools.*test" tests # Test 2: If a test file exists, check its content for usage of this fixture echo "Checking test file content for fixture usage:" fd -e js -e ts "combine.*tools.*test" tests -x grep -n "manual-tools.json" {} || echo "No matching content found" # Test 3: Check for other fixture files in the same directory echo "Listing other fixture files in the same directory:" fd . tests/fixtures/tools -t fLength of output: 760
scripts/build-tools.js (4)
8-8
: LGTM: Improved code readabilityThe addition of this empty line enhances the readability of the code by clearly separating the function declaration from its body.
17-17
: LGTM: Improved code structureThe addition of this empty line enhances the readability of the code by clearly separating different operations within the function.
Regarding a past comment about refactoring:
As previously suggested by @akshatnema, consider refactoring the tools scripts to avoid manually passing filePaths for the tags file. This could potentially improve the overall design and maintainability of the code.
19-19
: LGTM: Improved code structureThe addition of this empty line enhances the readability of the code by clearly separating the main operations from the error handling block.
Regarding a past comment about variable declarations:
As previously noted by @sambhavgupta0705, consider reviewing the use of
let
for variable declarations. In this context, it might be beneficial to useconst
for variables that are not reassigned (likegithubExtractData
andautomatedTools
) to prevent accidental reassignment and improve code clarity.
Line range hint
1-37
: Verify PR objective: Test addition not found in this fileThe changes in this file are stylistic improvements that enhance code readability. However, the main objective of this PR, as stated in the description, is to "add test for combine tools script". This file doesn't contain any new tests.
Could you please clarify where the new test for the combine tools script has been added? If it's in a different file, please ensure it's included in the PR. If it's not yet implemented, consider adding the test to fulfill the PR objective.
To verify the existence of the test, you can run the following command:
This will search for test files and grep for lines containing "combine" followed by "tools", which should help locate the new test if it exists.
tests/fixtures/combineToolsData.js (3)
116-136
: LGTM! Well-structured test cases for valid tools and empty lists.The constants
validToolT8
,automatedToolsT8
, andmanualToolsT8
effectively represent scenarios with valid tools and empty automated tool lists. These test cases will be useful for testing the system's ability to handle valid tools and merge empty automated lists with manual lists.
179-193
: LGTM! Please clarify the purpose of the 'circular' test case.The constants
circularTool
andautomatedToolsT12
are well-structured and consistent with previous definitions.Could you please clarify the purpose of this test case? The name
circularTool
suggests it might be involved in a circular reference, but this isn't evident from the structure. Adding a comment explaining the specific scenario being tested would greatly improve understanding for other developers.
1-212
: Overall, well-structured and comprehensive test fixtures.This file provides a robust set of test fixtures for various scenarios in the combine tools functionality. The constants are consistently structured and cover a wide range of test cases, including valid tools, invalid tools, missing data, and edge cases.
To further improve the file:
- Consider adding brief comments explaining the purpose of each test case, especially for less obvious scenarios.
- Standardize the use of arrays in filter values across all tool definitions.
- Organize the module exports to match the order of definition in the file.
These minor improvements will enhance the clarity and maintainability of the test fixtures.
tests/tools/combine-tools.test.js (3)
87-92
: Add assertions to verify the handling of missing dataCurrently, the test only checks for the existence of
category1
. Consider adding more assertions to verify that tools with missing language or technology data are handled properly.For example:
expect(combinedTools).toHaveProperty('category1'); +expect(combinedTools.category1.toolsList).toHaveLength(expectedLength); +// Add assertions to check that tools with missing data are included or excluded as intended.
75-75
: Previous comment still applicable regarding error handling
103-103
: Previous comment still applicable about validating errors
it('should throw an error when URL parsing fails', async () => { | ||
let error; | ||
|
||
try { | ||
await combineTools(automatedTools, manualToolsWithInvalidURLT11, toolsPath, tagsPath); | ||
} catch (err) { | ||
error = err; | ||
expect(err.message).toContain('Invalid URL'); | ||
} | ||
expect(error).toBeDefined(); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use Jest's async error handling for clarity
Improve the test by using .rejects.toThrow()
to handle asynchronous errors more clearly and succinctly.
Apply the following change:
-it('should throw an error when URL parsing fails', async () => {
- let error;
-
- try {
- await combineTools(automatedTools, manualToolsWithInvalidURLT11, toolsPath, tagsPath);
- } catch (err) {
- error = err;
- expect(err.message).toContain('Invalid URL');
- }
- expect(error).toBeDefined();
+it('should throw an error when URL parsing fails', async () => {
+ await expect(combineTools(automatedTools, manualToolsWithInvalidURLT11, toolsPath, tagsPath))
+ .rejects.toThrow('Invalid URL');
+});
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it('should throw an error when URL parsing fails', async () => { | |
let error; | |
try { | |
await combineTools(automatedTools, manualToolsWithInvalidURLT11, toolsPath, tagsPath); | |
} catch (err) { | |
error = err; | |
expect(err.message).toContain('Invalid URL'); | |
} | |
expect(error).toBeDefined(); | |
}); | |
it('should throw an error when URL parsing fails', async () => { | |
await expect(combineTools(automatedTools, manualToolsWithInvalidURLT11, toolsPath, tagsPath)) | |
.rejects.toThrow('Invalid URL'); | |
}); |
it('should throw an error when there is an invalid category', async () => { | ||
let error; | ||
|
||
try { | ||
await combineTools(invalidAutomatedToolsT10, manualTools, toolsPath, tagsPath); | ||
} catch (err) { | ||
error = err; | ||
expect(err.message).toContain('Error combining tools'); | ||
} | ||
expect(error).toBeDefined(); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Simplify error assertions with .rejects.toThrow()
Refactor this test to leverage Jest's .rejects.toThrow()
for more straightforward error handling in asynchronous code.
Apply the following change:
-it('should throw an error when there is an invalid category', async () => {
- let error;
-
- try {
- await combineTools(invalidAutomatedToolsT10, manualTools, toolsPath, tagsPath);
- } catch (err) {
- error = err;
- expect(err.message).toContain('Error combining tools');
- }
- expect(error).toBeDefined();
+it('should throw an error when there is an invalid category', async () => {
+ await expect(combineTools(invalidAutomatedToolsT10, manualTools, toolsPath, tagsPath))
+ .rejects.toThrow('Error combining tools');
+});
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it('should throw an error when there is an invalid category', async () => { | |
let error; | |
try { | |
await combineTools(invalidAutomatedToolsT10, manualTools, toolsPath, tagsPath); | |
} catch (err) { | |
error = err; | |
expect(err.message).toContain('Error combining tools'); | |
} | |
expect(error).toBeDefined(); | |
}); | |
it('should throw an error when there is an invalid category', async () => { | |
await expect(combineTools(invalidAutomatedToolsT10, manualTools, toolsPath, tagsPath)) | |
.rejects.toThrow('Error combining tools'); | |
}); |
it('should throw an error when fs.writeFileSync fails', async () => { | ||
let error; | ||
let invalidPath = "this/is/not/valid" | ||
|
||
try { | ||
await combineTools(automatedTools, manualTools, invalidPath, invalidPath); | ||
} catch (err) { | ||
error = err; | ||
expect(err.message).toMatch(/ENOENT|EACCES/); | ||
} | ||
expect(error).toBeDefined(); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Refactor error handling using Jest's .rejects
Consider refactoring the test to use Jest's .rejects
for cleaner and more concise asynchronous error handling.
Apply the following change:
-it('should throw an error when fs.writeFileSync fails', async () => {
- let error;
- let invalidPath = "this/is/not/valid"
-
- try {
- await combineTools(automatedTools, manualTools, invalidPath, invalidPath);
- } catch (err) {
- error = err;
- expect(err.message).toMatch(/ENOENT|EACCES/);
- }
- expect(error).toBeDefined();
+it('should throw an error when fs.writeFileSync fails', async () => {
+ const invalidPath = "this/is/not/valid";
+ await expect(combineTools(automatedTools, manualTools, invalidPath, invalidPath))
+ .rejects.toThrow(/ENOENT|EACCES/);
+});
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it('should throw an error when fs.writeFileSync fails', async () => { | |
let error; | |
let invalidPath = "this/is/not/valid" | |
try { | |
await combineTools(automatedTools, manualTools, invalidPath, invalidPath); | |
} catch (err) { | |
error = err; | |
expect(err.message).toMatch(/ENOENT|EACCES/); | |
} | |
expect(error).toBeDefined(); | |
}); | |
it('should throw an error when fs.writeFileSync fails', async () => { | |
const invalidPath = "this/is/not/valid"; | |
await expect(combineTools(automatedTools, manualTools, invalidPath, invalidPath)) | |
.rejects.toThrow(/ENOENT|EACCES/); | |
}); |
it('should handle errors when processing tools with circular references', async () => { | ||
let error; | ||
circularTool.circular = circularTool; | ||
|
||
try { | ||
await combineTools(automatedToolsT12, {}, toolsPath, tagsPath); | ||
} catch (err) { | ||
error = err; | ||
expect(err.message).toContain('Converting circular structure to JSON'); | ||
} | ||
expect(error).toBeDefined(); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Refactor to use .rejects.toThrow()
for error handling
Streamline the test by utilizing Jest's .rejects.toThrow()
method for handling promises that are expected to reject.
Apply the following change:
-it('should handle errors when processing tools with circular references', async () => {
- let error;
- circularTool.circular = circularTool;
-
- try {
- await combineTools(automatedToolsT12, {}, toolsPath, tagsPath);
- } catch (err) {
- error = err;
- expect(err.message).toContain('Converting circular structure to JSON');
- }
- expect(error).toBeDefined();
+it('should handle errors when processing tools with circular references', async () => {
+ circularTool.circular = circularTool;
+ await expect(combineTools(automatedToolsT12, {}, toolsPath, tagsPath))
+ .rejects.toThrow('Converting circular structure to JSON');
+});
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it('should handle errors when processing tools with circular references', async () => { | |
let error; | |
circularTool.circular = circularTool; | |
try { | |
await combineTools(automatedToolsT12, {}, toolsPath, tagsPath); | |
} catch (err) { | |
error = err; | |
expect(err.message).toContain('Converting circular structure to JSON'); | |
} | |
expect(error).toBeDefined(); | |
}); | |
it('should handle errors when processing tools with circular references', async () => { | |
circularTool.circular = circularTool; | |
await expect(combineTools(automatedToolsT12, {}, toolsPath, tagsPath)) | |
.rejects.toThrow('Converting circular structure to JSON'); | |
}); |
This PR adds test for combine tools script.
Summary by CodeRabbit
New Features
Bug Fixes
combineTools
function to catch exceptions and log validation errors.Tests
combineTools
function to ensure reliability and correctness.