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: Testing
Testing Accessibility Features With Playwright cover image

Testing Accessibility Features With Playwright

Discover how Playwright can help ensure accessibility in your applications. This article demonstrates how to use Playwright for testing keyboard navigation and identifying accessibility regressions before production....

Does Replay Fix All ​​Debugging Issues? cover image

Does Replay Fix All ​​Debugging Issues?

Rob Ocel and Adam Barrett talk with Jason Laster, CEO and co-founder of Replay. For those of you who are unfamiliar, Replay is an innovative browser development tool that is revolutionizing the way developers approach time travel debugging and bug fixing. This episode highlights all the reasons why Replay is such an amazing tool and all the problems it solves for developers. Jason shares the background on where the concept of time travel debugging came from, and how it actually works in Replay. The idea that you can capture a bug once and replay it as many times as needed enables developers to zoom in and identify the root cause of the issue. This approach saves infinite time, as you no longer have to rely on guesswork or spend hours reproducing bugs. Download this podcast episode here!...

Testing a Fastify app with the NodeJS test runner cover image

Testing a Fastify app with the NodeJS test runner

ant to simplify your testing process? Our new blog post on Node.js' built-in test runner is a great place to start. Learn how to test Fastify apps, including practical examples for testing an API server and SQL plugins....

 E2E Testing Basics with Playwright cover image

E2E Testing Basics with Playwright

