Implement Jest Matchers for Color Palette Validation
This challenge focuses on creating custom Jest matchers in TypeScript to validate color palettes. This is a common task in front-end development for ensuring consistency in design systems and preventing design regressions. You will implement matchers that verify the structure, format, and uniqueness of color values within a given palette.
Problem Description
Your task is to create a set of custom Jest matchers for TypeScript that can be used to assert properties of color palettes. A color palette is typically represented as an object where keys are color names (e.g., "primary", "secondary") and values are color codes (e.g., hex codes, RGB strings).
You need to implement two custom matchers:
toHaveValidColorStructure: This matcher should check if the provided object has a structure that represents a valid color palette. This means it should be an object, and all its values must be strings.toHaveUniqueColorValues: This matcher should check if all the color values within the palette object are unique. No two keys should map to the same color code.
You will also need to register these matchers with Jest.
Examples
Example 1: toHaveValidColorStructure
Input (Palette Object):
{
"primary": "#3498db",
"secondary": "rgb(255, 0, 0)",
"accent": "#2ecc71"
}
Jest Assertion:
expect(colorPalette).toHaveValidColorStructure();
Expected Output: pass: true
Example 2: toHaveValidColorStructure (Invalid Structure)
Input (Palette Object):
{
"primary": "#3498db",
"secondary": 12345, // Invalid value type
"accent": "#2ecc71"
}
Jest Assertion:
expect(colorPalette).toHaveValidColorStructure();
Expected Output: pass: false, with a message indicating an invalid value type.
Example 3: toHaveUniqueColorValues
Input (Palette Object):
{
"primary": "#3498db",
"secondary": "rgb(255, 0, 0)",
"accent": "#2ecc71"
}
Jest Assertion:
expect(colorPalette).toHaveUniqueColorValues();
Expected Output: pass: true
Example 4: toHaveUniqueColorValues (Duplicate Values)
Input (Palette Object):
{
"primary": "#3498db",
"secondary": "rgb(255, 0, 0)",
"tertiary": "#3498db" // Duplicate of "primary"
}
Jest Assertion:
expect(colorPalette).toHaveUniqueColorValues();
Expected Output: pass: false, with a message indicating duplicate color values.
Constraints
- The input to the matchers will always be a JavaScript object.
- The keys of the object will always be strings.
- The values can be strings or other primitive types, which need to be validated.
- Performance is not a critical concern for this challenge, but the implementation should be reasonably efficient.
Notes
- You will need to extend Jest's
Matchersinterface to include your custom matchers. - Refer to the Jest documentation on "Adding Custom Matchers" for guidance on implementation and registration.
- For
toHaveValidColorStructure, consider how you would handle non-string values robustly. - For
toHaveUniqueColorValues, you'll need a way to efficiently check for duplicate string values.