Skip to content

This Dot Blog

This Dot provides teams with technical leaders who bring deep knowledge of the web platform. We help teams set new standards, and deliver results predictably.

Newest First
Tags:Storybook
Mocking API on Storybook using MSW cover image

Mocking API on Storybook using MSW

In this blog, you will learn how to mock APIs on Storybook using MSW. This blog will assume you have your project setup with either GraphQL, or a REST API like Axios or Fetch API and also will assume you have Storybook installed in your project. We will be covering how to mock for both GraphQL and REST API. In this project, we will use Vue and our UI tool. But don't worry. The sample code will work for whichever framework you choose. What is MSW? MSW(Mock Service Worker) is an API mocking library that uses Service Worker API to intercept actual requests. Why Mock? Mocking helps us avoid making an actual HTTP request by using a mock server and a service worker. This, in turn, prevents any form of break in case something goes wrong with the server you would have sent a request to. What is a Mock Server? A mock server is simply a fake server that works as a real server to help users test and check APIs . It imitates a real API server by returning the mock API responses to the API requests. You can ream more here. What is a Service Worker? A Service worker enable communication between the application, the browser, and the networks (if netwrok is available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests, and take appropriate action based on whether the network is available or not. You can learn more about Service Worker API here. Use Cases Enough of all the stories 😃. Now we will be looking at two use cases: - GraphQL - REST API We will need to install some pulig ins to maximize what msw has to offer by running one of these commands in the root directory of the project: Installing MSW and the addon ` Generate a service worker for MSW in your public folder. ` Replace the placeholder with the relative path to your server's public directory. For example, the Vue command will be: ` You can check here to see what path your framework will use. Note: If you already use MSW in your project, you have likely done this before, so you can skip this step. Configuring Storybook In your .storybook/preview.js file, add this: ` You also want to ensure that your GraphQL set up is initialized in this .storybook/preview.js file if you are using Apollo Client. Creating our mock API Lets create where our mocking will be happening by first creating mock folder in the src folder. Create a data.ts file in the mock folder, and add this code, which will serve as our fake response. ` Create a mockedPost.ts file and add this code. ` Create a mockedUserProfile.ts file and add this code. ` The concept of interception comes into place with these mocked files. For example, if there is any request outside of the mocked request, msw won't mock it. So every API url or query we want to mock must correspond to the component that's data you are trying to mock, regardless of if the API url is authentic or not. Create a handlers.ts file and add this code. Handlers allow us to have multiple request, no matter its method [POST, GET]... ` How do we make use of the Handler? I created two components to test for our two use cases - Card - Posts Card component - Create a Card folder in your component folder. - Create a Card.vue and add this snippet ` - create an index.ts and add this code ` - create Card.stories.ts and add this code ` below is the UI expectation Posts component - Create a Posts folder in your component folder. - Create a Posts.vue and add this snippet ` - create an index.ts and add this code ` - create Posts.stories.ts and add this code ` below is the UI expectation Code Explanation We created a card and posts component that is making use of certain query/API call to get data. msw has a property handlers which accepts an array of requests, giving us the ability to add as many requests as we want provided that they are in the component. Overview Of the UI Below is an overview of the UI, which brings together the components: Whewww!!! 😌 Why mock? - You want test without hitting the actual API - Yhe API isn't yet avaible from the backend team. - During development to reduce dependencies between teams. - To accelerate third parties API integration. - during functional and integration testing. - to test various advanced scenarios more easily. - for demonstration purposes. Conclusion If you have any issues, we provided a repo which you can use as a template if you want to start a new project with the setup and use it to practice. Please let me know if you have any issues or questions, and also contributions are welcome....

Storybook: Can Your Next Project Benefit from It? cover image

Storybook: Can Your Next Project Benefit from It?

