Tech Startup https://ehsaantech.com/ Technology Partner Thu, 06 Jun 2024 11:28:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://ehsaantech.com/wp-content/uploads/2022/02/cropped-ehsaantechlogo-32x32.png Tech Startup https://ehsaantech.com/ 32 32 From Testing to Automation: NestJS and GitHub Actions https://ehsaantech.com/from-testing-to-automation-nestjs-and-github-actions/ Fri, 16 Feb 2024 07:08:04 +0000 https://ehsaantech.com/?p=3606 Services Full Stack Development QA & Automation Mobile App Development Cloud and DevOps UIUX MVP development Company About CASE STUDIES Blogs X Contact Us Introduction In the world of software development, we’re on a mission to make our code rock-solid and reliable. In my previous article, we explored how to test our code in NestJS […]

The post From Testing to Automation: NestJS and GitHub Actions appeared first on Tech Startup.

]]>

From Testing to Automation: NestJS and GitHub Actions

Introduction

In the world of software development, we’re on a mission to make our code rock-solid and reliable. In my previous article, we explored how to test our code in NestJS using Jest. But here’s the catch: testing manually can be time-consuming. That’s where automation swoops in to save the day.

In this article, we’re going to learn a super cool trick: how to make our tests run automatically using GitHub Actions. Think of it like having your own coding assistant that checks your work whenever you make changes. But why do we need this? Well, that’s where Continuous Integration (CI) comes in.

Continuous integration refers to the build and unit testing stages of the software release process. Every revision that is committed triggers an automated build and test.

Automation makes our system reliable, resilient and gives us confidence not only to the development team but also the leadership if all tests are passing in CI.

Buckle up, then! As NestJS and GitHub Actions work together to make your coding life easier and your program more dependable, we’re going to enter into the world of automation. Let’s get started on this exciting journey!

Prerequisites

Before diving into this tutorial, make sure you have a basic understanding of Git/GitHub.

Putting Unit Test Automation into Action

We’ll start by setting up a new repository on your GitHub account and initializing Git for your project. Follow these straightforward steps:

  1. Open your project folder in your terminal and run git init
  2. Stage your project files with git add .
  3. Commit your staged changes with git commit -m “commit-name”
  4. Connect your local project to GitHub repository using git remote add origin “your_repository_origin”
  5. Push your changes to GitHub with git push origin master

Now, your project is on GitHub, and you’re ready to set up GitHub Actions for automated testing.

In the root folder of your project, create a .github/workflows directory if it doesn’t already exist.

Inside the workflows directory, create a test.yml file. This file will contain the configuration for your GitHub Actions workflow.

 

Image description

 

Next, copy and paste this code into your test.yml file:

test.yml

Event Trigger: This workflow is triggered whenever there is a push or pull request to the “master” branch of your GitHub repository.

Node.js Versions: It tests your code on different Node.js versions (16.x and 18.x).

Checkout Repository: This step checks out your code repository, making it available for further actions.

Set Up Node.js: It configures the Node.js environment by using the specified Node.js version.

Install Dependencies: This step installs project dependencies using npm ci to ensure a clean and consistent environment.

Run Tests: It executes your unit tests using “npm test”

The Run Tests task specifies its working directory as src/book because it contains the book.service.spec.ts file where all the tests are located. In contrast, the working directory for the Install Dependencies task is configured as the root directory. This is because the package.json file, which holds the project’s dependencies, is located in the root folder.

 

Image description

 

Finally, after making these configuration changes, you should commit and push them to your GitHub repository. Once you’ve done that, GitHub will automatically start running the tests associated with your commits. You can easily track the progress and results of these tests by navigating to the GitHub Actions tab in your repository. This way, you can keep an eye on how your automated tests are performing. This ensures that your code is continuously checked for errors and bugs, preventing issues from going unnoticed.

 

Image description

Image description

 

That’s all for today. Thanks for reading.

