Avoid Direct Node Access in Testing Library: Error Explained with Fixes & Examples

While writing tests using React Testing Library, you may see this warning:

Avoid direct Node access. Prefer using the methods from Testing Library

This can be confusing, especially for beginners

In this guide, you’ll learn:

  • What this warning means
  • Why it happens
  • How to fix it (step-by-step)
  • Best practices with examples

What Does This Error Mean?

πŸ‘‰ In simple terms:

You are accessing DOM elements directly (like document.querySelector) instead of using Testing Library methods.


❌ Example That Causes This Warning

const element = document.querySelector('.btn');
expect(element.textContent).toBe('Submit');

πŸ‘‰ Problem:

  • Direct DOM access
  • Not user-focused ❌

Why This is a Problem?

Testing Library follows this principle:

βœ… β€œTest the app the way users use it”

Users don’t use:

  • querySelector
  • getElementById

πŸ‘‰ They interact with:

  • Text
  • Buttons
  • Labels

Correct Way Using Testing Library

Example Fix

import { render, screen } from '@testinglibrary/react';

render(<button>Submit</button>);
const button = screen.getByText('Submit');
expect(button).toBeInTheDocument();

πŸ‘‰ Now:

  • Uses Testing Library methods βœ…
  • Matches real user behavior βœ…

Common Scenarios & Fixes

❌ Scenario 1: Using querySelector

const el = container.querySelector('.title');

βœ… Fix

screen.getByText('Title');

❌ Scenario 2: Using getElementById

document.getElementById('username');

βœ… Fix

screen.getByLabelText('Username');

❌ Scenario 3: Accessing container directly

const { container } = render(<App />);
const el = container.firstChild;

βœ… Fix

screen.getByRole('heading');

Best Queries to Use

Testing Library provides powerful queries:


By Role (Best)

screen.getByRole('button');

By Text

screen.getByText('Submit');

By Label

screen.getByLabelText('Email');

By Placeholder

screen.getByPlaceholderText('Enter name');

Query Priority (Very Important)

Follow this order:

  1. getByRole
  2. getByLabelText
  3. getByText
  4. getByPlaceholderText
  5. getByTestId (last option)

When is Direct DOM Access Allowed?

πŸ‘‰ Rare cases only:

  • Debugging
  • Complex DOM structure
  • No accessible selectors available

Example:

const { container } = render(<App />);
console.log(container.innerHTML);

Real-World Example

❌ Bad Test

const { container } = render(<button>Login</button>);
expect(container.firstChild.textContent).toBe('Login');

βœ… Good Test

render(<button>Login</button>);
expect(screen.getByText('Login')).toBeInTheDocument();

Why Testing Library Recommends This

  • Better readability
  • More maintainable tests
  • Closer to real user behavior
  • Encourages accessibility

Common Mistakes


❌ Overusing getByTestId

πŸ‘‰ Use only when necessary


❌ Ignoring accessibility

πŸ‘‰ Use roles and labels


❌ Writing implementation-based tests

πŸ‘‰ Focus on user behavior


Interview Tip

If asked:

β€œWhy avoid direct DOM access?”

πŸ‘‰ Answer:

β€œBecause Testing Library encourages testing from the user’s perspective using accessible queries instead of implementation details.”


Final Summary

  • Avoid direct DOM methods (querySelector, getElementById)
  • Use Testing Library queries (getByRole, getByText)
  • Write user-focused tests
  • Follow query priority

πŸ’‘ Writing tests? Subscribe to get simple testing guides, real-world examples, and debugging tips. Happy Coding!

Prompt Engineering vs RAG vs Fine-Tuning: Differences Explained with Examples

With the rise of AI tools like ChatGPT, many developers and beginners are hearing terms like:

  • Prompt Engineering
  • RAG (Retrieval-Augmented Generation)
  • Fine-tuning

But what do they actually mean? πŸ€”

In this guide, you’ll learn:

  • What each concept is
  • How they work
  • Key differences
  • Real-world examples
  • When to use each

1. What is Prompt Engineering?

Simple Definition

Prompt Engineering is the process of writing better inputs (prompts) to get better outputs from AI.


Example

❌ Bad Prompt

Explain React

πŸ‘‰ Output: Basic explanation


βœ… Good Prompt

Explain React in simple terms with real-world examples for beginners

πŸ‘‰ Output: Clear, structured answer


Key Idea

πŸ‘‰ You are not changing the AI model
πŸ‘‰ You are only improving how you ask questions


When to Use

  • Chatbots
  • Content generation
  • Coding help
  • Quick improvements

2. What is RAG (Retrieval-Augmented Generation)?