I will show you what Storybook is all about and hopefully help you decide if you need it in your next project. Don't worry if you have limited experience as an engineer because you don't need to have an advanced technical background to make use of Storybook. What is Storybook? Storybook is a tool for developing UIs that allows you to work on one component at a time. What is a component? A component is smallest part of a UI. In chemistry, we refer to it as an atom(_Smallest unit of a matter_). Most frameworks are now components based. Why Storybook? Storybook allows you to actually develop the entire UIs without starting the major application. But in order to cleary state why one would choose to use it, lets look at some benefits and challenges of Storybook. Benefits - Being able to build components in isolation,and not having to think about integrations or other systems running in your stack is a blessing - A clearer vision of your components styling and layout - Navigating between UI component as you get to see all component as a sidebar item - Communicating with other devs. It really allows you to show how your new component is supposed to be used and which features it boasts. - You can manipulate props value - Its is not framework agnostic i.e you can use for Vue, React, Angular, etc. - Great for documenting Challenges - If you’re integrating it into an existing project, there is some migration work to be done. - You rely on addons and decorators for handling data. - It can take up a lot of time to maintain and properly set up. - It takes team commitment to keep it updated and ensure everything still works. What are add-ons actually? Add-ons are plugins that can be added to make certain feature work. For example, by default scss doesn't work on Storybook, so you will have to install an add-on to make it work as expected. When to use Storybook In this section, we will the making use of This Dot Labs' Open source project starter.dev as a case study. starter.dev is built using a variety of technologies to demonstrate architectural patterns and best practices using these tools. This project uses these technologies like Vue, React, Nextjs, Angular, etc to show various ways Github can be implemented!. Lets Pick a component from starter.dev GitHub Showcases to demonstrate the features Storybook has. Every conponent has a control tab that allows us to manipulte the props if there be any. For example: Here, looking at the image with the props, you will notice some properties: - cardType: This is a dropdown/select option with two opions issue and pullrequest. - state: this defines the state of the card - author: the person who created it or a name, or whatever, you get the point. Lets change some of the props and see the result - cardType will be pullrequest - state will be closed Here, we can see there has been a change. This is so helpful, and tells the team members what the component can and can't do. Other features Looking at other interesting features like - Settings Here, we can toggle for feature like side nav, the controls (which, in the dropdown option, is call addons) - Responsiveness There are few options that help us test for responsivess. Below, you will find an image showing those options: Here we can select any option to see the responsiveness of that component. Large screen Mobile screen Hover state of the card - Inspection Here, we can see certain properties like padding, and current width and height Looking to get started To get started, all you need is to visit this sites based on your prefered technology - Storybook with Vue - Storybook with React - Storybook with Angular - Storybook with Web Components - Storybook with Web Svelte - Storybook with Web Preact - Storybook with Web Ember Conclusion It's up to you to decide if Storybook helps you achieve your goals faster, or if you think it's useful for your project setup. It's important to look at what it could offer and what it can't. You can decide to use it for just plain documentation or for components, or both....

Storybook 6.5 - Key Features to Note cover image

Storybook 6.5 - Key Features to Note

Storybook is an open-source tool for building UI components and pages in isolation. It allows you to work on one component at a time. You can develop entire UIs without needing to start up a complex dev stack, force certain data into your database, or navigate around your application. Storybook 6.5 was recently released and it comes with exciting features highlighted in this article. Support for the Latest Popular Javascript Libraries and Frameworks Support for Angular and React Out of the Box Storybook 6.5 supports React 18 and Angular 14 out of the box. When you run your React project for the first time, it will auto-detect the React version and use the new root API if it detects it on React 18. Check out #17215. Figma Plugin With Storybook 6.5, you can easily compare design specs and different implementations with the help of the Figma plugin’s Storybook Connect which embeds stories into the Figma workspace. This plugin allows developers to interact with the Figma design using a link created by the Figma plugin between the stories and designs. Check out more here. Interaction Testing Storybook Interaction Testing allows developers to write tests for your application in the story file itself. The tests execute in the browser, and you can get a GUI to visualize and debug them. Under the hood, it is powered by Jest, Playwright, and a testing library, giving you the familiarity of testing the application. Check out Integrated Test. Webpack 5 Lazy Compilation Lazy Compilation is a feature that only calls the content of a page when it is needed, and delays every other content until a route to the content is called. Storybook 6.5 only compiles the core runtime, and builds stories as you visit them. This enables the developer to quickly spin-up stories, and rebuild larger Storybooks. Learn more about Storybook Lazy Compilation Other features Storybook support for Vite Builder has been improved with instant rebuild of stories, and have officially been brought into Storybook's core. There were also improvements to accessibility features for Storybook and UI design features for stories. Wrap Up Storybook 6.5 offers a number of features and out of the box support for both React and Angular, making this release among the most exciting for this open source UI tool: Figma’s Storybook Connect embeds stories into the Figma workspace. Write tests for your application in the story file itself with Storybook Interaction Testing. Webpack 5 Lazy Compilation calls the content of a page when it is needed, and delays every other content until a route to the content is called. If you get a chance to try out Storybook yourself, please let us know by tweeting us at @ThisDotMedia!...

How to Set Up Storybook in VueJS cover image