End-to-end (E2E) testing is a crucial piece of the application testing puzzle. E2E testing generally refers to testing your application as an entire system as opposed to testing it in small isolated pieces like unit tests. This post introduces Playwright, a powerful E2E testing framework that offers APIs in several different programming languages. Before we dive in, let's take a high-level look at some of its most noteworthy features. - Component testing - This post is specifically about E2E tests but being able to test your components in isolation with the same framework is a really nice feature. - Incredible flexibility - Headless and headed test modes - Multiple browsers (Chromium, Firefox, WebKit), and mobile device testing environments - API is available in several different languages - Single-page and multi-page app testing - Project config supports running particular sets of tests against specific browsers and environments - Multiple browser contexts - Useful for testing multiple sessions or user accounts simultaneously - Parallel test execution - Runs tests in parallel by default - Test Generation - You can interact with your web app UI in the headed Playwright browser and have it generate selectors and test code for you. We won’t touch on it in this article, but you can learn more about it here - Debugging - Has built-in support for debugging Playwright in Practice In this post, we will reference a fictional web application with authentication that includes user login and profile setup flows to illustrate how you can use Playwright to test an application. Here is the directory structure for our tests: ` Playwright configuration playwright.config.ts is where you can specify various options and features for your testing setup. The projects option is where things get really interesting. You can use projects to configure different sets of tests to run on different browsers and devices. We can add tags to our test description to target particular tests for specific projects. For example, we can tag particular tests with @firefox and configure a project that only runs it against the Firefox browser. This might be useful for testing against regressions for a browser specific bug. We are also able to match against file names. In the project config below, we are ignoring tests with .mobile in the filename in all of our projects except the one that is mobile-specific. Here are some reference pages for some of the features, and config options covered here: - - - ` The webServer option allows specifying a web server for server-rendered and API servers. You can provide a command to start the server, and Playwright will wait for it to be ready before running your tests. Artifacts and Fixtures In addition to the models and specs directories, we also have an artifacts directory and a fixtures directory. The artifacts directory is used to store any artifacts generated during tests, such as screenshots or videos. Playwright can automatically take screenshots or videos of test runs, and these will be saved in the artifacts directory. The fixtures directory, on the other hand, contains any static data that might be needed during tests, such as images or data files. For example, in our auth-flow tests, we use an avatar image stored in the fixtures directory to simulate a user uploading an avatar image during the profile setup process. Selectors and Basic Test Writing In Playwright, we use selectors to target and interact with specific elements on a page. Playwright supports a wide range of selector engines, including CSS, XPath, and text-based selectors. You can also create custom selectors to suit your specific testing needs. When writing tests, we typically use the page.locator() method to target a specific element using a selector. For instance, you can use CSS selectors to target elements by their class, ID, or attributes. Here's an example that demonstrates how to use selectors to interact with a simple login form: ` In this example, we used CSS selectors to target the email and password input fields and a text-based selector to locate the login button. We can call methods, such as fill() and click(), that simulate user interactions and verify that the application behaves as expected. If you want to learn more on this topic, check out the writing tests page of the documentation. Page Object Models One pattern that Playwright recommends in its documentation is called Page Object Models. A page object model is a design pattern for organizing tests in a way that makes them more maintainable and encapsulates reusable logic. The basic idea is to define a set of classes that represent the pages and components of your web application, and then use these classes in your tests to interact with the application. For testing our applications, auth flows we might add a auth-flow.ts file. We can define an AuthFlow class that represents the authentication flow of our web application. This class encapsulates all the logic for requesting magic links, creating user accounts, and clicking links in the email sent to the user. By defining this class, we can write more readable and maintainable tests that use the AuthFlow class to perform the necessary actions. We accept a page argument in our constructor. This is a special argument that is always available in the browser context of our tests. It allows us to interact with the page via selectors and other easy to use APIs. There is a dedicated page in the documentation for this special object. ` Specs Finally, let's take a look at the specs directory. This directory contains the actual test files that use the AuthFlow class to perform the authentication and profile setup flows. new-user.spec.ts For example, the new-user.spec.ts file contains a test that verifies that a new user can complete the authentication flow, and be successfully redirected. In this example, we use the test.describe.serial test annotation to run the tests one after the other, since the second (sign-out) test depends on the user being logged in. (By default, Playwright runs as many tests as it can in parallel). We use test.beforeAll to run setup code (creating a magic link and user account) and test.afterAll to run any cleanup at the end of the tests. One of the first things you’ll notice is the callback functions that we pass to the Playwright test methods like beforeAll get called with an object argument that includes things like browser and baseURL. The browser object provides an API to the actual browser that our tests are running in, and we can use it to create and open new pages like we do in the first couple of lines of the beforeAll below. ` profile-setup.spec.ts Next, we have a profile-setup.spec.ts file that contains a test that verifies that the profile setup form can be filled out and changes can be successfully saved. Tests similar to this will be pretty common in most web applications. Luckily Playwright’s API and selectors make it pretty easy. We are able to test form accessibility here by trying both clicking and tabbing to the next fields. ` sign-in.spec.ts And finally, we have a sign-in.spec.ts file that contains a test that verifies that the sign-in modal can be opened and a magic link can be sent. ` Once you get familiar with the API, and the tools that Playwright makes available to you, writing tests for your application becomes pretty easy… and dare I say… fun? Summary There is so much more that we can cover when it comes to Playwright because it’s such a fantastic and powerful tool. Hopefully, this served as a good introduction to help you get started writing some basic E2E tests for your application. We covered some good ground after the intro by looking at some of the configuration options Playwright provides, and then writing some example tests for a fictional authentication flow. Our page object model implementation provided a nice abstraction for working with our app’s authentication mechanisms. Please keep in mind that this is not a prescription for how you need to write or structure your tests. The specific setup in this post is more to serve as a guide and a way to introduce some of the features and ways to start writing some tests. The most important part is that you can meet your application testing goals, and enjoy your time building out your tests!...

How to Create Better Test Coverage Using Cypress 10 cover image

How to Create Better Test Coverage Using Cypress 10