Simple Definition

RAG combines AI with external data sources to give more accurate answers.


Real-Life Analogy

πŸ‘‰ Imagine:

  • AI = Student
  • Database = Book

πŸ‘‰ Instead of guessing, the student:

  • Looks into the book
  • Then answers

How It Works

  1. User asks a question
  2. System searches database/documents
  3. Relevant data is retrieved
  4. AI generates answer using that data

Example

Without RAG

What is my company policy?

πŸ‘‰ AI doesn’t know ❌


With RAG

πŸ‘‰ System fetches policy from database
πŸ‘‰ AI answers correctly βœ…


Use Cases

  • Chatbots with company data
  • Customer support systems
  • Knowledge base search

3. What is Fine-Tuning?

Simple Definition

Fine-tuning is training an AI model with your own data to make it specialized.


Real-Life Analogy

πŸ‘‰ AI = Fresh graduate
πŸ‘‰ Fine-tuning = Job training


Example

You train model with:

Customer support conversations

πŸ‘‰ Now AI:

  • Talks like your support team
  • Understands your domain

Use Cases

  • Domain-specific AI (medical, finance)
  • Brand-specific tone
  • Custom chatbots

Key Differences (Very Important)

FeaturePrompt EngineeringRAGFine-Tuning
Changes model?❌ No❌ Noβœ… Yes
Uses external data?❌ Noβœ… Yesβœ… Yes
CostLowMediumHigh
ComplexityEasyMediumAdvanced
SpeedFastMediumSlow setup
Best forQuick resultsDynamic dataDeep customization

Real-World Comparison Example

Scenario: Company Chatbot

πŸ”Ή Prompt Engineering

πŸ‘‰ Ask better questions
❌ No company data


πŸ”Ή RAG

πŸ‘‰ Fetch company documents
βœ… Always updated


πŸ”Ή Fine-Tuning

πŸ‘‰ Train model on company data
βœ… Deep understanding


When to Use What?

Use Prompt Engineering when:

  • You need quick improvements
  • No custom data required
  • Beginner level

Use RAG when:

  • You have external data
  • Data changes frequently
  • Need accurate answers

Use Fine-Tuning when:

  • You need custom behavior
  • Domain-specific AI
  • High accuracy required

Best Approach (Pro Tip)

πŸ‘‰ In real-world applications:

βœ… Combine all three:

  • Prompt Engineering β†’ better instructions
  • RAG β†’ real-time data
  • Fine-tuning β†’ deeper intelligence

Common Mistakes


❌ Thinking prompt engineering is enough

πŸ‘‰ Not for complex systems


❌ Using fine-tuning for dynamic data

πŸ‘‰ Use RAG instead


❌ Ignoring RAG

πŸ‘‰ Leads to outdated answers


Interview Tip

If asked:

β€œPrompt vs RAG vs Fine-tuning?”

πŸ‘‰ Answer:

β€œPrompt engineering improves input, RAG adds external knowledge, and fine-tuning customizes the model itself.”


Final Summary

  • Prompt Engineering β†’ Better questions
  • RAG β†’ External data integration
  • Fine-tuning β†’ Model training

πŸ‘‰ Each solves different problems


πŸ’‘ Found this helpful? Subscribe for simple AI guides, real-world examples, and developer-friendly tutorials. Happy Coding!

Type vs Interface in TypeScript: Complete Guide with Examples (Beginner to Advanced)

When working with TypeScript, one of the most common questions is:

πŸ€” Should I use type or interface?

Both are used to define the structure of data, but they behave differently in certain scenarios.

In this guide, you’ll learn:

  • What type and interface are
  • Key differences
  • All important scenarios with examples
  • When to use each (very important)

What is interface in TypeScript?

An interface is used to define the structure (shape) of an object.


Basic Example

interface User {
name: string;
age: number;
}
const user: User = {
name: "Raju",
age: 25,
};

What is type in TypeScript?

A type is more flexible and can define:

  • Objects
  • Primitives
  • Unions
  • Tuples
  • Functions

Basic Example

type User = {
name: string;
age: number;
};

πŸ‘‰ Works similar to interface for objects


Key Differences (Quick Overview)

Featureinterfacetype
Object structureβœ… Yesβœ… Yes
Union types❌ Noβœ… Yes
Intersection types⚠️ Limitedβœ… Yes
Declaration mergingβœ… Yes❌ No
FlexibilityMediumHigh

Scenario 1: Object Definition

πŸ‘‰ Both work the same

interface User {
name: string;
}
type User = {
name: string;
};

βœ… No major difference here


Scenario 2: Declaration Merging (Important)