How to Set Up Storybook in VueJS

How to setup Storybook in VueJS In this post, we will take a look at how to setup storybook in our VueJS application. What is Storybook? Storybook is a tool for developing UI components / libraries faster and in isolation. Storybook is an excellent addition to a project development cycle as it allows you to work on one component at a time and develop entire UIs without needing to start up a complex dev stack, force certain data into your database, or navigate around your application. It can also be used to write a documentation (story) of what each component does: for the parameters it accepts, the event it emits and response to expect. A story describes a component in a specified state. You'd want to write a story for each state a component can have, such as active, inactive, loading. Storybook will then let you preview the component in its specified state in an interactive component library. Setup our Project Let’s start by creating our VueJS project. We would be using yarn for package management. Using Vue CLI >Install Vue CLI if you don't already have it installed. ` >Create vue app ` >Enter 'your-app' folder ` Add storybook ` >Add Storybook to package.json ` -p command refers to the port number where the Storybook will be run. -c command refers to the config directory. -s command refers to directory to load static / public files >run the following command, we should now see storybook running on port :9001 ` Let's Configure Storybook in our VueJS project As a best practice, Storybook configuration should be stored in a directory called .storybook. Create .storybook directory as the config directory in the project root ` Next lets create our config file Create main.js inside our .storybook folder ` The main configuration file main.js controls the behaviour of the Storybook server. - stories - an array of globs that describes the location of your story files, relative to main.js. This makes the maintenance of the main.js file much easier by keeping it highly focused on the configuration of Storybook rather than its implementation. You can require as many stories as you need. - addons - a list of all the addons you are using (we will be describing what addons are as we go). - babel - custom babel configuration. Note: you must always restart the Storybook’s process when you modify the main.js so as to update it. Our folder structure should look like this: Let's write a story for a button component First, let's write our custom button component - ../src/component/button.vue ` Let's write stories inside ./src/stories/button.stories.js ` Addons are plugins in Storybook used to perform advanced functionalities on components. Examples are actions, knobs etc. - The actions addon is used to display data received by an event handler (callback) arguments in your stories. - The knobs addon allows you to dynamically interact with a component’s args (inputs). Experiment with alternate configurations of the component to discover edge cases. Update our main.js file. Now let's add the path from main.js to our stories folder: ` >Let's stop our storybook server and run it again ` Now if we click on the button we would notice that there's a log of the event under actions in our storybook. If we click on the knobs tab, we would be able to edit the values that our component accepts and see how they change in realtime. Conclusion Yes! We've been able to setup Storybook in VueJS and have also built a simple button component to test out knobs and actions. For more complex examples like using Vuex store in stories, check out Using Storybook with VueJS. If you have any questions or run into any trouble, feel free to reach out on Twitter or Github....

Mixing Storybook with Angular with a Sprinkle of Applitools cover image

Mixing Storybook with Angular with a Sprinkle of Applitools

