Custom Jest matchers specifically designed for comparing generated code output with intelligent whitespace handling and detailed diff reporting.
Automatic Setup: These Jest extensions are automatically registered when you import @graphql-codegen/testing. No additional setup is required - the matchers become globally available in all test files.
Custom Jest matcher that normalizes whitespace and performs string comparisons while ignoring formatting differences. Essential for testing generated code where formatting may vary but content should match.
declare global {
namespace jest {
interface Matchers<R> {
/**
* Normalizes whitespace and performs string comparisons
* Ignores formatting differences while comparing content
* @param expected - The expected string to compare against
* @returns Jest matcher result
*/
toBeSimilarStringTo(expected: string): R;
}
}
}Functionality:
oneLine template tag from common-tagsstripIndent for better diff displayjest-diff for enhanced difference visualizationUsage Examples:
import { expect } from '@jest/globals';
// Basic usage - whitespace differences are ignored
expect(`
export interface User {
id: string;
name: string;
}
`).toBeSimilarStringTo(`export interface User { id: string; name: string; }`);
// Generated code comparison
const generatedCode = await plugin(schema, [], config);
expect(generatedCode.content).toBeSimilarStringTo(`
export type QueryResolvers = {
users?: Resolver<User[], {}, Context>;
};
`);
// Complex code structure comparison
expect(actualResolvers).toBeSimilarStringTo(`
export type Resolvers<ContextType = any> = {
Query?: QueryResolvers<ContextType>;
User?: UserResolvers<ContextType>;
};
`);Matcher Implementation Details:
The matcher extends Jest's expect functionality globally and is automatically available once the package is imported. It performs the following steps:
oneLine to flatten whitespace/\s\s+/gjest-diff with stripIndent for cleaner displayGlobal Registration: The matcher is registered via expect.extend() when the module is imported, making it available in all Jest test files without additional imports.
Error Handling:
When comparisons fail, the matcher provides:
jest-diff can generate meaningful comparisons