AgentSkillsCN

error-handling

调试并解决TypeScript、Jest测试、ESLint以及依赖项验证中常见的错误。

SKILL.md
--- frontmatter
name: error-handling
description: Debug and resolve common errors in TypeScript, Jest tests, ESLint, and dependency validation.

Error Handling

Use this skill when you encounter errors during development, testing, or build processes.

1. TypeScript Errors

Common Errors and Fixes

Error CodeMeaningFix
TS2307Cannot find moduleCheck path alias in tsconfig.json, verify file exists
TS2339Property does not existAdd property to interface, check for typos
TS2345Argument type mismatchCast with as, fix the type, or update interface
TS7006Implicit anyAdd explicit type annotation
TS2322Type not assignableCheck for null/undefined, use optional chaining

Debugging Workflow

  1. Run npm run type-check to see all errors.
  2. Focus on the first error (later errors are often cascading).
  3. Check if the error is in your code or a library type definition.

Example: Fixing TS2307

Error:

code
error TS2307: Cannot find module 'shared/types/blog' or its corresponding type declarations.

Diagnosis: Path alias not resolving.

Fix: Verify tsconfig.json has the alias:

json
"paths": {
  "shared/*": ["src/shared/*"]
}

2. Jest Test Failures

Project Test Configuration

This project uses a unified Jest entrypoint that runs both environments:

bash
# Run ALL tests (recommended)
npm test

# Run only UI tests
npm run test:ui

# Run only Server tests
npm run test:server

The unified config (jest.config.ts) delegates to:

  • jest.browser.ts → UI tests (src/ui/**/*.test.tsx) in jsdom environment
  • jest.node.ts → Server tests (src/server/**/*.test.ts, src/shared/**/*.test.ts) in Node environment

Common Patterns (Both Environments)

SymptomLikely CauseFix
"Cannot find module"Missing path alias or mockCheck moduleNameMapper in jest config
"TypeError: X is not a function"Mock not returning expected shapeVerify mock implementation
Timeout errorsAsync not awaitedAdd await or increase timeout

UI-Specific Issues (jest.browser.ts)

SymptomLikely CauseFix
"act() warning"State update after unmountWrap in await waitFor()
"SyntaxError: Cannot use import"ESM library not transpiledMock the module (see example below)
"document is not defined"Wrong test environmentEnsure file matches src/ui/**/*.test.tsx pattern

Server-Specific Issues (jest.node.ts)

SymptomLikely CauseFix
"Nest can't resolve dependencies"Missing provider in test moduleAdd provider or mock to Test.createTestingModule
"EntityMetadataNotFoundError"Entity not registeredAdd entity to TypeOrmModule.forRoot({ entities: [...] })
Database state leakingTests not isolatedUse :memory: SQLite and synchronize: true

Debugging Workflow

  1. Run the single failing test with verbose output:

    For UI tests:

    bash
    npx jest src/ui/path/to/test.test.tsx --config jest.browser.ts --verbose
    

    For Server tests:

    bash
    npx jest src/server/path/to/test.test.ts --config jest.node.ts --verbose
    
  2. Check if the mock is set up correctly.

  3. Verify beforeEach/afterEach cleanup.

Example: Fixing ESM Mock Issues (UI)

Error:

code
SyntaxError: Cannot use import statement outside a module

Diagnosis: ESM library not transpiled by Jest.

Fix: Add to jest config's transformIgnorePatterns or mock the module:

typescript
jest.mock('react-markdown', () => ({
  __esModule: true,
  default: ({ children }: { children: string }) => <div>{children}</div>,
}));

Example: Fixing "act()" Warnings (UI)

Error:

code
Warning: An update to Component inside a test was not wrapped in act(...)

Fix: Wrap assertions in waitFor:

typescript
await waitFor(() => {
  expect(screen.getByText('Loaded')).toBeInTheDocument();
});

Example: Fixing NestJS Dependency Resolution (Server)

Error:

code
Nest can't resolve dependencies of the BlogService (?). Please make sure that the argument "BlogPostRepository" at index [0] is available in the RootTestModule context.