Here you’ll find the source code for the implementation mentioned above.

Ehsaan Technologies is a Software Development & Consultancy firm providing customized Web development and Mobile App development services to its customers across the Globe.

 

In pursuing advanced technology and personalized development, we are driven by the need to improve businesses and maximize their digital impact.

The post From Testing to Automation: NestJS and GitHub Actions appeared first on Tech Startup.

]]>
Mastering Unit Testing With NestJS https://ehsaantech.com/mastering-unit-testing-with-nestjs/ Thu, 15 Feb 2024 13:21:55 +0000 https://ehsaantech.com/?p=3574 Services Full Stack Development QA & Automation Mobile App Development Cloud and DevOps UIUX MVP development Company About CASE STUDIES Blogs X Contact Us Introduction Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually scrutinized for proper operation. In this guide, we will walk […]

The post Mastering Unit Testing With NestJS appeared first on Tech Startup.

]]>

Mastering Unit Testing With NestJS

Introduction

Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually scrutinized for proper operation. In this guide, we will walk through an example of unit testing in Node.js using the NestJS framework. We will focus on testing a BookService class, covering its methods for creating, retrieving, updating and deleting books while demonstrating best practices for testing.

Prerequisites

Before diving into unit testing, make sure you have a basic understanding of Node.js, NestJS, Jest and MongoDB.

Setting up the Environment

To begin, let’s set up the environment by creating a book.service.ts file. Additionally, we’ll install and import all necessary dependencies and construct a BookService class.

Next, proceed to develop a function for generating a new book entry using MongoDB and the Mongoose library.

Then, develop a function to find a book by its id.

Similarly, create a function to update a book.

Finally, create a function to delete a book.

Unit Testing the BookService

Now, as we delve into the unit testing process for the BookService class, our aim is to ensure that each function operates precisely as intended.

Initializing the Testing Environment

First create a book.service.spec.ts file in the same directory as the book.service file.
In unit testing for NestJS, the Test and TestingModule classes from @nestjs/testing establish the testing environment. To simulate database interactions, the getModelToken function from @nestjs/mongoose is employed. Through the jest.fn() function, a mock BookService instance is created to track method calls. This mock service and a simulated database model are provided by configuring the testing module using getModelToken(Book.name). After compilation, the BookService instance and model are accessed using the module.get() method.

Testing the ‘create’ Function of BookService

In this test scenario, we create a mock object that simulates a new book. We then set up a mock implementation of the create function within the model to resolve with our predefined mock book. By calling the create function of our service with the mock book data, we ensure that the service responds as anticipated. The expect statement confirms that the result corresponds to our predefined mock book, thereby validating the correctness of the create function. Also initialize all the required dependencies.

Testing the ‘findById’ Function of BookService

For this test scenario, we begin by importing essential dependencies and creating a mockBook object. This object will serve as a placeholder for simulating a book’s attributes and properties during our tests.

Then we thoroughly test findById function. We have declared three test cases.

The first test case ensures that the function correctly finds and returns a book by its ID. We achieve this by mocking the model’s findById function to resolve with our predefined mock book, and then verifying if the result matches the expectation.

The subsequent test cases handle error scenarios. In the second test case, we simulate an invalid ID and assert that calling findById with this ID triggers a BadRequestException. We achieve this by mocking the isValidObjectId function to return false and then using expect to confirm the thrown error.

The third test case tests the condition where the findById function cannot find the requested book. We mock the model’s findById function to return null, simulating a scenario where the book is not found. As expected, we then verify if calling findById with this ID raises a NotFoundException.

By testing these different scenarios, we ensure that our findById function behaves correctly and handles exceptions as intended.

Testing the ‘updateById’ Function of BookService

In this test scenario, we verify the functionality of updating and returning a book’s information. The test scenario involves simulating the update of a book’s title and confirming that the updated book object is returned as expected.

