Developer Insights
Join millions of viewers! Our engineers craft human-written articles solving real-world problems weekly. Enjoy fresh technical content and numerous interviews featuring modern web advancements with industry leaders and open-source authors.
Detect Hand Sign Languages with Tensorflow
Interested in learning how to use Tensorflow to detect hand sign languages in your apps? By the end of this read, you will know how to implement Tensorflow in your application with very simple steps. In our example today, we will be using Vue. What is Tensorflow? Tensorflow is an end-to-end platform _(meaning: delivering complex systems or services in functional form after developing it from beginning to end.)_ used for building Machine Learning applications, and it is also open-source. TensorFlow enables you to build dataflow graphs and structures to define how data moves through a graph by taking inputs as a multi-dimensional array called Tensor. You can read more on Tensorflow here. What is a Model? A model is a function with learnable parameters that maps an input to an output. A well-trained model will provide an accurate mapping from the input to the desired output. Tensorflow Models Tensorflow models are pre-trained models, and there are four defined categories of them: - Vision: Analyze features in images and videos. - Body: Detect key points and poses on the face, hands, and body with models from MediPipe - Text: Enable NLP in your web app using the power of BERT and other Transformer encoder architectures. - Audio: Classify audio to detect sounds. If you want to go into more detail, check out Tensorflow Models. All these models are broken down into subs and for our case, we will be making use of the Body Model which has the hand pose detection we need in order to detect the hand signs. Hand Pose Detection This model used a 2D and 3D multi-dimensional array which enables it to predict the keypoints of the hands. Example of a 2D is [[1,2],[3,5],[7,8],[20,44]] and that of a 3D is [[1,2,5],[3,5,8],[7,8,6],[20,44,100]]. This hand pose detection is a model from the MediPipe as we established above, and it provides us with two model types which are lite and full. The accuracy of the prediction increases from lite to full while the inference speed reduces, i.e. the response time will be slower as the accuracy increases. What do we need? There are a few dependencies we need to get things working, and I also will be assuming that you have your project set up as well. You will need to add these dependencies to the project ` Above, in the commands, you will notice we added a fingerpose. Let's talk a little about what we need the figerpose for. Fingerpose Fingerpose is a gesture classifier for hand landmarks detected by Mediapipe hand pose detection. It also allows you to add your own hand gesture, which means that a gesture that signifies the letter Z can signify Hello based on your fingerpose data. We will see an example of how the data looks in a bit. You can check out fingerpose for more details. Get started We are going to use Vue for this illustration. We will start by looking at the HTML first, and then we will cover the JavaScript. Our Template will be a basic HTML that will have a video tag so we can show a video after getting access to our webcam. Template ` The snippet above shows a div and a video tab. The video is used when we gain access to the webcam. We will now be writing the JS required to initialize the webcam. Script ` We imported two methods from vue: onMounted and ref. The onMounted runs when the page is fully mounted while the ref is used to declare a reactive value to reference the video element. If you look at the video tag in the template, you will notice a ref property. You can check out Template ref and onMounted lifecycle hook. In the openCam function, we first try to test if mediaDevices is available on your browser navigation. >The MediaDevices interface provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data. This MediaDevice has a method getUserMedia which prompts the user for permission to use a media input. You can find all you need to know about getUserMedia here. From the snippet, we can see that getUserMedia returns a promise, and with that, we can get the media stream as a response using then(). We check if the video element has srcObject or not. If it does we assign the media stream to the srcObject and if not, we convert the media stream to a URL and assign it to the src of the video element. With this Snippet and with a few style, you should have your video showing your awesome face! Introducing Tensorflow and Hand Detection Now that we got our webcam working, we will update the Template and the script in order to detect, predict, and display the alphabet based on the hand sign prediction. The updated HTML should now look like this: ` The div with class name alphabet will display the alphabet based on the hand sign prediction. We will be introducing two(2) new functions, createDetectionInstance and handleSignDetection. Firstly, lets begin with the createDetectionInstance which is an integral part of the hand sign detection and then we will introduce handleSignDetection which predicts and displays the hand sign. ` To be able to detect hand poses, we need to create an instance of the handpose detector, and here, we created a function createDetectionInstance which is an asynchronous function. You can check out this Tensorflow blog to see more details. Now that we have created an avenue to detect hand signs, let us start detecting the hand. In that light, we will be adding a handleSignDetection function. ` The handleSignDetection runs after creating the detection instance. We have a setInterval that runs every 2 seconds (PS: _the 2 seconds timing is arbitrary and can be less or more_) to check if there is any hand sign. We also have a conditional statement to ensure the video element exists, and the detection instance was created accordingly. So, the detector calls a method estimateHands, which tries to predict the hand pose by getting keypoints with values that are either in 2D or 3D (Multi-dimensional Array). If you check your console log, you will see an array of data if any hand pose is detected. Now that we can detect hand poses, we will now add fingerpose that will help predict and display the alphabet based on the hand sign. ` Assuming that our detector sensed a hand, it is time to match this value based on the hand signs we created with the fingerpose. The landmark variable is a 3D array pulled from the hand result's keypoint3D key value. There is also a keypoint as well, which is a 2D value, and both will give the same result. Now, using GE.estimate, we can generate a possible gesture that matches the sign, and a score/confidence is assigned to each gesture pending the amount of gesture predicted. So, the gesture with the highest score/confidence is selected since it is estimated to be the closest to the hand sign from the figerpose hand signs we created. We also imported Handsigns and its content looks like this: You can also get the handsigns folder from the 100-ms-vue repository. Looking at the screenshot, there is a GestureDescription instance that takes a string A which will represent what the hand sign will stand for. So, it could be anything you want the handsign to stand for. >onMounted is asynchronous because we need to ensure that our detection instance is created, which is required to detect the hand sign. With the updated code, you should be able to display some letters. Conclusion Don't forget, you can see in detail how this was implemented in one of This Dot Labs' open source projects 100-ms-vue. Please note that what we did is just a basic implementation, and to have a production-ready version, it will need a bigger model, and a more complex detection to be able to identify hand sign language....
Jul 12, 2023
7 mins
How To Authenticate Your SolidJS Routes With Solid Router
In this post, we will talk about how we can authenticate our SolidJS route with Solid Router. By the end of this article, we will understand what authentication is, and how it is used to guard routes in SolidJS using the Solid Router. Overview Route authentication has been around for a while, and is now a fundamental part of many applications like Facebook, Gmail, and Instagram. At this point, it’s about as ubiquitous as entering a password into a phone. Authentication through route guards in SolidJS can be achieved in two different ways. The first that we are going to cover in this app is the use of a Solid Router. The second is provided by Solid Start, which is more like a folder-based routing. It is a meta-framework (a framework built on another framework). At its core, it's powered by SolidJS and Solid Router. This article assumes that you have already set up a SolidJS project, and will not walk through that part of the process. If you have not yet spun up a project, you can find tutorials and instructions at SolidJS. What is Authentication? Authentication is a process of verifying the identity of the user. It provides access control to check if the user is authenticated. Authentication enables organizations to keep their networks secure by permitting only authenticated users or processes to gain access to their protected resources which, in our case, is the route in the application. To learn more about authentication, you can check out the following; - Authentication By Mary E. Shacklett - Authentication By Auth0 - Authentication By Wiki What is a route guard? A route guard helps to prevent unauthenticated users from accessing certain routes/parts in an application. For example, an app lock on a mobile phone can be seen as a guard. You may be able to access the phone and some apps, but you can’t access other apps. We can also use parental controls on the phone, internet, and so on as a type of guard. You can read more about route guard. Get Started If you haven't installed the Solid Router in your project, run the command below: ` Solid Router is a universal router for SolidJS which works whether you're rendering on the client or the server. It was inspired by and combines the paradigms of React Router and the Ember Router. To read more, check out Solid Router Having installed @SolidJS/router, we will be creating the following files; - Home: *src/pages/Home.jsx* - Signin: *src/pages/Signin.jsx* - Pricing: *src/pages/Pricing.jsx* - RouteGuard: *src/RouteGuard/index.jsx* - Header: *src/components/Header/index.jsx* - Header styles: *src/components/Header/Header.module.css* Terminologies - useNavigate: a library provided to us by SolidJS Router that is used to navigate. - createEffect: creates a listener, which calls it's first argument when attached signals change. - Outlet: serves as the children associated with RouteGuard wrapper - NavLink: used to navigate between pages just like a tag which takes a property href for the page route path. Home page Below is the code we will paste in our home page file. But if you already have a content for this, you don't have to change it. ` This is just a simple page component with a style imported at the top. Signin page This is the content of our sign in page, but if have a content already, that's fine. The most important contents are the logIn function and the createEffect. ` The logIn function will be called when the login button is clicked. When clicked, a hardcoded token is saved in the session storage. The user is then navigated to the home page, which by default, can only be accessed if the user has been authenticated. The createEffect ensures the authenticated user won't access the sign in page. Pricing page This is just another page which, in this project, represents another protected page that could only be accessed by an authenticated user. ` This is just a simple page component with a style imported at the top. RouteGuard Component ` This serves as the wrapper for routes you want to protect from unauthenticated users. If there is no token in the session storage, the user will be routed to the signin page. Header component If you already have the content for the header file, you don't have to change it. All you need is the logOut function. ` Above, we have styles imported from the header CSS module, and we have a logOut function that is used to remove the token from the session storage and also navigate the user to the signin page. Header styles This is the style for the header component. ` Updates for src/App.jsx This file is where the route is managed, and where we grouped certain routes we wanna guard or protect from unauthenticated users. ` Update for src/App.module.css ` Updates for src/index.jsx We have to update this file by wrapping our App with Router ` Update for src/index.css ` Conclusion In this article, we were able to understand what authentication is, and how to create a route guard which is very important when trying to prevent certain users from accessing certain routes in our application. I hope we have been able to help you see the possibilities of making use of SolidJS and Solid Router to build a well-authenticated application. If you are having issues, you can check out the repo for SolidJS-route-guard. Don't forget that you can see, in detail, how this was maximized in one of This Dot's open source project starter.dev GitHub Showcases. Happy coding!...
Mar 6, 2023
4 mins
Mocking REST API in Unit Test Using MSW
Unit testing has become an integral part of application development, and in this discussion, we will be talking about mocking API while unit testing using MSW, a tool used for mocking APIs. We also won't be setting the test environment up since we expect you have already done so, and also we will be using a React project for our testing. Please note: the setup will work for any framework of your choice. What is MSW? MSW (Mock Service Worker) is an API mocking library that uses Service Worker API to intercept actual requests. Why Mock? Well, it avoids us making an actual HTTP request by leveraging on mock server, and a service worker which, in turn, prevents any form of break should something go wrong with the server you would have sent a request to. What is a Mock Server? A mock server imitates a real API server by returning the mock API responses to the API requests. This will help intercept the API request. You can read more here. Project Setup We will be installing few packges, and doing a little configuration. Installations We will be installing the following - msw: This package helps use to mock the API request and also helps us set up the server. - whatwg-fetch: Not always required, but what it does is it makes fetch available if you are useing the fetch API. Sometimes you get this: ` Creating the mock config Lets create a mock folder in our src folder to keep things organized. We want to have two files in the mock folder in this example: - postHandler.js: Here, we will have the handler that will help with intercepting the API. - serverSetup.js: Here we will set up or server that will house the handler. postHandler.js content Its important that the API url matches the url you intend to intercept: ` Lets explain the above code: posts: This is dummy data that is going to serve as our response data knowing full well what the data structure might look like. postHandler: This will serve as the handler, which will help in intercepting the request made to that url. serverSetUp.js content ` From the above code, the setupServer can take in any number of handlers separated by comma. The setupServer serves as our "fake" server where we can add as many handlers to intercept requests. Component Lets create a component for the purpose of our test. Here, I will be making use of the App.js file. My code will look like this: ` All we are doing is fetching some data from the URL when the component mounts and saving the data in our state to display them. And we are using the jsonplacehoder url to fetch posts. Test the component We will create a test file named App.spec.js with this contents ` We imported the component we want to test with: the whatwg-fetch to prevent us with the possible error we talked about. Then, we imported our server. There are few methods above: - beforeAll: This runs before all tests are executed. - afterAll: The opposite of beforeAll. - afterEach: As the name implies, it runs after each test. - resetHandler: It is a useful clean up mechanism between multiple test suites that leverage runtime request handlers. If you added another handler during a test, this resetHandler will remove that handler so that the next test will not know about it. You can see an example of reset handler. Though, in our code example, we didn't need it. But its important to know we have such control and power over what we want to do. So, in summary before all listen to the server for any request, after all close the server and after each test reset handler. On app render there is an API call, but our server will intercept it, so at first the loading text will exist. Then after, it won't. Will it work without intercepting? Yes it will. So, why do all of this? - Anything could happen to the API server, so you don't want you app test to fail. - The data could change, and we don't want a situation where the test fails because of data changes. Conclusion We have created a repo that you can test with in case you have issues following along. Please feel free to let us know what you think as we look forward to building a stronger community by sharing knowledge....
Dec 14, 2022
4 mins
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....
Nov 2, 2022
5 mins
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....
Oct 28, 2022
6 mins
How to Apply a Gradient Effect to Text with CSS
I will be taking us through some ways we can add gradient effect to text. This tutorial also assumes that you have an understanding of CSS and its properties like background, and background-color. Creating Gradient Effects Before we start creating gradient effect, let's understand a few concepts. What is gradient? Gradients let you display smooth transitions between two or more specified colors. You can read more about Gradient here. Linear Gradient Perhaps the most common and useful type of gradient is the linear-gradient(). The gradients “axis” can go from left-to-right, top-to-bottom, or at any angle you chose. Below, you will find a code example. You can read more about Linear Gradient. Radial Gradient Radial gradients differ from linear ones in that they start at a single point and emanate outwards. Gradients are often used to simulate a lighting, which as we know isn’t always straight. So they can be useful to make a gradient seem even more natural. Below you will find a code example: You can read more about Radial Gradient. Code We will be exploring various ways we can add gradients to text, but lets look at the CSS properties that can help us achieve this. - background - -webkit-background-clip - -webkit-text-fill-color Background The CSS background properties are used to add background effects for elements. More on CSS background. -webkit-background-clip The background-clip property defines how far the background (color or image) should extend within an element. More on CSS background clip. -webkit-text-fill-color The text-fill-color property specifies the fill color of characters of the text. If this property is not specified, the value of the color property is used. The text-fill-color and the color properties are the same, but the text-fill-color takes precedence over the color if the two have different values. More on CSS Text fill color. Full Gradient What we mean here is applying gradient effect on the entire text. In our code sample we used both radial and linear gradient. Partial Gradient What we mean here is applying gradient effect to some part of the text. In our code sample, we used both radial and linear gradient. There are various ways to go about this depending on what you wish to achieve. First Concept This concept involves us first applying the gradient to the entire text, then targeting the part on the text we dont wnat the gradient to affect by wrapping that part of the text with any tag of your choice. But in our case, we used span tag. ` Second Concept This concept involves us giving the entire text a color using the css color property, and then giving the part of the text, we want to apply the gradient effect by wrapping the part of the text with any tag of your choice. But in our case, we used span tag. ` _The code snipet below shows the examples in full and can be practiced with_ Source Code If you have any issue at all, here is a link to the git repository Text gradient effect....
Sep 26, 2022
3 mins
State Management with Apollo Client and Vue using Reactive Variable
State Management is an integral part of Software development with tools like VueX, Pinia which is like VueX 5, Redux, Context API, and others. In our example, we will be using Vue3 composition API, a bit of TypeScript. This article will assume that you already have a project setup with Apollo. State Managemnet Before we dive into what state management is and what it offers, lets understand few thing which are integral to it. What is State? State is a part of an application, such as user details, usernames, login information, and website themes(dark or light). In simple terms, state is like a warehouse that's contents you can access when you need to from wherever you are. What is State Management? State Management is just simply a design pattern to help synchronize the state of the application throughout all of the components in the application. This also prevents us from passing too many props accross the application. When to implement State Management: - When the application contains large number of components. - To prevent redundant data, knowing well some other components might need that data. - Prevent passing props across the application, making it messy. For more explainations, you can check the links below: - What does state-management even mean and why does it matter in Front End Web Development with frameworks like React or Vue? by Sean Grogg - What does state-management even mean and why does it matter in Front End Web Development with frameworks like React or Vue? by Robert Polevoi - State management by Tom Nolle How to implement State management? There are so many ways to do it. But in this discussion, we will be implementing it with Vue Apollo. Apollo Client It is the client for Vue Apollo. It helps to easily integrate GraphQL queries and mutation in your application which, in our case, is Vue. Reactive Variables This is a new feature from Apollo Client 3. > Reactive variables are a useful mechanism for representing local state outside of the Apollo Client cache. How to create a Reactive variable in Apollo? This is quite simple since Apollo client provides us with makeVar. ` What the above code means is we make use of makeVar to create a variable of any type be it boolean, number, array, or object. Also, by calling the variable that makeVar is assigned to without passing a parameter will only output its current value, but passing a parameter will update its value. You can learn more about makeVar here. Setup of the Project We will be creating a state for a counter that does increment, decrement, or reset. But first, let's set up our enviroment. Setting up the Reactive variable Lets create our reactive variable in ./variables/counts.js: ` Configuring the cache Lets also update our cache config to something like this: ` Creating a component Let's create ./components/Counter.vue component: ` Please note that you can always get the counts value even without the GraphQL query. All you need to do is call count() like the example about _Reactive variables_, and force a re-render using loading as a ref. Like this: ` loading ref to help re-render when there is a change so as to get the latest value of counts. The manner you will prefer depends on what you want to achieve. But I will go with the example with the query as it still preserves the GraphQL feel. Conclusion State Management with Apollo Client saves you the stress of installing VueX, or Redux (for the React users), as long as the application makes use of Apollo. In this quick training, we learned about state and why state management is important to building and maintaining applications. Further, we learned how to manage state by using a reactive variable in Apollo. If you need any help understanding how to use this training, or additional clarification, please feel free to reach out to me....
Jul 27, 2022
3 mins
Getting Started with Vue and Vitest
I will be taking us through some steps to get you started with Vue and Vitest. This walk-through will assume that you have an understanding of how unit testing works, so lets dive in! What is Vitest? Vitest is a unit-test framework by Anthony Fu and Jessica Sachs, who are on the Vue Core Team. It is powered by Vite, and can also be used with React, Svelte, Lit and more. Similarities between Jest and Vitest If you write Jest, using Vitest will feel very natural. The only major difference is that, with Vitest, you don't have the methods readily available until you import them. Why Vitest? - It is very fast - It has hot reload out of the box. You don't have to add extra watch flags since it does that by default. - happy-dom or jsdom for DOM mocking - Out-of-box TypeScript / JSX support - Components testing for Vue, React, Svelte, Lit and more - Read more here. Migration It's easy to migrate from Jest to Vitest, all you need to do is follow the setup here. Setup the Project I will assume you already have Vue CLI installed on your machine, which helps you set up the application without needing to do so many configurations yourself. If you don't have the Vue CLI installed yet, just run this command: ` Create the project Having installed the Vue CLI, you can go to the folder where you want to create the application and run: ` Installing dependencies & configurations Now it's time for us to add Vitest to the project. Please Ensure you are in the project directory before running this next command. ` You will also need to add some plugins to the project. - @vitejs/plugin-vue: Helps vitest know which framework to use. In our case, we are using Vue. Read More. - jsdom: gives us access to the DOM while testing. Read More. - @vue/test-utils: gives us access to methods like mount and shallowMount. Read More. You can add them by running this command in the project root directory. ` In your package.json file, add the following to the script: ` This will enable you to run the test commands. Next, we will create a vitest.config.ts file in our root directory and add this code: ` Create a component Now lets create a component HelloWorld.vue in the components folder and add this code to it: ` Creating your test environment Create a test folder. Inside that folder, create a file e.g example.spec.ts, and in this file add this code: ` Code explanation With Vite, you will have to import the methods used for testing like describe, expect, test, it, and so on. In the code above, we are testing for two things: - The content on the page. - The value of the prop passed, which in our case is _message_. This means that it's possiblle for the prop value to be correct, but the content of the page wrong. If, for example, we update our Home.vue content template tag to be this... ` ... this will fail, and can only pass if we add 'Something' as part of the prop value that we pass. Now try running this command: ` Conclusion Kudos to Anthony Fu, Jessica Sachs of the Vite team for this amazing job well done. I strongly believe that Vitest will probably become the industry standard just like Vite. Feel free to let us know what you think....
Jul 11, 2022
3 mins
Let's innovate together!
We're ready to be your trusted technical partners in your digital innovation journey.
Whether it's modernization or custom software solutions, our team of experts can guide you through best practices and how to build scalable, performant software that lasts.