Fix: Provide the repository in your test module:

typescript
const moduleRef = await Test.createTestingModule({
  imports: [
    TypeOrmModule.forRoot({
      type: 'better-sqlite3',
      database: ':memory:',
      entities: [BlogPost],
      synchronize: true,
    }),
    TypeOrmModule.forFeature([BlogPost]), // ← Register the repository
  ],
  providers: [BlogService],
}).compile();

Example: Fixing Database State Leaking (Server)

Problem: Tests pass individually but fail when run together.

Fix: Ensure each test uses a fresh in-memory database:

typescript
beforeAll(async () => {
  const moduleRef = await Test.createTestingModule({
    imports: [
      TypeOrmModule.forRoot({
        type: 'better-sqlite3',
        database: ':memory:', // ← Fresh DB per test suite
        synchronize: true,
        entities: [BlogPost],
      }),
      BlogModule,
    ],
  }).compile();

  app = moduleRef.createNestApplication();
  await app.init();
});

afterAll(async () => {
  await app.close(); // ← Always close to release resources
});

3. ESLint / Prettier Errors

Quick Fixes

bash
# Auto-fix all fixable issues
npm run format

# Check without fixing
npm run lint

Common ESLint Errors

RuleContextFix
@typescript-eslint/no-unused-varsBothRemove variable or prefix with _
@typescript-eslint/no-explicit-anyBothReplace any with proper type
prettier/prettierBothRun npm run format
react-hooks/exhaustive-depsUIAdd missing dependency to array
react-hooks/rules-of-hooksUIEnsure hooks are called at top level

Example: Fixing react-hooks/exhaustive-deps (UI)

Error:

code
React Hook useEffect has a missing dependency: 'fetchData'

Fix Options:

  1. Add the dependency (preferred):

    typescript
    useEffect(() => {
      fetchData();
    }, [fetchData]);
    
  2. Use useCallback to stabilize the function:

    typescript
    const fetchData = useCallback(() => {
      /* ... */
    }, []);
    useEffect(() => {
      fetchData();
    }, [fetchData]);
    

4. Dependency Cruiser Violations

Understanding Violations

Run the check:

bash
npm run depcruise:verify

Common Violations and Fixes

ViolationMeaningFix
not-to-serverUI importing from serverMove shared code to src/shared
not-to-uiServer importing from UIMove shared code to src/shared
no-circularCircular dependency detectedRefactor to break the cycle

Example: Fixing Cross-Boundary Import

Error:

code
error no-orphans: src/ui/containers/blog/hooks/useBlog.ts → src/server/modules/blog/blog.entity.ts

Fix: The UI should not import server entities. Create a shared type:

  1. Create src/shared/types/blog.ts:

    typescript
    export interface BlogPost {
      id: string;
      title: string;
      // ... shared fields
    }
    
  2. Update UI to import from shared:

    typescript
    import { BlogPost } from 'shared/types/blog';
    

5. Build Errors

NestJS Build Failures

bash
npm run build:server
ErrorFix
Decorator metadata errorsEnsure emitDecoratorMetadata: true in tsconfig
Circular dependency warningUse forwardRef() or restructure modules

Webpack Build Failures

bash
npm run build:ui
ErrorFix
Module not foundCheck webpack aliases match tsconfig paths
Asset size warningConsider code splitting or lazy loading

6. Runtime Errors

Server Errors (NestJS)

ErrorCauseFix
EADDRINUSEPort already in useKill process on port or change port
EntityNotFoundErrorDatabase record missingCheck ID, handle with try/catch
UnauthorizedExceptionJWT invalid/expiredCheck token, re-authenticate

Client Errors (React)

ErrorCauseFix
"Hydration mismatch"SSR/client content differsEnsure consistent rendering
"Maximum update depth"Infinite re-render loopCheck useEffect dependencies
"Cannot read property of undefined"Null referenceAdd optional chaining ?.

7. Escalation

If the error persists after following this guide:

  1. Search the error message in project issues.
  2. Check if the error is in a third-party library (update or file issue).
  3. Ask for help with the full error message and reproduction steps.