During the test execution, the service’s ‘updateById’ function is called with the relevant book ID and the updated book data. The mock implementation ensures that the service interacts with the model’s ‘findByIdAndUpdate’ method as intended.

Testing the ‘deleteById’ Function of BookService

The test ensures that the “deleteById” function successfully deletes a book and returns the expected result. By mocking the database operation using “findByIdAndDelete,” we verify that the function interacts correctly with the data model.

Book Delete By Id

Running Test Scenarios

After completing our test scenarios to cover various aspects of our application’s functionality, it’s time to see them in action.

Must ensure that you are in the root directory of your Nest.js project, follow these steps:

  • Open your terminal or command prompt.
  • Enter the following command: npm run test

This command initiates the execution of your unit tests using the testing framework we set up earlier.

 

Image description

 

Running the tests is a crucial step in ensuring the reliability and correctness of your code base.

Conclusion

Throughout this guide, we explored the core concepts of unit testing in NestJS, including the setup of testing modules, the creation of mock services, and the execution of test cases.

Ehsaan Technologies is a Software Development & Consultancy firm providing customized Web development and Mobile App development services to its customers across the Globe.

In pursuing advanced technology and personalized development, we are driven by the need to improve businesses and maximize their digital impact.

The post Mastering Unit Testing With NestJS appeared first on Tech Startup.

]]>
Optimizing Images In Next.js For SEO-friendly Media https://ehsaantech.com/optimizing-images-in-next-js-for-seo-friendly-media/ Thu, 15 Feb 2024 09:20:20 +0000 https://ehsaantech.com/?p=3538 Services Full Stack Development QA & Automation Mobile App Development Cloud and DevOps UIUX MVP development Company About CASE STUDIES Blogs X Contact Us In the visually-driven world of the internet, images play a pivotal role in engaging users and conveying information. However, optimizing images for Next.js applications goes beyond just aesthetics—it significantly impacts your […]

The post Optimizing Images In Next.js For SEO-friendly Media appeared first on Tech Startup.

]]>

Optimizing Images In Next.js For SEO-friendly Media

In the visually-driven world of the internet, images play a pivotal role in engaging users and conveying information. However, optimizing images for Next.js applications goes beyond just aesthetics—it significantly impacts your site’s performance and SEO. In this comprehensive guide, we’ll delve into the art of optimizing images for Next.js, ensuring that your media not only looks great but also boosts your website’s search engine rankings.In today’s fast-paced digital world, users expect websites to load quickly and smoothly. If a website takes too long to load due to unoptimized images, visitors are more likely to abandon it and seek alternatives. This high bounce rate can signal to search engines that your content isn’t meeting user expectations, which might result in diminished search engine rankings.

Let’s dive in

1. Choosing the Right Image Format
When optimizing images, choosing the right format is crucial. Next.js supports various formats such as JPEG, PNG, and WebP. For instance, let’s say you have a product image named “product.jpg”

2. Resizing and Scaling Techniques

Responsive images are a cornerstone of modern web design. With the rise in mobile device usage, creating a seamless experience for mobile users is crucial. Optimized images play a vital role in ensuring that your website is mobile-friendly and loads quickly on smartphones and tablets. Google’s mobile-first indexing also considers mobile user experience when ranking websites. Next.js’s Image component handles resizing for you, but you can enhance it using breakpoints:

3. Image Compression Strategies

Reducing image file sizes is key to faster load times. You can use tools like imagemin or next-optimized-images to compress images during build:

4. SEO-friendly Image Filenames and Alt Text

Choose descriptive filenames and provide meaningful alt text for accessibility and SEO:

5. Implementing Lazy Loading for Improved Performance

Search engines rely on web crawlers to index the content of websites. Slow-loading or unoptimized images can hinder the crawling process, making it harder for search engines to understand and index your content accurately. Properly optimized images ensure that search engine crawlers can efficiently process your site’s content.Lazy loading defers offscreen image loading, enhancing performance. Next.js’s Image component supports lazy loading out of the box:

