“Great UI is the cornerstone of successful businesses, representing the pinnacle of user experience and design excellence.”
When discussing business growth in 2024, various metrics and goals come into play. However, one aspect is often overlooked: the user interface (UI) of software that users interact with. While building the perfect UI, angular developers may face a multitude of challenges in isolating and showcasing UI components. Such challenges can lead to – inefficiencies in development, longer time-to-market, and bad user experience.
Is there a solution?
Of course, there is but before that, you must know the importance of UI component development and testing in isolation.
Significance of Developing and Testing UI Components in Isolation
Developing and testing UI components in isolation is crucial for these reasons:
- It allows focused development, enabling developers to concentrate on a specific component without being influenced by the entire application. This isolation aids in more efficient debugging and faster development cycles.
- Isolated testing ensures that a UI component functions correctly on its own, reducing the likelihood of unexpected behavior when integrated into the larger application. This approach enhances code maintainability and makes it easier to identify and fix issues early in the development process.
- Additionally, testing components independently promotes reusability, as well-tested and modular components can be effortlessly integrated into various parts of the application or reused across projects. This not only saves development time but also contributes to a more consistent and cohesive user interface.
Learn how we implemented UI Test Automation for an Angular-based application, resulting in a remarkable 90% reduction in manual testing efforts for a client.
Now, let’s get deeper into this blog and explore the solution that not only addresses the challenge of isolation but also offers additional benefits.
Storybook: An Overview & The Solution
In the context of Angular, a storybook is a tool used for developing and showcasing UI components in isolation. It provides a sandbox environment where developers can build, test, and document individual components independently, promoting modular and scalable front-end development.
Using Storybook in Angular projects offers several benefits. Such as:
- Isolated Component Development: Storybook allows developers to work on Angular components in isolation, promoting focused development and efficient testing without needing to navigate the entire application.
- Documentation and Showcase: It serves as a visual documentation for components, making it easier for developers to understand their usage and variations. It also acts as a showcase, providing a centralized location for viewing and interacting with components.
- Rapid Prototyping: With Storybook, developers can quickly prototype and iterate over UI components, facilitating a faster design and development process. It accelerates the feedback loop and ensures a more responsive development workflow.
- Enhanced Collaboration: It promotes collaboration by offering a shared space where designers, developers, and other stakeholders can review and interact with components independently of the main application. This fosters better communication and understanding of the UI elements.
- Regression Testing: As components are tested in isolation, Storybook helps catch regressions early in the development cycle, ensuring that changes to one component do not negatively impact others. This practice enhances the reliability and stability of the application.
Excited about using Storybook in Angular? Let me guide you through setting up this tool and gaining hands-on experience as we progress.
Getting Started with Storybook in Angular
To install Storybook in an Angular project using the Angular CLI, follow these steps:
1. Install Angular CLI: If you haven’t installed Angular CLI, do so by running the following command in your terminal:
npm install -g @angular/cli
2. Create a new Angular project: Generate a new Angular project using the Angular CLI:
ng new your-angular-project
3. Navigate to the project directory: Change into the project directory using:
cd your-angular-project
4. Install Storybook CLI: Install the Storybook CLI using the following command:
npx storybook@latest init
5. Follow the prompts: The Storybook CLI will guide you through the setup process. Choose the framework (Angular), and let it install the necessary dependencies.
6. Start Storybook: After the setup is complete, start Storybook by running:
npx ng run your-angular-project:storybook
This will launch Storybook in your browser, and you can view your components and stories.
Fig: Angular Terminal
7. View your stories: With Storybook running, navigate to `http://localhost:6006` in your browser to see and interact with your Angular component stories.
Fig: Storybook Dashboard
Onwards to knowing the folders that get created when Storybook is installed!
Folder Structure
The image below illustrates the creation of Storybook, including all the folders:
Fig: Folder Structure
- .storybook: This folder typically contains configuration files and settings specific to Storybook, a tool used for developing UI components in isolation. Here’s a breakdown of the contents you might find in this folder:
-
- main.js: This file is the main configuration file for Storybook. It defines the core settings for your Storybook instance, such as where to find your stories, addons configuration, webpack configuration, etc. You can customize various aspects of Storybook behavior here.
- preview.js: The preview configuration file allows you to tweak settings related to how your stories are displayed in the Storybook UI. You can use this file to add global decorators, parameters, or configure the viewport.
- tsconfig.json: If you need to customize webpack configurations for Storybook, you can create or modify this file. It allows you to extend or override the default webpack configuration used by Storybook.
- stories: This folder houses individual Storybook stories, containing isolated examples or scenarios showcasing the behavior and appearance of Angular components or pages within the Storybook environment.
Let’s dive into the real work! I’ll guide you through creating your own stories to enhance visualization and interaction while working with Angular Components.
Creating Stories for Angular Components
Follow these steps to create stories:
Step 1: Create an Image card Component
To begin, let’s create a basic Angular component that functions as a card for displaying content, such as images or text on html and typescript.
a. For image.component.html:
<div class="d-flex align-items-center justify-content-center mt-5"> <div class="card h-100" style="width: 50rem"> <img [ngStyle]="{ opacity: imgOpacity }" src="{{ imgSrc }}" alt="{{ altTxt }}" /> <div class="card-body" *ngIf="figCaptionTxt && figCaptionTxt.trim().length > 0" > <figcaption> {{ figCaptionTxt }} </figcaption> </div> </div> </div>
b. For image.component.ts:
import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-image', templateUrl: './image.component.html', styleUrls: ['./image.component.scss'], }) export class ImageComponent implements OnInit { @Input() imgSrc: string = 'Your Image URL'; @Input() altTxt?: string = 'Pondicherry French Hotel'; @Input() figCaptionTxt?: string = ‘Image caption’ @Input() imgOpacity?: number = 1; constructor() {} ngOnInit(): void {} }
Step 2: Create stories
To begin creating stories for Angular components in Storybook, go to the specific stories folder in your project folder and create an image.stories.ts file.
For Image.stories.ts:
import { Meta, StoryObj } from '@storybook/angular'; import { ImageComponent } from '../app/image/image.component'; const meta: Meta<ImageComponent> = { title: 'Image/Image Component', component: ImageComponent, tags: ['autodocs'], }; export default meta; type Story = StoryObj<ImageComponent>;
To simplify and help you understand stories, I’ve created four examples that you can implement in the above code. Let’s look at them:
Example 1: This example illustrates the component without a caption, allowing for cases where captions are not provided.
export const NoImageCaption: Story = { args: { figCaptionTxt: '', }, };
Fig: NoImageCaption
Example 2: This example demonstrates the component with a descriptive caption, which is useful when additional context or information is required for the image.
export const WithImageCaption: Story = { args: { figCaptionTxt: 'The French Quarter or White Town area in Pondicherry is filled with elegant colonial mansions in the midst of tree-lined boulevards, named on French streets beginning with "rue", numerous parks and charming cafés.', }, };
Fig: WithImageCaption
Example 3: This example displays the image with full opacity, providing a clear and vivid representation of the content.
export const WithFullOpacity: Story = { args: { imgOpacity: 1, }, };
Fig: WithFullOpacity
Example 4: This example presents the image with reduced opacity, suitable for scenarios where a translucent effect is desired for aesthetic or stylistic purposes.
export const WithHalfOpacity: Story = { args: { imgOpacity: 0.5, }, };
Fig: WithHalfOpacity
Step 3: Create story using play function for login page Interaction
a. Install Storybook’s addon-interactions:
npm install @storybook/testing-library @storybook/jest @storybook/addon-interactions --save-dev
b. Update your Storybook configuration (in .storybook/main.ts) to include the interactions addon.
addons: [ // Other Storybook addons '@storybook/addon-interactions', // Register the addon ],
c. Add the following code to your login.stories.ts file:
export const testLogin: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement); const emailInput = canvas.getByLabelText('Email address', { selector: 'input', }); await userEvent.type(emailInput, '[email protected]', { delay: 100, }); const passwordInput = canvas.getByLabelText('Password', { selector: 'input', }); await userEvent.type(passwordInput, 'ExamplePassword', { delay: 100, }); const submitButton = canvas.getByRole('button'); await userEvent.click(submitButton); }, };
This code snippet defines a Storybook story called “testLogin” that demonstrates the login functionality of a component. It interacts with input fields for email and password, and simulates a button click to test the login functionality in isolation.
Step 4: Run Storybook
To view all interactions, run Storybook and navigate to your interaction story in the “Interaction” tab.
Fig: Login page Interactions
Congratulations on successfully integrating Storybook with Angular! 😄
To streamline and organize all the processes we’ve covered, I have a special add-on recommendation for you before we conclude.
Storybook Addon for Documentation
The Docs addon is a fundamental tool for documenting components directly within Storybook. It allows you to create comprehensive documentation alongside your component stories, providing context, usage instructions, examples, and more.
Use this command to install Doc addon:
npm install @storybook/addon-docs
Here’s an overview of the add-on:
- Usage: You can document your components using Markdown or MDX syntax, writing detailed explanations, usage examples, and prop descriptions.
- Integration: Docs addon seamlessly integrates with your existing Storybook setup, allowing you to document components alongside their stories.
- Automatic Generation: The Docs addon automatically generates documentation based on your component stories, making it easy to keep your documentation up to date as your components evolve.
- Customization: You can customize the appearance and layout of your documentation using various configuration options provided by the Docs addon.
- Accessibility: Docs addon ensures that your documentation is accessible to all users, supporting screen readers and keyboard navigation.
- Examples: You can include usage examples and code snippets within your documentation to illustrate how to use your components in different scenarios.
In a nutshell, integrating Storybook with Angular offers significant benefits for developers by streamlining component development, facilitating collaboration across teams, and ensuring consistent user experiences.
The platform’s extensive ecosystem of addons, including the Docs addon for comprehensive component documentation, further enhances its versatility and usefulness in Angular projects.
So, start incorporating Storybook into Angular workflows and reach out to Nitor Infotech to build better software products.