Skip to main content

Python type() Function

When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...

Testing and Debugging in the PERN Stack

Introduction

In the previous article, we learned:

  • Docker

  • Containers

  • Docker Compose

  • Multi-container architecture

  • Kubernetes basics

  • Cloud-native deployment

Now it is time to learn one of the most important professional development skills:

Testing and Debugging

Large applications can contain:

  • Bugs

  • Logic errors

  • API failures

  • UI issues

  • Security vulnerabilities

Testing helps ensure applications work correctly before users access them.

In this article, we will learn:

  • What testing is

  • Types of testing

  • Unit testing

  • Integration testing

  • API testing

  • Jest

  • React Testing Library

  • Backend testing

  • Debugging techniques


What is Testing?

Testing means:

Checking whether application features work correctly

Why Testing is Important

Testing helps:

  • Reduce bugs

  • Improve reliability

  • Prevent crashes

  • Increase code quality

  • Build stable applications


Types of Testing

Testing TypePurpose
Unit TestingTest small functions
Integration TestingTest connected modules
API TestingTest backend APIs
End-to-End TestingTest complete application

What is Unit Testing?

Unit testing checks:

Small individual parts of code

Example:

  • Functions

  • Components

  • Utility methods


Example Function

function add(a, b) {

    return a + b;
}

Unit Test Example

test('adds numbers correctly', () => {

    expect(add(2, 3)).toBe(5);
});

Understanding test()

test()

defines test case.


Understanding expect()

expect()

checks expected result.


What is Jest?

Jest is a popular testing framework for:

  • React

  • Node.js

  • JavaScript applications


Why Jest is Popular

Jest provides:

  • Simple syntax

  • Fast testing

  • Mocking support

  • Snapshot testing


Installing Jest in Backend

npm install --save-dev jest

Updating package.json

"scripts": {

    "test": "jest"
}

Running Tests

npm test

Creating Test Files

Example:

math.test.js

Example Test File

const add = require('./math');

test('adds numbers', () => {

    expect(add(5, 5)).toBe(10);
});

Understanding toBe()

toBe()

checks exact values.


Common Jest Matchers

MatcherPurpose
toBe()Exact value
toEqual()Object comparison
toContain()Check arrays
toBeTruthy()Boolean checks

Example toContain()

expect(['apple', 'mango'])
.toContain('apple');

Testing Async Functions

Backend APIs often use:

async/await

Async Test Example

test('fetch users', async () => {

    const data = await getUsers();

    expect(data.length).toBe(3);
});

API Testing

API testing checks:

  • Routes

  • Responses

  • Status codes

  • Authentication


Installing Supertest

npm install --save-dev supertest

What is Supertest?

SuperTest helps test Express APIs.


Example API Test

const request = require('supertest');

const app = require('./app');

test('GET /students', async () => {

    const response = await request(app)
    .get('/students');

    expect(response.statusCode).toBe(200);
});

Testing POST APIs

test('create student', async () => {

    const response = await request(app)

    .post('/students')

    .send({

        name: 'Rahul'
    });

    expect(response.statusCode)
    .toBe(201);
});

Mocking in Jest

Mocking means:

Creating fake versions of functions or APIs

Why Mocking is Useful

Mocking prevents:

  • Real API calls

  • Database modifications

  • Slow tests


Example Mock Function

jest.fn()

Mock API Example

jest.mock('axios');

Frontend Testing in React

React applications commonly use:

React Testing Library

Installing React Testing Library

npm install @testing-library/react

What React Testing Library Does

It tests:

  • Components

  • Buttons

  • Inputs

  • User interactions


Example React Component

function Button() {

    return <button>Click Me</button>;
}

Testing React Component

import {

    render,
    screen

} from '@testing-library/react';

import Button from './Button';

test('button renders', () => {

    render(<Button />);

    expect(

        screen.getByText('Click Me')

    ).toBeInTheDocument();
});

Understanding render()

render()

renders component virtually for testing.


Understanding screen()

screen()

searches rendered elements.


Testing User Interactions

React Testing Library supports:

  • Click events

  • Form inputs

  • Typing simulation


Example Click Test

import userEvent from
'@testing-library/user-event';

Button Click Example

test('button click', async () => {

    render(<Button />);

    const button = screen.getByText(
        'Click Me'
    );

    await userEvent.click(button);
});

What is Snapshot Testing?

Snapshot testing compares:

UI changes over time

Snapshot Example

expect(container)
.toMatchSnapshot();

End-to-End Testing

End-to-end testing checks:

Complete application workflow

Example:

  • Login

  • Dashboard access

  • Logout


Popular E2E Testing Tools

ToolPurpose
CypressFrontend testing
PlaywrightBrowser automation

What is Cypress?

Cypress tests real browser interactions.


Installing Cypress

npm install cypress --save-dev

Running Cypress

npx cypress open

Example Cypress Test

describe('Login Test', () => {

    it('logs user in', () => {

        cy.visit('/login');

        cy.get('input[type=email]')
        .type('test@gmail.com');

        cy.get('button')
        .click();
    });
});

What is Debugging?

Debugging means:

Finding and fixing errors in code

Common Types of Bugs

Bug TypeExample
Syntax ErrorMissing bracket
Logical ErrorWrong calculation
Runtime ErrorUndefined variable

Using console.log()

Most basic debugging method:

console.log(data);

Browser Developer Tools

Modern browsers provide:

Developer Tools

Shortcut:

F12

Useful DevTools Tabs

TabPurpose
ConsoleErrors and logs
NetworkAPI requests
ElementsHTML inspection

Debugging Backend APIs

Use:

  • Morgan

  • Postman

  • Thunder Client

to inspect backend behavior.


Handling Errors Properly

Always use:

try...catch

Example

try {

    const data = await fetchUsers();

} catch (err) {

    console.error(err.message);
}

Logging Errors

Useful logging libraries:

  • Winston

  • Morgan

  • Pino


What is Code Coverage?

Code coverage measures:

How much code is tested

Running Coverage Report

npm test -- --coverage

Benefits of Testing

Testing improves:

  • Stability

  • Maintainability

  • Security

  • Developer confidence


Common Beginner Mistakes

Not Testing Edge Cases

Example:

  • Empty input

  • Invalid email

  • Large files


Testing Too Little

Important features must always be tested.


Ignoring Error Handling

Always test:

  • Invalid requests

  • Unauthorized access

  • Database failures


Best Practices

Write Small Tests

Small tests are:

  • Easier to debug

  • Faster to run


Use Separate Test Files

Example:

auth.test.js
student.test.js

Automate Testing

Use CI/CD pipelines to run tests automatically.


Test Critical Features First

Priority:

  • Authentication

  • Payments

  • Database operations


Real-World Testing Workflow

Professional workflow:

Write Code
    ↓
Write Tests
    ↓
Run Tests
    ↓
Fix Bugs
    ↓
Deploy Application

Real-World Companies Using Automated Testing

Testing is heavily used by:

  • Google

  • Netflix

  • Amazon

  • Facebook

  • Microsoft


Conclusion

You have now learned testing and debugging in the PERN stack.

You learned:

  • Unit testing

  • API testing

  • Jest

  • React Testing Library

  • Cypress

  • Debugging techniques

  • Error handling

  • Code coverage

Now your PERN stack development workflow is becoming professional, reliable, and production-ready.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? 📌 Readability – Comments make code easier to understand for you and others. 📌 Maintenance – When you revisit your code after months, comments remind you what you were doing. 📌 Collaboration – In team projects, comments explain code to fellow developers. 📌 Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . 💻 Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } 🧠 Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

💡 Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. 🧑‍💻 Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...