So, optimizing images for Next.js goes beyond aesthetics, it’s about improving page speed, user experience, and SEO. By applying these strategies and utilizing Next.js’s features, you’ll create visually appealing, SEO-friendly images that elevate your site’s performance and drive organic traffic. Remember, the careful balance of image quality and performance is the key to success in the digital era.

In pursuing advanced technology and personalized development, we are driven by the need to improve businesses and maximize their digital impact.

The post Optimizing Images In Next.js For SEO-friendly Media appeared first on Tech Startup.

]]>
React 18: Automatic Batching https://ehsaantech.com/react-18-automatic-batching/ Mon, 12 Feb 2024 10:16:07 +0000 https://ehsaantech.com/?p=3463 Services Full Stack Development QA & Automation Mobile App Development Cloud and DevOps UIUX MVP development Company About CASE STUDIES Blogs X Contact Us Batching is when React groups multiple state updates into a single re-render for better performance. For example, if you have two state updates inside of the same click event, React has […]

The post React 18: Automatic Batching appeared first on Tech Startup.

]]>

React 18: Automatic Batching

Batching is when React groups multiple state updates into a single re-render for better performance.

For example, if you have two state updates inside of the same click event, React has always batched these into one re-render. If you run the following code, you’ll see that every time you click, React only performs a single render although you set the state twice:

In React 18, all updates will be automatically batched, no matter where they originate from.

This means that updates inside of timeouts, promises, native event handlers or any other event will batch the same way as updates inside of React events. We expect this to result in less work rendering, and therefore better performance in your applications by avoiding unnecessary re-renders and thus improve the performance.

How to opt out of batching?

flushSync is a method in React that allows you to force a synchronous update to a component. It can be used in cases where you need to update a component immediately, rather than waiting for the next render cycle. This can be useful for cases such as updating a component’s state in response to a user interaction, or for doing some other type of imperative update.

Additionally, flushSync is not recommended to use in most cases, it’s better to rely on React’s built-in mechanism to handle updates. It’s only recommended to use in cases where you need to update a component immediately, and the regular way of updating component is not working.

In pursuing advanced technology and personalized development, we are driven by the need to improve businesses and maximize their digital impact.

The post React 18: Automatic Batching appeared first on Tech Startup.

]]>
React Suspense for data fetching https://ehsaantech.com/react-suspense-for-data-fetching/ Mon, 12 Feb 2024 07:30:41 +0000 https://ehsaantech.com/?p=3402 Services Full Stack Development QA & Automation Mobile App Development Cloud and DevOps UIUX MVP development Company About CASE STUDIES Blogs X Contact Us In React 18 there is a new feature called Suspense that lets you declaratively wait for anything including data. Suspense is not a state management system like Redux. It merely enables declarative fallback rendering while […]

The post React Suspense for data fetching appeared first on Tech Startup.

]]>

React Suspense for data fetching

In React 18 there is a new feature called Suspense that lets you declaratively wait for anything including data. Suspense is not a state management system like Redux. It merely enables declarative fallback rendering while a component waits for an asynchronous operation (such as a network request) to be finished. It allows us to synchronize loading states across different components which allows for a better user experience.

How To Use Suspense

Let’s compare the implementation of the conventional conditional rendering method against Suspense to see how it works.


This method is generally called “fetch-on-render” because fetching doesn’t start until the component has been rendered.
Now let’s see how this example would be rewritten using React Suspense.



In the code block above, the Weather component is wrapped with a Suspense component which contains a fallback prop. This means that when the component Weather is waiting for an asynchronous operation,React will render “loading…” to the DOM instead.The Weather component is then rendered only after the promises and APIs are resolved.

In pursuing advanced technology and personalized development, we are driven by the need to improve businesses and maximize their digital impact.

The post React Suspense for data fetching appeared first on Tech Startup.

]]>