βœ… interface supports merging

interface User {
name: string;
}

interface User {
age: number;
}

πŸ‘‰ Result:

{
name: string;
age: number;
}

❌ type does NOT support merging

type User = {
name: string;
};

type User = {
age: number;
}; // ❌ Error

Scenario 3: Union Types

βœ… Using type

type Status = "success" | "error" | "loading";

❌ interface cannot do this

πŸ‘‰ Not supported


Scenario 4: Intersection Types

βœ… Using type

type Person = {
name: string;
};

type Employee = Person & {
salary: number;
};

⚠️ interface alternative

interface Person {
name: string;
}

interface Employee extends Person {
salary: number;
}

Scenario 5: Functions

βœ… Using type

type Add = (a: number, b: number) => number;

βœ… Using interface

interface Add {
(a: number, b: number): number;
}

Scenario 6: Extending / Inheritance

interface

interface Person {
name: string;
}

interface Employee extends Person {
salary: number;
}

type

type Person = {
name: string;
};

type Employee = Person & {
salary: number;
};

Scenario 7: Primitive Types

βœ… Only type supports this

type ID = string | number;

πŸ‘‰ interface cannot do this ❌


Scenario 8: Tuples

type Point = [number, number];

πŸ‘‰ Only type supports tuples


Scenario 9: Working with Classes

interface (preferred)

interface User {
name: string;
}

class Person implements User {
name = "Raju";
}

When to Use interface

Use interface when:

  • Defining object structure
  • Working with classes
  • Need declaration merging
  • Building large applications

When to Use type

Use type when:

  • Using unions (|)
  • Using intersections (&)
  • Working with primitives
  • Advanced type logic

Best Practice (Very Important)

πŸ‘‰ Use both together:

type Status = "success" | "error";

interface ApiResponse {
status: Status;
data: string;
}

Common Mistakes


❌ Using interface for unions

interface Status = "success" | "error"; // ❌

❌ Overusing any

πŸ‘‰ Avoid losing type safety


❌ Confusion between both

πŸ‘‰ Use based on use case


Interview Tip

If asked:

β€œtype vs interface?”

πŸ‘‰ Answer:

β€œBoth define data shapes, but type is more flexible (supports unions, tuples), while interface supports declaration merging and is better for object-oriented design.”


Final Summary

  • Both define structure of data
  • interface β†’ best for objects & classes
  • type β†’ best for advanced types
  • Use both based on need

πŸ’‘ Found this helpful? Subscribe to get simple TypeScript tutorials, interview questions, and real-world coding tips. Happy Coding!

TypeScript Error: β€œObject literal may only specify known properties” (Fix Explained)

While working with TypeScript, you might encounter this error:

Object literal may only specify known properties, and 'age' does not exist in type 'User'

This error can be confusing for beginners.

In this guide, you’ll learn:

  • What this error means
  • Why it happens
  • How to fix it (step-by-step)
  • Common mistakes to avoid

What Does This Error Mean?

πŸ‘‰ In simple terms:

TypeScript is telling you that you are adding a property that is not defined in the type or interface


Example That Causes the Error

interface User {
name: string;
}

const user: User = {
name: "Raju",
age: 25, // ❌ Error here
};

πŸ‘‰ Error:

Object literal may only specify known properties, and 'age' does not exist in type 'User'

Why This Error Happens

TypeScript uses strict type checking.

πŸ‘‰ It ensures that:

  • You only use properties defined in the type
  • No extra or unexpected data is added

How to Fix This Error


Fix 1: Add the Missing Property

If the property is valid, add it to the interface:

interface User {
name: string;
age: number;
}

πŸ‘‰ Now it works βœ…


Fix 2: Remove Extra Property

If the property is not needed:

const user: User = {
name: "Raju",
};

Fix 3: Use Index Signature (Flexible Objects)

If object can have dynamic properties:

interface User {
name: string;
[key: string]: any;
}

πŸ‘‰ Allows extra properties βœ…


Fix 4: Use Type Assertion (Use Carefully)

const user = {
name: "Raju",
age: 25,
} as User;

⚠️ This tells TypeScript to ignore extra properties
πŸ‘‰ Use only when you are sure


Fix 5: Assign Object to Variable First

const temp = {
name: "Raju",
age: 25,
};

const user: User = temp;

πŸ‘‰ This may bypass strict checking in some cases


⚠️ Common Mistakes


❌ Typo in property name

namee: "Raju" // ❌ wrong

❌ Forgetting to update interface

πŸ‘‰ Adding new fields but not updating type


❌ Overusing any

πŸ‘‰ Removes TypeScript benefits


