paint-brush
Elevating Frontend Development: The Crucial Role of Testing in Web Devby@ljaviertovar
615 reads
615 reads

Elevating Frontend Development: The Crucial Role of Testing in Web Dev

by L Javier TovarNovember 22nd, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In web development, this involves checking that web pages look and function correctly in different browsers and devices.

People Mentioned

Mention Thumbnail
featured image - Elevating Frontend Development: The Crucial Role of Testing in Web Dev
L Javier Tovar HackerNoon profile picture

Frontend web development is one of the most exciting and dynamic areas in the world of technology. We are constantly creating attractive and functional user interfaces that directly impact the user experience.


However, there is an aspect that is often overlooked and underestimated: testing. While it may initially appear as a secondary task, it is an essential practice in web development.


If you are new to this field, you may wonder what “testing” involves and why you should invest time in it. On the other hand, if you already have experience, it is crucial to consistently remember the importance of testing and how it can enhance the quality of your projects.


What Is Testing in Web Development?

In web development, this involves checking that web pages look and function correctly in different browsers and devices.


It is an essential part of the development process to ensure a smooth and error-free user experience.


Testing in frontend web development can be divided into two main categories: manual testing and automated testing.


Each approach has its advantages and challenges.

Manual Testing

Manual testing is exactly what it sounds like: a human performs checks and evaluations directly on a web application’s user interface.


This involves clicking buttons, filling out forms, and navigating the site to verify its functionality.

Manual testing is effective in identifying visual and usability issues, but it is prone to subjectivity and can be labor-intensive and slow, especially on large projects.


Automated Testing

Automated testing is a more efficient and systematic approach. Instead of relying entirely on manual interventions, scripts and test suites are created to perform specific actions in an application and verify if the expected results are achieved.


This not only saves time but also allows for regression testing, which means you can quickly check whether new updates have negatively impacted existing parts of your application.


The Foundations of Automated Testing: Unit and Integration Testing

Two fundamental concepts in the field of testing are unit testing and integration testing.


These two practices are essential to ensure the functionality and stability of an application. Unit testing focuses on evaluating individual components, while integration testing focuses on how these components work together as a complete system.


Although this blog is not a practical tutorial, let’s look at some examples to get a bit more of an idea of these testing practices.


Unit Testing: Breaking Down the Code

Unit testing is the first pillar of testing in web development. It focuses on evaluating individual code units, such as functions or methods, to ensure they function correctly in isolation.


The goal of unit testing is to ensure that each small part of the code, or unit, performs the task it was designed for.


Practical Example:


Imagine you’re developing an e-commerce application and have a function that calculates the total price of a purchase.


A unit test for this function could verify if the calculations are accurate, if discounts are applied correctly, and if taxes are handled properly.

This is done by testing the function with different datasets and checking that the results are as expected.


Let’s assume you have the following function in your React application:


function calculateTotalPrice(subtotal, discount, taxes) {
  // Perform calculations to get the total price
  const priceWithDiscount = subtotal - discount;
  const priceWithTaxes = priceWithDiscount * (1 + taxes);
  return priceWithTaxes;
}


And here’s how you can write a unit test for this function using the Jest library, which is commonly used in the React development environment:


import { calculateTotalPrice } from './yourFunctionFile'; // Make sure to import the function correctly

describe('Testing the calculateTotalPrice function', () => {
  it('should calculate the total price correctly', () => {
    const subtotal = 100;
    const discount = 10;
    const taxes = 0.08;

    const totalPrice = calculateTotalPrice(subtotal, discount, taxes);

    // Verify if the result is as expected
    expect(totalPrice).toBe(98); // The expected total price after the discount and taxes
  });

  it('should handle negative discounts', () => {
    const subtotal = 100;
    const discount = -10;
    const taxes = 0.08;

    const totalPrice = calculateTotalPrice(subtotal, discount, taxes);

    // Verify if the result is as expected
    expect(totalPrice).toBe(110); // The expected total price when a negative discount is applied
  });
});


In this example, we’ve written two unit tests. The first one checks if the calculateTotalPrice function correctly calculates the total price after applying the discount and taxes.


