Skip to main content

Debugging and Testing in TypeScript

Level: Beginner to Intermediate

ℹ️ What You'll Learn
  • What Debugging and Testing in TypeScript means in React + TypeScript
  • How type safety improves React components
  • How to model School Management System data with interfaces and types
  • Common TypeScript mistakes to avoid
  • How to explain this topic in interviews

Why This Matters

Debugging and Testing in TypeScript helps you build React screens with fewer runtime bugs. In real .NET Web API projects, TypeScript makes API DTOs, component props, form state, and shared data contracts easier to understand and safer to change.

Type-safe testing prevents bugs and ensures tests remain valid as code evolves.

Prerequisite: Read React JS article 17 first.

The Problem

React JavaScript can fail at runtime when props, API responses, or form values have the wrong shape. This lesson shows how Debugging and Testing in TypeScript uses TypeScript to catch many of those mistakes while you write code, before the student dashboard reaches users.

Typed Component Tests

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import StudentCard from './StudentCard';

describe('StudentCard', () => {
test('renders student name', () => {
const student: Student = {
id: 1,
name: 'Ravi Kumar',
className: '10',
marks: 95
};

render(<StudentCard student={student} />);

expect(screen.getByText('Ravi Kumar')).toBeInTheDocument();
});

test('calls onDelete when delete clicked', async () => {
const student: Student = {
id: 1,
name: 'Ravi',
className: '10',
marks: 95
};

const onDelete = jest.fn();
const user = userEvent.setup();

render(<StudentCard student={student} onDelete={onDelete} />);

const deleteButton = screen.getByRole('button', { name: /delete/i });
await user.click(deleteButton);

expect(onDelete).toHaveBeenCalledWith(1);
});
});

Mock with Types

const mockStudent: Student = {
id: 1,
name: 'Ravi Kumar',
className: '10',
marks: 95
};

const mockStudents: Student[] = [
mockStudent,
{ id: 2, name: 'Priya Sharma', className: '10', marks: 88 }
];

const mockFetch = jest.fn((url: string) =>
Promise.resolve({
ok: true,
json: async () => mockStudent
} as Response)
);

Typed Hook Tests

import { renderHook, waitFor } from '@testing-library/react';
import { useFetch } from './useFetch';

describe('useFetch', () => {
test('fetches and returns data', async () => {
global.fetch = jest.fn(() =>
Promise.resolve({
ok: true,
json: async () => mockStudents
} as Response)
);

const { result } = renderHook(() =>
useFetch<Student[]>('/api/students')
);

expect(result.current.loading).toBe(true);

await waitFor(() => {
expect(result.current.loading).toBe(false);
});

expect(result.current.data).toEqual(mockStudents);
});
});

DevTools Debugging

function StudentDetail() {
const { data: student, loading, error } = useFetch<Student>('/api/students/1');

console.log('Render:', { student, loading, error });

useEffect(() => {
console.log('Effect: student changed', student);
}, [student]);

return <div>{student?.name}</div>;
}

Type-Safe Mocking

jest.mock('./api/studentService');

import { studentService } from './api/studentService';

const mockService = studentService as jest.Mocked<typeof studentService>;

mockService.getAll.mockResolvedValue([
{ id: 1, name: 'Ravi', className: '10', marks: 95 }
]);

// Type-safe: mockService methods are known

Testing Custom Hooks with Types

import { act, renderHook } from '@testing-library/react';
import { useForm } from './useForm';

describe('useForm', () => {
test('validates form', () => {
const { result } = renderHook(() =>
useForm<StudentForm>({
initialValues: { name: '', email: '' },
validate: (values) => {
const errors: Partial<Record<keyof StudentForm, string>> = {};
if (!values.name) errors.name = 'Required';
return errors;
},
onSubmit: async () => {}
})
);

expect(result.current.values.name).toBe('');

act(() => {
result.current.handleChange({
target: { name: 'name', value: 'Ravi' }
} as any);
});

expect(result.current.values.name).toBe('Ravi');
});
});

Key Takeaways

  • Type test data with interfaces
  • Mock API responses with types
  • Test hooks with renderHook
  • Type-safe mocking
  • Console logging for debugging
  • Next: Deployment and build
⚠️ Testing Mistakes
  1. No types on mocks — Mocks could be wrong
  2. Any in tests — Defeats purpose
  3. Not testing error — Only happy path
  4. Ignoring types — Tests break when code changes
💡 Test Patterns
// Use factory functions for test data
const createStudent = (overrides?: Partial<Student>): Student => ({
id: 1,
name: 'Ravi',
className: '10',
marks: 95,
...overrides
});

const student = createStudent({ name: 'Priya' });
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Typed Testing. Try these prompts:

  • "How do you type test data?"
  • "When mock with jest.fn<T>()?"
  • "How do you test custom hooks?"
  • "Quiz me on testing types"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Quick Definitions

  • Debugging and Testing in TypeScript - The main React + TypeScript concept explained in this lesson.
  • Type/interface - A contract that describes the shape of data.
  • Typed props/state - React data with clear compile-time expectations.
  • API DTO - The request or response shape shared with ASP.NET Core Web API.

Common Mistakes

  • Using any too quickly instead of defining a useful type
  • Typing props loosely and losing the benefit of TypeScript
  • Forgetting that API data can still be missing or invalid at runtime
  • Making types too complex before the component is stable
  • Not sharing clear DTO shapes between frontend and backend teams

Practice Task

Create a small React TypeScript example using Debugging and Testing in TypeScript. Keep it connected to a School Management System scenario.

Suggested practice:

  1. Define a clear Student, Teacher, or Attendance type.
  2. Build a small typed component or hook.
  3. Add one valid example and one intentionally wrong example to see TypeScript errors.
  4. Explain the type contract in your own words.
  5. Rebuild the same example once without looking at the article.

Quick Revision

QuestionAnswer
What is the main idea?Use TypeScript to make Debugging and Testing in TypeScript safer in React.
Where is it used?Props, state, forms, API responses, context, hooks, and routes.
What should beginners avoid?Overusing any and ignoring runtime API validation.
What is the best debugging habit?Read the TypeScript error, check the data shape, and fix the type contract.
🎯 How would you explain Debugging and Testing in TypeScript in an interview?

Debugging and Testing in TypeScript is a React + TypeScript concept that improves safety and maintainability. I would explain which values need types, how TypeScript catches mistakes early, and how it helps when consuming ASP.NET Core Web API responses.

🎯 Where is this used in a real React TypeScript project?

It is used in typed props, API response models, form state, route parameters, context values, custom hooks, and reusable UI components.

Next Article

Deployment and Build in TypeScript ->

nexcoding.in