Real-World Scenario

Imagine:

πŸ‘‰ API returns:

{
"name": "Raju",
"age": 25
}

But your interface is:

interface User {
name: string;
}

πŸ‘‰ You’ll get this error


Best Practices

  • Keep types updated
  • Avoid unnecessary properties
  • Use strict typing
  • Avoid overusing any

Interview Tip

If asked:

β€œWhat is this error?”

πŸ‘‰ Answer:

β€œIt occurs when an object contains properties that are not defined in its type or interface.”


Final Summary

  • TypeScript enforces strict object structure
  • Extra properties cause this error
  • Fix by updating type or removing extra fields
  • Use index signature for flexible objects

Related Articles


πŸ’‘ Facing more TypeScript errors? Subscribe to get simple fixes, real-world examples, and developer-friendly explanations. Happy Coding!

What is DOM, Virtual DOM, and Real DOM in React? (Simple Explanation for Beginners)

If you are new to web development or React, you might have heard terms like:

  • DOM
  • Virtual DOM
  • Real DOM

And it can feel confusing πŸ˜…

Don’t worry β€” in this guide, we’ll explain everything in very simple terms, even if you are not from a technical background.


What is DOM?

DOM stands for:

Document Object Model

πŸ‘‰ In simple words:

DOM is a structure of your web page


Real-Life Analogy

Think of a web page like a house 🏠

  • Walls β†’ HTML elements
  • Furniture β†’ Content
  • Layout β†’ Structure

πŸ‘‰ DOM is like the blueprint of the house


Example

<h1>Hello</h1>
<p>Welcome to my website</p>

πŸ‘‰ Browser converts this into a structure like:

Page
β”œβ”€β”€ h1 β†’ "Hello"
└── p β†’ "Welcome to my website"

What is Real DOM?

Real DOM is:

The actual DOM in the browser


Problem with Real DOM

Whenever something changes:

πŸ‘‰ The browser may rebuild or update large parts of the page

This can be:

  • Slow
  • Inefficient
  • Costly for performance

Example

Imagine:

πŸ‘‰ You change one word on the page

❌ Browser may re-check or update entire section


What is Virtual DOM?

Virtual DOM is a concept used by React


Simple Definition

Virtual DOM is a lightweight copy of the Real DOM


Real-Life Analogy

Think like this:

πŸ‘‰ Instead of directly editing your house 🏠
πŸ‘‰ You first make changes in a model (mini version)

Then:

βœ” Compare changes
βœ” Update only what is needed


How Virtual DOM Works (Step-by-Step)


Step 1: Initial Render

React creates:
πŸ‘‰ Virtual DOM
πŸ‘‰ Real DOM


Step 2: State Changes

When something changes:

πŸ‘‰ React creates a new Virtual DOM


Step 3: Comparison (Diffing)

React compares:

  • Old Virtual DOM
  • New Virtual DOM

Step 4: Update Only Changes

πŸ‘‰ React updates only the changed parts in Real DOM


Example (Very Simple)


Initial UI

<h1>Hello</h1>

Updated UI

<h1>Hello World</h1>

What React Does

❌ Does NOT reload whole page
βœ… Updates only text inside <h1>


Why Virtual DOM is Faster

FeatureReal DOMVirtual DOM
UpdatesFull or largeOnly required parts
SpeedSlowerFaster
EfficiencyLowHigh

Key Differences (Simple Table)

FeatureReal DOMVirtual DOM
TypeActual UICopy of UI
SpeedSlowFast
UpdatesDirectIndirect
Used byBrowserReact

Why React Uses Virtual DOM

React uses Virtual DOM to:

βœ” Improve performance
βœ” Reduce unnecessary updates
βœ” Make apps faster


Real-World Example

Imagine a shopping app:

πŸ‘‰ You add 1 item

❌ Without Virtual DOM β†’ entire page refresh
βœ… With Virtual DOM β†’ only cart updates


Common Misunderstanding


❌ Virtual DOM replaces Real DOM

πŸ‘‰ Not true

πŸ‘‰ It works along with Real DOM


Interview Tip

If asked:

β€œWhat is Virtual DOM?”

πŸ‘‰ Answer:

β€œIt is a lightweight copy of the Real DOM used by React to efficiently update only changed parts of the UI.”


Final Summary

  • DOM = structure of webpage
  • Real DOM = actual browser DOM
  • Virtual DOM = lightweight copy used by React
  • React updates only changed parts β†’ faster performance

πŸ’‘ Found this helpful? Subscribe to get simple explanations of complex concepts, React tutorials, and coding tips. Happy Coding!