The second test verifies if the function properly handles negative discounts. Jest allows us to use the expect function to compare the function's result with an expected value and check if the function behaves as expected.


Integration Tests: Connection and Collaboration

Integration tests are the second pillar of testing and focus on evaluating how different parts of an application interact when combined. These tests ensure that various components of an application, which perform correctly in unit tests, seamlessly integrate.


Practical Example:


Let’s say you’re building a news website with a navigation bar component and a comments component.


Integration tests could evaluate if the comments load correctly when a user clicks on an article from the navigation bar. This involves verifying not only the functionality of each component in isolation but also how they collaborate.


In this case, let us assume that we have the following components:


NavigationBar.js :

import React from 'react';

function NavigationBar(props) {
  const handleArticleClick = (articleId) => {
    // Handle the article click event, perhaps by passing it to a parent component.
  };

  return (
    <nav>
      <ul>
        <li onClick={() => handleArticleClick(1)}>Article 1</li>
        <li onClick={() => handleArticleClick(2)}>Article 2</li>
        <li onClick={() => handleArticleClick(3)}>Article 3</li>
      </ul>
    </nav>
  );
}

export default NavigationBar;


Comments.js :


function Comments({ articleId, comments }) {
  // Fetch and display comments for the given articleId
  const articleComments = comments.filter((comment) => comment.articleId === articleId);

  return (
    <div>
      <h2>Comments for Article {articleId}</h2>
      <ul>
        {articleComments.map((comment) => (
          <li key={comment.id}>{comment.text}</li>
        ))}
      </ul>
    </div>
  );
}

export default Comments;


Now, here’s how we could write an integration test using a React testing library like this:


import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import NavigationBar from './NavigationBar';
import Comments from './Comments';

test('loads and displays comments when an article is clicked', () => {
  // Mock some comments data
  const comments = [
    { id: 1, articleId: 1, text: 'Comment 1 for Article 1' },
    { id: 2, articleId: 1, text: 'Comment 2 for Article 1' },
    { id: 3, articleId: 2, text: 'Comment 1 for Article 2' },
  ];

  // Render the components
  const { getByText } = render(
    <>
      <NavigationBar />
      <Comments articleId={1} comments={comments} />
    </>
  );

  // Initially, the comments for Article 1 should not be visible
  expect(getByText("Comment 1 for Article 1")).not.toBeVisible();
  expect(getByText("Comment 2 for Article 1")).not.toBeVisible();

  // Simulate clicking on "Article 1" in the NavigationBar
  fireEvent.click(getByText('Article 1'));

  // After clicking, the comments for Article 1 should be visible
  expect(getByText("Comment 1 for Article 1")).toBeVisible();
  expect(getByText("Comment 2 for Article 1")).toBeVisible();
});


This test checks that comments load correctly when you click “Article 1” in the navigation bar. Integration tests like this help ensure that individual components work well together as part of your larger application.


The Importance of Testing and Early Error Detection

Software errors are inevitable. They can arise at any stage of development, from the inception of an idea to implementation and, finally, user delivery. However, what we can control is when and how we identify these errors.


Early error detection refers to the practice of identifying and resolving issues in the early stages of the development process. This proactive approach focuses on preventing errors from spreading and becoming costly obstacles in advanced project stages.


The significance of testing and early error detection lies in two fundamental aspects. Firstly, thorough testing allows developers to identify and address issues in their code before they reach end-users.


Secondly, early error detection is not just a matter of quality but also an economic concern, among others. Correcting problems in the early development stages is significantly more cost-effective than doing so in advanced stages or, worse yet, after the software has been deployed.

Conclusion

In summary, testing in web development involves a “polishing” approach through unit testing and a “connecting” approach by conducting integration testing.


Both are crucial pillars to ensure that your application is robust, reliable, and ready to face real-world challenges.


Although this is just a glimpse into the world of testing, I hope you now have a better understanding of what it entails. I recommend delving deeper into this topic for more comprehensive knowledge.



Read more:


Want to connect with the Author?

Love connecting with friends all around the world on Twitter.


Also published here.