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

test(config): Add unit tests for config utilities; Update ESLint config to extend from eslint-config-yscope/jest for test files. #135

Merged
merged 13 commits into from
Jan 7, 2025

Conversation

junhaoliao
Copy link
Member

@junhaoliao junhaoliao commented Nov 28, 2024

Description

  1. Add unit tests for config utilities.
  2. Add dev dependency jest-environment-jsdom.
  3. Update test files ESLint config to extend from eslint-config-yscope/jest.
  4. Enforce 100% branches / functions / lines coverage on file src/utils/config.ts.
  5. Exclude coverage for unreachable lines / branches in file src/utils/config.ts.

Validation performed

  1. Ran all tests and ensured all test cases passed with no coverage threshold failure.

Summary by CodeRabbit

  • New Features

    • Added a new dependency for the Jest testing environment.
    • Introduced a new test suite for configuration utilities, covering various scenarios.
    • Exported a new variable, MAX_PAGE_SIZE, for configuration management.
    • Exported a new variable, UNMANAGED_THEME_THROWABLE, for error handling.
  • Bug Fixes

    • Enhanced error handling consistency for configuration management.
  • Documentation

    • Improved comments in the configuration utility functions for clarity.
  • Chores

    • Updated Jest configuration to include a new coverage threshold for a specific file.
    • Updated ESLint configuration to align with predefined settings.

Copy link

coderabbitai bot commented Nov 28, 2024

Warning

Rate limit exceeded

@junhaoliao has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 42 minutes and 9 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 3399b12 and 13b014a.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • test/utils/config.test.ts (1 hunks)

Walkthrough

This pull request introduces several changes across multiple files. The Jest configuration in jest.config.ts now includes a 100% coverage threshold for src/utils/config.ts. The package.json file has been updated to add a new dependency, jest-environment-jsdom, and the ESLint configuration has been modified to extend from yscope/jest. Additionally, the src/utils/config.ts file has been updated for improved error handling related to the THEME configuration key and now exports new variables, UNMANAGED_THEME_THROWABLE and MAX_PAGE_SIZE. A new test suite in test/utils/config.test.ts has been created to validate the configuration utilities.

Changes

File Change Summary
jest.config.ts Added a coverage threshold of 100% for branches, functions, and lines for src/utils/config.ts.
package.json Added dependency: "jest-environment-jsdom": "^29.7.0"; updated ESLint config to extend from yscope/jest.
src/utils/config.ts Improved error handling for THEME key in testConfig, setConfig, and getConfig; added variables UNMANAGED_THEME_THROWABLE and MAX_PAGE_SIZE.
test/utils/config.test.ts Introduced unit tests for testConfig, setConfig, and getConfig, covering various valid and invalid scenarios.

Possibly related PRs

Suggested reviewers

  • davemarco

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@junhaoliao junhaoliao requested a review from davemarco November 28, 2024 10:10
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (5)
src/utils/config.ts (2)

106-111: Consider removing unreachable code

Since testConfig throws an error for the THEME key, this case in the switch statement is unreachable. Consider removing it to improve code maintainability.

-        /* c8 ignore start */
-        case CONFIG_KEY.THEME:
-            // Unexpected execution path.
-            break;
-        /* c8 ignore end */
         /* c8 ignore next */
         default: break;

58-60: Consider extracting the error message to a constant

The error message "${key}" cannot be managed using these utilities is duplicated. Consider extracting it to a constant to maintain consistency and ease future updates.

+const UNMANAGEABLE_CONFIG_ERROR = (key: string) => 
+    `"${key}" cannot be managed using these utilities.`;

 // In testConfig
-            throw new Error(`"${key}" cannot be managed using these utilities.`);
+            throw new Error(UNMANAGEABLE_CONFIG_ERROR(key));

 // In getConfig
-            throw new Error(`"${key}" cannot be managed using these utilities.`);
+            throw new Error(UNMANAGEABLE_CONFIG_ERROR(key));

Also applies to: 149-151