Testing is an integral part of software development, and it is important that all developers learn best testing practices. Jordan Powell, DX engineer at Cypress and Angular Google Developer Expert, has some tips to share with developers on how to write better tests using Cypress 10. In this article, we will take a look at Powell’s tips for writing end-to-end tests, component tests, and advanced testing patterns in Cypress. If you want to learn more from Jordan Powell, please check out his Advanced Cypress JS Drop training. Table of Contents - Why is Testing important? - Types of Testing - A new take on the testing pyramid - Differences between end-to-end testing and component testing - Jordan Powell’s best practices for E2E testing - Don’t use HTML Native selectors - Use Closures - Independent Test - Use Route Aliases - Setting a Global baseUrl - Jordan Powell’s Best Practices for Component Testing - Default Config Mount - Cypress Intercept - Use createOutputSpy - Jordan Powell’s Advanced Cypress Patterns - Session - Origin - Conclusion Why is Testing important? Software testing identifies issues within the application, and helps ensure that only high quality products are shipped to the user. Here are Jordan Powell’s reasons on why testing is important, and how it helps developers: Documentation: Good testing coverage will result in developers creating stronger test plans and better QA testing for new releases. Confidence: Writing good tests allows developers to build new features in confidence because the applications are working as intended. Safe Refactoring: Good test coverage leads to less refactoring down the road, and provides developers more time to work on new features. Improved UX: Good test coverage provides better UX (User Experience) for the end user because the application is working as intended. Types of Testing E2E, Integration, and Unit testing are three common methods for testing software applications. Unit Test: Unit testing serves as the foundation of the test pyramid. If you're working in a functional language, a unit will most likely be a single function. Your unit tests will call a function with different parameters and ensure that it returns the expected values. In an object-oriented language, a unit can range from a single method to an entire class. Integration test: Integration testing is where individual components of your application are tested as a group. End-to-end testing: E2E Testing is a technique that tests your app from the web browser through to the back end of your application, as well as testing integrations with third-party APIs and services. These types of tests are great at making sure your entire app is functioning as a cohesive whole. A new take on the testing pyramid In Jordan Powell’s Advanced Cypress JS Drop training, he challenges developers to rethink the traditional testing pyramid, and believes that component testing should also be included. Component Testing with Cypress 10 allows developers to test individual components quickly, regardless of its complexity. Component tests differ from end-to-end tests in that instead of visiting a URL to pull up an entire app, a component can be "mounted" and tested on its own. Differences between end-to-end testing and component testing Here are a few key differences between End-to-end and component testing: | End-to-end testing | Component testing | | ------------------------------------------------------- | ------------------------------------------------------------------------ | | The entire application and all of its layers are tested | Only the independent components are tested | | Testing can be done by developers and QA Teams | Testing is done by the developers | | Often requires a complex setup | No extra configuration for CI(Continuous Integration) environments needed | | Initialization command: cy.visit(url) | Initialization command: cy.mount() | Jordan Powell’s best practices for E2E testing Don’t use HTML Native selectors It is not good practice to use element selectors, id attributes, or class attributes when writing End-to-end tests. Using HTML Native selectors can lead to team members refactoring tests later on, or changing attributes which could affect the tests. Jordan Powell recommends using data attributes that can inform the team that this is a test attribute. When other team members need to change anything, they will be aware of the function of the attribute and what it may affect. Use Closures Jordan warns against assigned return values for Cypress assertions, and recommends using closures to access the Commands yield like this: ` Independent Test It is not good practice to combine related tests. Jordan Powell suggests that tests should be run independently from one another without sharing or relying on other test states. If test suites are related in any way, run the related properties or methods before each of the test runs, like in the code below: ` Use Route Aliases Another recommended practice is to use route aliases to guard Cypress against proceeding until an explicit condition is met. ` Setting a Global baseUrl It is bad practice to use hardcoded URL strings for the baseUrl because it will eventually fail when the environment changes. Instead, Powell recommends using a config file that holds the environment baseUrl. Jordan Powell’s Best Practices for Component Testing All of the code examples in this next section will be for Angular, but Cypress component testing works for all major Frontend JavaScript frameworks. Default Config Mount Component testing takes two parameters: the component to mount, and the object for configuration. A Custom Mount Config can boost flexibility. It ships a default mount config which you can use, but to manage multiple modules and import without adding too many boilerplate codes, it is recommended to have a custom mount config for specific instances. ` Cypress Intercept Component testing handles the individual components you are testing at a particular time, to access external API it is recommended to use cy.intercept. According to the Doc Cy.intercept can be used to passively listen for matching routes without manipulating the request or its response in any way. ` Use createOutputSpy When working with eventEmitter for components that may contain forms or other elements with events, createOutputSpy will automatically create an EventEmitter and set up the spy on it's .emit() method. ` Jordan Powell’s Advanced Cypress Patterns Session When testing for routes or components that require authentication Cypress provides cy.session which eliminates creating functions in your test to check for sessions on every call to the route or component. cy.session caches the sessions, and it will skip the login process for testing components that need the sessions on a second call. ` Origin Running tests for projects that require a visit to multiple different domains could get CORS, or a limitation of visits, due to browser environment. Cypress provides Origin to help bypass some of the browser limitations. ` Conclusion In this article, we looked at Jordan Powell’s tips for writing End-to-end tests, component tests, and advanced testing patterns in Cypress. I recommend watching the full video for Jordan Powell’s Advanced Cypress JS Drop training. Are you excited about the Cypress Component Testing? Let us know on Twitter....

Mocking REST API in Unit Test Using MSW cover image

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....

How to Create a Custom Login Command with Cypress, React, & Auth0 cover image

How to Create a Custom Login Command with Cypress, React, & Auth0

Auth0 is a tool for handling user authentication and account management. Cypress is a tool for writing end to end tests for your application. Getting these two technologies to work together can have a few gotchas, especially if your application is set up to have the end to end tests in a separate folder from your frontend code. Today, we’ll go over the steps you’ll need to implement so you can have a custom Cypress command to log in a user, and also let your front end code continue to work safely! --- Setup For this setup, we're making the choice to keep our end to end tests in one folder, and our front end code in a sibling folder. You don't have to do it this way. It's just the choice we've made for this project. So our folder setup has two root level folders, "cypress" and "app": ` --- React Adjustments Auth0 provides a default login form for you to use. We’ll focus on the fact that the forms use web workers to store the user’s access tokens in memory. This helps them keep that access token more secure from attackers. This is important to note for Cypress. But because Cypress does not have a way to interact with that web worker. So we need to be able to detect when our application is running the site through Cypress so we can adjust how we get the access token. We’ll need to update the way our Auth0 form saves that token based on if our app is running normally, or if it’s running through Cypress. To do this, we can add a check to the cacheLocation prop in our Auth0Provider field that wraps around our root app component. app/index.ts ` > Important note if you’re using TypeScript: > If your project is using TypeScript, there will be two more small changes you might need to make. > First, your editor may be yelling at you that it doesn’t know what Cypress means, or that it doesn’t exist on the window interface. So you can make a type file to solve this. src/types/globals.d.ts ` > Then, in the root level tsconfig file, we need to add an option to the compilerOptions section so it knows to look for this file we just made and use it. Then your editor should be happy! :) app/tsconfig.ts ` And that’s all your front end code should need to work! It’ll continue to work as expected when running your app locally or in production. But now when you run your Cypress tests, it’ll store that access token in local storage instead, so we can make use of that within our tests. --- Cypress Adjustments Now we can make our custom login command! Having a custom command for something like logging in a user that might need to be repeated before each step is super helpful. It makes it faster for your tests to get started, and doesn’t need to rely on the exact state of your UI so any UI changes you might make won’t affect this command. There’s a few different things we’ll need to handle here: - Writing the custom command itself - Making an e2e file where we’ll set up this command to run before each test - Updating the Cypress config file to know about the environment variables we’ll need - If you’re using TypeScript, you’ll also need to make a separate “namespace” file and an index file to pull all the pieces together. We’ll start with the meat of the project: making that custom command! I’ll share the whole command first. Then we’ll walk through the different sections individually to cover what’s going on with each part. The Custom Command Cypress automatically sets up a support folder for you, so you’ll likely already find a commands file in there. This will go in that file. If you don’t have it, you can create it! cypress/support/commands.ts ` The first piece to note is line 2. Cypress.Commands.add('loginWithAuth0', (username, password) => {... This is what actually tells Cypress “hey, this is a command you can use”. The name can be anything you want. I’m using “loginWithAuth0”, but you could call it “login” or “kitty” or whatever makes the most sense for your project. Just make sure you know what it means! :) Lines 3-6 are setting our the environment variables that the Auth0 call will use. Then, on line 8, we use Cypress to make the actual request to Auth0 that allows us to log in. For this use case, we’re choosing to login with a username and password, so we tell the call that we’re using the “password” type and send all the necessary environment variables for the call to work. (You can find info on what these values should be from the Auth0 docs.) Then, on lines 20 and 21, we’re starting to deal with the response we get back. If the call was successful, this should contain the information on the test user we just signed in and the access token we need for them. So we extract those values from the body of the response so we can use them. On line 22, we again use Cypress to get the browser’s window, and let us store the user access token. We'll use localStorage for this as seen on line 23. Important note here! Pay extra special attention to the way the string is set up that we’re storing in localStorage on line 24! Auth0 needs the access token to be stored in this specific manner. This is the only way it will find our token! So make sure yours is set up the same way. The rest of the code here is taking the information we got from the Auth0 call and adding it to our new localStorage value. You’ll see that on line 35 we’re parsing the user information so we have access to that, and then setting an expiration on line 40 so the token won’t last forever. And that’s it - our command is set up! Now on to the rest of the things we need to set up so we can actually use it. :) Supporting Files If you have commands that should be run before every test call, you can create an e2e file in your support folder. These are your global imports and functions that will apply to all of your Cypress test files. Here we’ll import our custom commands file and actually call our new command in a beforeEach hook, passing in the test username and password we want to use. cypress/support/e2e.ts ` > TypeScript Note: > To get the typings to work properly for your custom commands, you’ll need to do two things. > First, you’ll want to make a new file called namespace in your “support” folder. Then, you’ll want to declare the Cypress namespace in there, and set up a line for your new custom command so Cypress knows the type for it. (If you originally edited the default Cypress commands file, you’ll also want to go to the bottom of that file and remove the namespace section from it - this is replacing that.) ` > Then in your support folder, create an “index.ts” file and add your commands and namespace imports to it. ` > That should clear up any TypeScript related warnings in your files! The final piece is updating our Cypress configuration file. We need to add all the environment variables we need in here so Cypress is aware of them and we don’t have them hard coded in our files. cypress.config.ts ` Wrap Up With that in place, you should be good to go! Whenever you run your Cypress tests now, you should see that a user is automatically logged in for you so you start on the first page of your app. We hope this helps! If you run into any issues or have questions on anything, please feel free to reach out to us. Leave a comment on this post or ask in our Discord. We’ll be happy to help!...

Mocking HTTP requests with Mock Service Worker cover image

Mocking HTTP requests with Mock Service Worker

Mock service worker is a fantastic tool for mocking network requests (supports REST and GraphQL requests)....

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....

Testing Vue Composables with Jest cover image

Testing Vue Composables with Jest

In this post, we will take a look at how to test Vue composables with Jest. What Are Composables? When developing large scale frontend applications, we reuse logic for repetitive tasks. With composables, we are able to resuse logic in a stateful manner with the help of the composition API. Testing For this example, we create a composable to handle changes in screen size. Depending on how complex your composable is, you can simply test the reactivity directly or load it into a wrapper component, and then test the wrapper component. ` Let's write the following tests for this composable. - check currect value of screen size - check currect value of screen size after resize event is fired To test that the resize event changes the current value when fired, we need to load our composable in a component. ` From the implementation we completed above, the core logic of our breakpoint method is in an external function called "composable", and we can simply reuse it across our frontend code. Any manipulation to the state of a composable should be done directly within the composable to avoid bugs and make it easier to read. I hope this article has been helpful. If you have any questions or run into any trouble, feel free to reach out on Twitter or Github....

Writing and Visually Debugging Tests with Jest Preview cover image

Writing and Visually Debugging Tests with Jest Preview

Testing is critical when building an industry-grade application, working on a large code base, building anything that many users will use, or just adding employable skills to your belt. Front end testing has become more complex over the years. Front-end developers now need to test the visual aspects of an application by testing end-to-end, testing components interacting with other components and the application, and unit testing individual parts of the application. Keeping track of activities such as click events, user interactions with forms, and loading states of the application in the browser while being able to see changes to the application during testing is difficult to achieve. On top of that, performing debugging at the same time becomes almost impossible. For the majority of us developers, debugging and tracking of tests or errors in the application are mostly achieved by scrolling through the codebase or errors in the console, relying only on the imaginative concept of what the UI components are at the time of testing. Fortunately, Jest Preview is here to save the day! Jest Preview Jest Preview is an open-source package for debugging jest tests in the browser, giving developers the visual state of the application while testing. Jest-preview works with jest and react-testing-library by default. For jest-preview to render the application, it initiates a server and serves the HTML in a browser. This allows you to visualize the application’s UI. This makes it easier to track and debug the jest tests. Features of Jest Preview Some key features of Jest Preview - Preview your actual app's HTML in a browser in milliseconds. - Auto reload browser when execute preview.debug(). - CSS Support: - Direct CSS import - Number of CSS-in-JS libraries, such as: - Styled-components - Emotion - Global CSS - CSS Modules - Sass - Support for viewing images. You can use Jest Preview with any testing libraries and frontend framework. Check out some examples of how to test with framework To see jest-preview in action we are going to build a simple application with tests, and use Jest preview to test our application. The Application We will be creating a click and count React application: ` Before we run the application, lets install a dependency: ` Since we used create-react-app, you must run the command: npx jest-preview config-cra Here is sample code for our application: ` Then our test will look something like this: ` Let’s trigger a click event: ` Edit the package.json file, and add the following to the start object: ` Running the tests: First, run your tests, and then run your jest-preview command. You could also add a concurrently running script, with a package like node-run-all: ` Then, edit the package.json file. ` Now run the command: ` Conclusion In this article you learned to use jest-preview which helps in tracking and debugging tests for frontend applications. Hopefully you have learned how easy it is to visually debug your tests and projects in the browser with Jest preview! Jest preview makes it easier to track all the steps of a test. You may also find that writing tests becomes more fun! Will you be using jest-preview for your next project?...

Cypress 10 - The Latest Release Details - Component Testing, Configuration Options cover image

Cypress 10 - The Latest Release Details - Component Testing, Configuration Options

Cypress 10 was recently released with some long awaited features and bug fixes! In this article, I will talk about some of the exciting features in the latest releases of 10.3.0, 10.2.0 and 10.1.0. Some of these features include component testing, changes to the Cypress configuration file, a new design for Cypress Onboarding UI Design, enabling Cypress natively for Apple silicon and Linux ARM64 and AArch64 systems, and adding live test data into the Cypress Dashboard! Critical features of Cypress 10 Cypress 10 release was announced on June 2022. This was a feature-packed release with many community-request features like component testing, TypeScript improvements, improved onboarding experience, improved error messages, Cypress configuration files, and more. To learn more, check out ChangeLog for a detailed list. Component Testing Let’s start with component testing. Component testing is directly integrated into the main Cypress application. Testing applications to achieve full coverage could be done using many approaches. Major web frameworks focus on breaking applications into components to create a complex functional component. Component testing allows you to test components independently in isolation, and focuses on the functionality of the particular component providing more focused coverage. End-to-end testing focuses on testing the entire application to ensure the application runs as expected while unit testing breaks down the application into smaller individual units of functions, methods, or modules tested in isolation. Unit testing provides little interaction between components and the application, which tends to make debugging difficult. The new Cypress 10 component testing provides component interaction between other components and the entire application. This is rendered in a real browser providing access to dev tools, and making debugging a lot easier during tests. To learn more about component testing, check out GitHub Issue #21111. To learn more about Cypress 10 and other included features, you can check out the announcement blog. Cypress Config File To provide a flexible and extensible configuration option for testing, Cypress 10 now supports multiple configuration file types, including TypeScript, CommonJS, or ESM Module configuration, and drop the cypress.json configuration file. The Cypress configuration file can be cypress.config.js, cypress.config.ts, cypress.config.cjs, or cypress.config.mjs file. 20643. A configuration file is required in a project. Running cypress open will walk you through to set up your Cypress project with specific testing options for your project. 20643. Cypress Onboarding UI Design Project set up for Cypress 10 now takes you through a beautiful UI, built with Vue. Running cypress open renders the on-boarding UI with specific instructions for your test configuration, and allows you to choose between end-to-end testing or component testing. Cypress 10.2.0 A minor version release of Cypress 10.2.0 was announced on Jun 21, 2022. This release focuses on machine compatibility for Apple and Linux distros. Cypress is now available natively on Apple silicon. This means no extra system configuration with emulators, and approximately 2.5x faster testing environment on Apple devices including M1 and M2. 19908 20686 Cypress is now natively available on ARM64 and AArch64 systems running Linux 22252. To learn more about the 10.2.0 release read Cypress 10.2.0: Run tests up to 2x faster on Apple silicon (M1) Cypress 10.3.0 A minor version release of Cypress 10.3.0 was announced on Jun 28, 2022. This version focuses on improving the cloud testing developer experience workflow. Cypress added actionable test data in the Cypress Dashboard from the test runs. Cypress Dashboard is a service by Cypress to provide access to recorded test results when running Cypress tests from a CI provider, giving insight to the tests which helps with tracking and debugging. With Cypress 10.3.0, test result data are directly retrieved and cached whenever possible to provide real-time metrics for test coverage. New columns include #21250: Latest runs to monitor, run, and fix tests locally within CI workflows. Average duration to help quickly identify and take action to improve the performance. To learn more check out Cypress 10.3.0: Speed up testing workflows with improved visibility into your test results Conclusion What do you think of these new features and the latest release? Make sure to read the ChangeLogs for a complete list of features in the releases including bug fixes. To start using the latest Cypress, run npm install cypress@latest --save-dev from your browser....