To better understand the Applitools Storybook SDK for Angular, we will be building a small Angular application from scratch, adding some Storybook stories, and then finally performing visual regression testing using the Applitools SDK to generate snapshots for us to view and analyze. You can find the source code for this article on GitHub by following this link storybook-angular-applitools repo. Create Angular 7 App using the latest CLI Make sure you have the latest Angular CLI installed. In my case, I will be using the Angular CLI v7.0.2. Create a new Angular App using the following npm command: ng new storybook-angular-applitools Create the ContentEditable Component The ContentEditable component we are going to build in this section wraps an HTML element and adds an HTML attribute of contenteditable=”true”. The component implements the ControlValueAccessor so that the component can be used like any other Angular form control inside HTML forms. This is an editable paragraph. The HTML fragment above renders in the browser as an editable area that users can click and enter any text or HTML. Create a new component file and add the following markup to contenteditable.component.html file: Next, add the code below to the contenteditable.component.ts file: ` The component is straightforward and follows the best practices in building a ControlValueAccessor. It defines a single @Input() property to allow the consumer of this component to control its styling. If you want to fully understand how ControlValueAccessor works in Angular check out Max’s article titled Never again be confused when implementing ControlValueAccessor in Angular. Next, add the following HTML snippet to the app.component.html file: Two-way Data-binding { content1 | json } Define the styles() method inside the AppComponent class: styles() { return { "background-color": "yellow", margin: "10px auto", "max-width": "60%", "line-height": "25px", padding: "10px" }; } And now run the application. You should see something similar to this below. You can start typing in the yellow editable rectangle and you will see whatever you type underneath. Let’s switch gears and add Storybook to the application. Add Storybook packages We need to add Storybook for Angular to your application. The Storybook website offers a detailed installation guide on Storybook for Angular. Once installed, apply the following changes, so that Storybook runs correctly with your Angular 7 application. Open the src/app/tsconfig.app.json file and make sure the exclude property has the following values: ` Open the .storybook/tsconfig.json file and paste the following: ` Create and run a few Storybook stories Add the following Storybook stories into the file located at src/app/stories/index.stories.ts: ` The first story renders the ContentEditable component with a yellow background. While the second renders the component with a red background. Run the Storybook tool to view and test your stories by issuing the following CLI command: npm run storybook You should be able to see something similar to this: Now that we are sure the Storybook stories are up and running, let’s set up Applitools to use these stories and run our visual automated tests. Add and run Applitools Storybook SDK for Angular To add Applitools Storybook SDK for Angular to this application issue the following CLI command: npm install @applitools/eyes.storybook --save-dev Make sure to grab an Applitool API Key and store it on your machine. For a complete tutorial on how to install and run Applitools Storybook SDK for Angular, you may check this link: Storybook Angular Tutorial. To run the Storybook stories and send the snapshots to the Applitools Server, issue the following command: npx eyes-storybook The command simply opens the Storybook stories, runs them one by one, and then sends all the DOM snapshots to the Applitools Server. Let’s have a look at the test results inside Applitools Test Manager. Review test results on Applitools Test Manager We can see the results of the tests we just ran from the Applitools Test Manager. To access the Applitools Test Manager, navigate to https://www.applitools.com. Sign in to get onto the Dashboard. For a detailed look at the Applitools Test Manager, you can check my article on Applitools — The automated visual regression testing framework The results for running the Storybook tests show the following: The test manager lists the test runs or batches (as referred to by Applitools) on the left- hand side. Clicking on any of the batches displays all of the snapshots for all of the Storybook stories in your application. Click on the first snapshot (the red color) to expand and review it in detail: A rich toolbox is available to zoom in/out on the snapshot and compare this snapshot to any previously taken, known as the baseline. In this case, since this is the first time we are running the stories, there won’t be any baseline set. Therefore, Applitools Test Manager sets these snapshots as a baseline for upcoming regression test cycles. Next, we’re going to simulate what happens when we have a visual regression in one of our components. To do this most easily, we’ll change one of our Storybook stories to render our component in a way that will be different from the baseline images we took earlier. Then, when we re-run the visual testing, we should see a discrepancy appear that we’ll have to resolve. To do this, let’s assume that the story named in the red background above, has the ngModel value changed and now reads as follows: ` Now run this command: npx eyes-storybook The command gives you a detailed test result every time you run it. Check the following results: Using @applitools/eyes.storybook version 2.1.9. √ Storybook was started √ Reading stories √ Done 2 stories out of 2 [EYES: TEST RESULTS]: ContentEditable Component: with yellow background [1024x768] — Passed ContentEditable Component: with red background [1024x768] — Failed 1 of 1 A total of 1 difference was found. See details at https://eyes.applitools.com/app/test-results/00000251861893628194?accountId=D9XKRBVuYUmBxXpWWWsB3g~ Total time: 36 seconds Running the second story fails, as expected because we changed the content that was initially displayed inside the ContentEditable component. The test result output provides you with a link to check the discrepancies online. Click on the link to open the issues directly in the Applitools Test Manager: A new batch is displayed on the left-hand side with a status of Unresolved. The Unresolved status indicates that the Applitools Test Manager discovered a discrepancy between the two test runs. This will require your input in order to resolve the discrepancy. Either approve the difference, and create a new baseline, or reject it to keep the original baseline. Notice the blue square above indicating the Not Equal sign. This means the second snapshot test run has some differences to the first test run snapshot (the baseline). Clicking on the first snapshot reveals the differences between both snapshots. The current one and the baseline. The differences in content are highlighted in blue. You can also compare the new snapshot with the baseline by selecting both: This should display both side by side and all differences are highlighted for you. You may spend more time at the Applitools Test Manager to explore all the rich features provided for you to do a thorough analysis on running the story tests. Conclusion This article touched the surface on how you can mix together Storybook and Angular together in one application. By means of Applitools Storybook SDK for Angular, you can provide automated visual UI testing by running the Storybook stories and generate snapshots that are then sent to the Applitools AI Server to compare and analyze and prepare the test results for you. You can grab the code for this article by cloning the repository on GitHub....