test/utils/config.test.ts (3)

21-75: Consider centralizing error messages and test constants.

While the test constants are well-defined, consider moving error messages and validation constants to a shared constants file to maintain consistency across the codebase.

Consider creating a new file src/constants/errors.ts:

export const CONFIG_ERRORS = {
    EMPTY_TIMESTAMP_KEY: 'Timestamp key cannot be empty.',
    EMPTY_LOG_LEVEL_KEY: 'Log level key cannot be empty.',
    INVALID_PAGE_SIZE: (maxSize: number) => 
        `Page size must be greater than 0 and less than ${maxSize + 1}.`,
    UNMANAGED_THEME: (key: string) => 
        `"${key}" cannot be managed using these utilities.`
} as const;

76-104: Enhance type safety in the test helper function.

The helper function could benefit from more explicit type definitions and error handling.

Consider this improvement:

-const runNegativeCases = (func: (input: ConfigUpdate) => Nullable<string>) => {
+type TestFunction = (input: ConfigUpdate) => Nullable<string>;
+type TestCase = {
+    input: ConfigUpdate | ConfigUpdate[];
+    expected?: Nullable<string | string[]>;
+    throwable?: Error;
+};
+
+const runNegativeCases = (func: TestFunction) => {
+    const runSingleCase = (
+        testInput: ConfigUpdate,
+        expectedResult?: Nullable<string>
+    ) => {
+        const result = func(testInput);
+        expect(result).toBe(expectedResult);
+    };

105-242: Consider improving test descriptions for clarity.

While the test coverage is comprehensive, some test descriptions could be more specific about the scenarios they're testing.

Consider these improvements:

  • Line 108: "should return null for valid decoder options" -> "should validate decoder options with all required fields"
  • Line 180: "should log an error for invalid page size" -> "should log an error when page size is negative"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 82e677e and 25e245c.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • jest.config.ts (1 hunks)
  • package.json (2 hunks)
  • src/utils/config.ts (4 hunks)
  • test/utils/config.test.ts (1 hunks)
🔇 Additional comments (8)
jest.config.ts (2)

34-38: LGTM! Coverage threshold aligns with testing standards.

The addition of 100% coverage threshold for src/utils/config.ts maintains consistency with other utility files like math.ts.


34-38: Verify test coverage implementation.

Let's ensure the new coverage requirements are achievable and properly implemented.

✅ Verification successful

100% test coverage requirement is achievable and properly implemented

The test coverage requirements are reasonable and achievable based on the following evidence:

  1. The implementation in config.ts is well-structured with clear, distinct code paths
  2. The test file config.test.ts demonstrates comprehensive coverage:
    • Tests all config operations (get, set, test) for each config key
    • Includes negative test cases for invalid inputs
    • Verifies error conditions and edge cases
    • Tests default values and localStorage interactions
  3. The only excluded code paths are properly marked with /* c8 ignore */ comments for unreachable defensive code

The existing test suite adequately covers:

  • All branches in switch statements
  • Validation logic for all config types
  • Error handling scenarios
  • Default value fallbacks
  • Type conversions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of test file and its coverage

# Check if test file exists
echo "Checking for config test file..."
fd "config.test.ts" test/utils/

# Check test coverage implementation
echo "Checking test coverage implementation..."
rg -A 5 "describe|test|it" test/utils/config.test.ts

# Check for any uncovered code markers
echo "Checking for coverage exclusion markers..."
rg "istanbul ignore" src/utils/config.ts

Length of output: 5580


Script:

#!/bin/bash
# Let's check the actual implementation to verify coverage feasibility

# Check the implementation of config.ts
echo "Checking config.ts implementation..."
cat src/utils/config.ts

# Check for any complex logic or edge cases
echo "Checking for complex patterns..."
ast-grep --pattern 'function $FNAME($$$) { $$$ }' src/utils/config.ts

# Check for conditional statements that might affect coverage
echo "Checking conditional statements..."
rg "if|switch|try" src/utils/config.ts

Length of output: 6619

package.json (2)

58-58: LGTM: Jest environment dependency added correctly

The addition of jest-environment-jsdom at version ^29.7.0 aligns perfectly with your existing Jest version and is essential for testing React components in a simulated browser environment.


101-101: LGTM: ESLint configuration simplified

The ESLint configuration for test files has been streamlined by extending from yscope/jest, which is a more maintainable approach than managing environment settings directly.

src/utils/config.ts (3)

58-60: LGTM: Clear and consistent error handling for theme configuration

The error handling for the THEME key is well-implemented and follows the function's documented behaviour.


149-151: LGTM: Consistent error handling pattern

The error handling for the THEME key maintains consistency with the pattern established in testConfig.


177-177: LGTM: Appropriate export of validation constant

Exporting MAX_PAGE_SIZE is appropriate as it represents a validation boundary that consumers might need to reference.

test/utils/config.test.ts (1)

1-20: LGTM! Environment and imports are well-structured.

The test environment and imports are properly configured for testing browser-specific functionality.

Comment on lines 231 to 235
it("should retrieve page size once set", () => {
setConfig({key: CONFIG_KEY.PAGE_SIZE, value: VALID_PAGE_SIZE});
const result = getConfig(CONFIG_KEY.PAGE_SIZE);
expect(result).toBe(VALID_PAGE_SIZE);
});
Copy link

@coderabbitai coderabbitai bot Nov 28, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove duplicate test case.

This test case is a duplicate of the one at lines 219-223.

Remove this duplicate test case:

-    it("should retrieve page size once set", () => {
-        setConfig({key: CONFIG_KEY.PAGE_SIZE, value: VALID_PAGE_SIZE});
-        const result = getConfig(CONFIG_KEY.PAGE_SIZE);
-        expect(result).toBe(VALID_PAGE_SIZE);
-    });

Copy link
Contributor

Choose a reason for hiding this comment

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

I agree with rabbit on this one

Copy link

Choose a reason for hiding this comment

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

@davemarco, thank you for confirming.

Copy link
Member Author

Choose a reason for hiding this comment

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

good catch. fixed now

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@junhaoliao
Copy link
Member Author

discussed offline with @davemarco and he will review this later in the evening

Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

Sorry for delay. I've never used this framework before so just reading through docs. I posted some general questions

src/utils/config.ts Show resolved Hide resolved
/**
* Negative test cases for `testConfig` and `setConfig` function.
*/
const NEGATIVE_CONFIG_CASES: Record<string, {
Copy link
Contributor

@davemarco davemarco Dec 4, 2024

Choose a reason for hiding this comment

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

Why do this when we could just run them like positive cases?

Copy link
Member Author

Choose a reason for hiding this comment

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

That's an attempt to deduplicate the test code for testConfig and setConfig, since everything that fails testConfig would also fail setConfig

Copy link
Contributor

Choose a reason for hiding this comment

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

I see. I think the code is a bit hard to read. I suggest two options.

Option 1: Only run all the tests for testConfig() (and write them like normal jest tests), and then just have a single negative test for setConfig(). I think this will still get "100% coverage", but slightly less accurate since we are not testing all errors in setConfig().

Options 2: Try to refactor current code. There may be a cleaner approach something like below where all the tests are defined in a standard jest format, but I have not yet attempted myself.

const defineConfigTests = (func) => {
    it('test1', () => {
      expect(func(input1).toBe('number');
    });

    it('test2', () => {
      expect(func(input2)).toBeGreaterThan(0);
    });

    etc...
};

Copy link
Contributor

Choose a reason for hiding this comment

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

@junhaoliao This was my one annoying comment lol

Copy link
Member Author

Choose a reason for hiding this comment

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

Right, sorry for missing that.

Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

I took a deeper look

case CONFIG_KEY.PAGE_SIZE:
if (0 >= value || MAX_PAGE_SIZE < value) {
result = `Page size must be greater than 0 and less than ${MAX_PAGE_SIZE + 1}.`;
}
break;
case CONFIG_KEY.THEME:
Copy link
Contributor

Choose a reason for hiding this comment

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

Question why do we not just let user set the theme in local storage? Would this not be simpler? See suggestion in setConfig()

Copy link
Member Author

Choose a reason for hiding this comment

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

This was considered an impossible code path (i.e., calling testConfig or setConfig with CONFIG_KEY.THEME at any place would constitute an implementation error) because only JoyUI should have direct access on the theme config. We only created the theme-related types and localStorage keys to avoid type and key conflicts. With that said, i do see that we could be calling setConfig to set the theme once we implement the profile system, where we could be restoring theme name settings from a profile.
If you agree, we can implement CONFIG_KEY.THEME in the config utilities in preparation of the config profile system.

Copy link
Contributor

Choose a reason for hiding this comment

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

I don't fully understand the comment "only JoyUI should have direct access on the theme config".

Like if we allow the theme to be set using setConfig, all it will do is persist the "light"/"dark"/"system" setting across sessions. If this isn't intended behaviour for some reason, then I'm okay leaving it as is.

Copy link
Member Author

Choose a reason for hiding this comment

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

JoyUI has it own theme management system and they also store the config into localStorage so we do add an entry in our enums to avoid conflicts.

Right, we don't "allow the theme to be set using setConfig".

Copy link
Contributor

Choose a reason for hiding this comment

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

Ah i finally understand what you mean. All good

src/utils/config.ts Show resolved Hide resolved
src/utils/config.ts Show resolved Hide resolved
src/utils/config.ts Show resolved Hide resolved
src/utils/config.ts Show resolved Hide resolved
test/utils/config.test.ts Show resolved Hide resolved
/**
* Negative test cases for `testConfig` and `setConfig` function.
*/
const NEGATIVE_CONFIG_CASES: Record<string, {
Copy link
Contributor

Choose a reason for hiding this comment

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

I see. I think the code is a bit hard to read. I suggest two options.

Option 1: Only run all the tests for testConfig() (and write them like normal jest tests), and then just have a single negative test for setConfig(). I think this will still get "100% coverage", but slightly less accurate since we are not testing all errors in setConfig().

Options 2: Try to refactor current code. There may be a cleaner approach something like below where all the tests are defined in a standard jest format, but I have not yet attempted myself.

const defineConfigTests = (func) => {
    it('test1', () => {
      expect(func(input1).toBe('number');
    });

    it('test2', () => {
      expect(func(input2)).toBeGreaterThan(0);
    });

    etc...
};

test/utils/config.test.ts Outdated Show resolved Hide resolved
Comment on lines 231 to 235
it("should retrieve page size once set", () => {
setConfig({key: CONFIG_KEY.PAGE_SIZE, value: VALID_PAGE_SIZE});
const result = getConfig(CONFIG_KEY.PAGE_SIZE);
expect(result).toBe(VALID_PAGE_SIZE);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

I agree with rabbit on this one

case CONFIG_KEY.PAGE_SIZE:
window.localStorage.setItem(LOCAL_STORAGE_KEY.PAGE_SIZE, value.toString());
break;
/* c8 ignore start */
case CONFIG_KEY.THEME:
// Unexpected execution path.
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
// Unexpected execution path.
window.localStorage.setItem(LOCAL_STORAGE_KEY.THEME, value.toString());

Copy link
Contributor

Choose a reason for hiding this comment

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

Why dont we save the theme selection to local storage?

Copy link
Member Author

Choose a reason for hiding this comment

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

Discussed at https://github.com/y-scope/yscope-log-viewer/pull/135/files#r1876734225 : we allocate the types and enums for theme config only to avoid name conflicts and we expected only JoyUI to read / write into localStorage, which might subject to change in the future.

Copy link
Contributor

Choose a reason for hiding this comment

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

@junhaoliao junhaoliao requested review from davemarco and removed request for davemarco December 22, 2024 13:43
Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

Next round of review

expect(() => setConfig({
key: CONFIG_KEY.THEME,
value: THEME_NAME.SYSTEM,
})).toThrow(`"${CONFIG_KEY.THEME}" cannot be managed using these utilities.`);
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
})).toThrow(`"${CONFIG_KEY.THEME}" cannot be managed using these utilities.`);
})).toThrow(UNMANAGED_THEME_THROWABLE);

Comment on lines 203 to 205
expect(() => getConfig(CONFIG_KEY.THEME)).toThrow(
`"${CONFIG_KEY.THEME}" cannot be managed using these utilities.`
);
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
expect(() => getConfig(CONFIG_KEY.THEME)).toThrow(
`"${CONFIG_KEY.THEME}" cannot be managed using these utilities.`
);
expect(() => getConfig(CONFIG_KEY.THEME)).toThrow(UNMANAGED_THEME_THROWABLE);

Copy link
Contributor

Choose a reason for hiding this comment

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

I think you updated all the dependencies in this PR. I think you should just install "jest-environment-jsdom" for this PR. Is it possible to revert the package-lock.json, and then just install jest-environment-jsdom?

Copy link
Member Author

Choose a reason for hiding this comment

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

Here's how I added the dependency:

  1. Add the entry in package.json.
  2. Remove node_modules and package-lock.json.
  3. nvm use 22 to make sure i'm using the latest version of npm.
  4. npm i.

Since the file is auto-generated, I think it's fine to leave it as-is. It might not be an issue after we merge #159

Copy link
Contributor

Choose a reason for hiding this comment

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

I still think its better practice not to update all the dependencies in all PRs. Like we shouldnt remove the package-lock.json. The updates might break something unrelated to the PR, it is also harder for the reviewer to check the dependency changes. Anyways here is a script that should revert the updates and install jest-environment-jsdom.

git checkout 969ff35b2387bc -- package-lock.json
git checkout 969ff35b2387bc -- package.json
npm ci
npm i -D jest-environment-jsdom

case CONFIG_KEY.PAGE_SIZE:
if (0 >= value || MAX_PAGE_SIZE < value) {
result = `Page size must be greater than 0 and less than ${MAX_PAGE_SIZE + 1}.`;
}
break;
case CONFIG_KEY.THEME:
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't fully understand the comment "only JoyUI should have direct access on the theme config".

Like if we allow the theme to be set using setConfig, all it will do is persist the "light"/"dark"/"system" setting across sessions. If this isn't intended behaviour for some reason, then I'm okay leaving it as is.

src/utils/config.ts Show resolved Hide resolved
Comment on lines +48 to +63
const cases = (
Object.keys(VALID_DECODER_OPTIONS) as Array<keyof DecoderOptions>
).map((key) => ({
decoderOptions: {
key: CONFIG_KEY.DECODER_OPTIONS,
value: {
...VALID_DECODER_OPTIONS,
[key]: "",
},
} as ConfigUpdate,
expected: {
formatString: null,
logLevelKey: "Log level key cannot be empty.",
timestampKey: "Timestamp key cannot be empty.",
}[key],
}));
Copy link
Contributor

Choose a reason for hiding this comment

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

Should we wrap this code in another function like createNegativeCasesForDecoderOptions() with a description so more clear what this does?

Copy link
Member Author

@junhaoliao junhaoliao Jan 7, 2025

Choose a reason for hiding this comment

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

Good point. Since that piece of logic is not re-usable (at the moment) and not worth testable, would an inline comment suffice?

Copy link
Contributor

@davemarco davemarco Jan 7, 2025

Choose a reason for hiding this comment

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

Okay an inline comment is fine

value: -1,
});

expect(result).toBe("Page size must be greater than 0 and less than 1000001.");
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
expect(result).toBe("Page size must be greater than 0 and less than 1000001.");
expect(result).toBe(`Page size must be greater than 0 and less than ${MAX_PAGE_SIZE + 1}.`);

src/utils/config.ts Show resolved Hide resolved
@@ -168,6 +174,7 @@ export {
CONFIG_DEFAULT,
EXPORT_LOGS_CHUNK_SIZE,
getConfig,
MAX_PAGE_SIZE,
Copy link
Contributor

Choose a reason for hiding this comment

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

This currently isn't used, but will be used if you address my later comment. This is just a marker for me to remember in case you disagree with later comment. So ignore

CONFIG_DEFAULT,
getConfig,
setConfig,
testConfig,
Copy link
Contributor

Choose a reason for hiding this comment

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

Required for my later comment.

Suggested change
testConfig,
testConfig,
MAX_PAGE_SIZE,

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/utils/config.ts (1)

64-66: Consider using false == for boolean comparisons

According to coding guidelines, prefer false == <expression> over !<expression>.

-        case CONFIG_KEY.THEME:
-            throw UNMANAGED_THEME_THROWABLE;
+        case CONFIG_KEY.THEME: {
+            throw UNMANAGED_THEME_THROWABLE;
+        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 90c664e and 193f199.

📒 Files selected for processing (2)
  • src/utils/config.ts (5 hunks)
  • test/utils/config.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/utils/config.test.ts
🧰 Additional context used
📓 Path-based instructions (1)
src/utils/config.ts (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

🔇 Additional comments (4)
src/utils/config.ts (4)

17-21: LGTM! Well-structured error handling for theme configuration

The introduction of UNMANAGED_THEME_THROWABLE improves error handling consistency and aligns with the design decision to delegate theme management to JoyUI.


112-117: LGTM! Appropriate handling of unreachable theme code

The coverage ignore comments for the theme case were discussed and approved in previous reviews.


155-157: LGTM! Consistent theme error handling

The error handling for theme configuration is consistent with testConfig.


183-183: LGTM! Appropriate exports added

The addition of MAX_PAGE_SIZE and UNMANAGED_THEME_THROWABLE to exports is well-justified for validation and testing purposes.

Also applies to: 187-187

Copy link
Member Author

@junhaoliao junhaoliao left a comment

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
test/utils/config.test.ts (1)

44-59: Add inline comment to explain decoder options test cases.

Based on past review discussions, an inline comment would help clarify the purpose of this code block.

Add a comment before line 44:

+    // Generate test cases for each decoder option field, ensuring empty values are properly validated
     const cases = (
         Object.keys(VALID_DECODER_OPTIONS) as Array<keyof DecoderOptions>
     ).map((key) => ({
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3585803 and 717f539.

📒 Files selected for processing (1)
  • test/utils/config.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
test/utils/config.test.ts (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

🪛 GitHub Check: lint-check
test/utils/config.test.ts

[failure] 38-38:
This line has a comment length of 157. Maximum allowed is 100

🪛 GitHub Actions: lint
test/utils/config.test.ts

[warning] 38-38: This line has a comment length of 157. Maximum allowed is 100

🔇 Additional comments (2)
test/utils/config.test.ts (2)

1-21: LGTM! Well-organized imports and environment setup.

The file is properly configured with jsdom environment and includes all necessary imports.


94-207: LGTM! Comprehensive test coverage.

The test suites are well-structured and cover all necessary cases:

  • Positive and negative test cases for all config types
  • Proper cleanup between tests using beforeEach
  • Thorough validation of localStorage interactions
  • Proper error handling verification

const VALID_PAGE_SIZE = 5000;

/**
* Runs a set of negative config test cases using the given function. Prevents duplication of negative test cases for `setConfig` and `testConfig` functions.
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix comment length to comply with linting rules.

The comment exceeds the maximum allowed length of 100 characters.

Split the comment into multiple lines:

-/** Runs a set of negative config test cases using the given function. Prevents duplication of negative test cases for `setConfig` and `testConfig` functions.
+/**
+ * Runs a set of negative config test cases using the given function. Prevents duplication
+ * of negative test cases for `setConfig` and `testConfig` functions.
  */
📝 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.

Suggested change
* Runs a set of negative config test cases using the given function. Prevents duplication of negative test cases for `setConfig` and `testConfig` functions.
/**
* Runs a set of negative config test cases using the given function. Prevents duplication
* of negative test cases for `setConfig` and `testConfig` functions.
*/
🧰 Tools
🪛 GitHub Check: lint-check

[failure] 38-38:
This line has a comment length of 157. Maximum allowed is 100

🪛 GitHub Actions: lint

[warning] 38-38: This line has a comment length of 157. Maximum allowed is 100

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
test/utils/config.test.ts (2)

45-60: Add inline documentation for test case generation logic.

The test case generation logic would benefit from an explanatory comment.

Add a comment before line 45:

+        // Generate test cases by mapping each decoder option key to a test case with an empty value
+        // and its expected error message
         const cases = (

81-92: Consider extracting error message as a constant.

The error message for invalid page size is duplicated across test cases. Consider extracting it to a constant to maintain consistency and ease future updates.

Add at the top of the file with other constants:

+/**
+ * Error message for invalid page size validation.
+ */
+const INVALID_PAGE_SIZE_ERROR = (maxSize: number) =>
+    `Page size must be greater than 0 and less than ${maxSize + 1}.`;

 const VALID_DECODER_OPTIONS: DecoderOptions = {

Then update the test:

-        expect(result).toBe(`Page size must be greater than 0 and less than ${MAX_PAGE_SIZE + 1}.`);
+        expect(result).toBe(INVALID_PAGE_SIZE_ERROR(MAX_PAGE_SIZE));
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 717f539 and 3399b12.

📒 Files selected for processing (1)
  • test/utils/config.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
test/utils/config.test.ts (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

🪛 GitHub Check: lint-check
test/utils/config.test.ts

[failure] 38-38:
This line has a comment length of 157. Maximum allowed is 100

🪛 GitHub Actions: lint
test/utils/config.test.ts

[warning] 38-38: This line has a comment length of 157. Maximum allowed is 100

🔇 Additional comments (3)
test/utils/config.test.ts (3)

1-21: LGTM! Well-organized imports and environment setup.

The imports are logically grouped, and the jsdom environment is correctly specified.


1-208: Great test coverage and organization!

The test file is well-structured with comprehensive coverage of configuration utilities. The use of helper functions and constants makes the tests maintainable and readable.

🧰 Tools
🪛 GitHub Check: lint-check

[failure] 38-38:
This line has a comment length of 157. Maximum allowed is 100

🪛 GitHub Actions: lint

[warning] 38-38: This line has a comment length of 157. Maximum allowed is 100


38-38: ⚠️ Potential issue

Split the comment into multiple lines to comply with length limit.

The comment exceeds the maximum length of 100 characters.

Apply this diff:

-/** Runs a set of negative config test cases using the given function. Prevents duplication of negative test cases for `setConfig` and `testConfig` functions.
+/**
+ * Runs a set of negative config test cases using the given function. Prevents duplication
+ * of negative test cases for `setConfig` and `testConfig` functions.
+ */

Likely invalid or redundant comment.

🧰 Tools
🪛 GitHub Check: lint-check

[failure] 38-38:
This line has a comment length of 157. Maximum allowed is 100

🪛 GitHub Actions: lint

[warning] 38-38: This line has a comment length of 157. Maximum allowed is 100

@davemarco
Copy link
Contributor

Confirmed test cases still run sucessfully after changes.

@davemarco
Copy link
Contributor

davemarco commented Jan 7, 2025

for title

test(config): Add unit tests for config utilities; Update ESLint config to extend from eslint-config-yscope/jest for test files.

@junhaoliao junhaoliao changed the title test(config): Add unit tests for config utilities; Update test files ESLint config to extend from eslint-config-yscope/jest. test(config): Add unit tests for config utilities; Update ESLint config to extend from eslint-config-yscope/jest for test files. Jan 7, 2025
@junhaoliao junhaoliao merged commit f74bacf into y-scope:main Jan 7, 2025
3 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants