Testing Vue 3 Applications with Mock Service Worker

Rate this content
Bookmark

In this talk, we will discuss some best practices for testing Vue 3 applications. We will explore how the Mock Service Worker and the Vue Testing Library can aid us in testing Vue 3 applications closer to a real-live user situation. Attendees will leave with a solid understanding of how to effectively test their Vue 3 applications to ensure reliability and maintainability.

FAQ

Mock Service Worker is used in testing V3 applications to simulate server responses, allowing developers to test how the application handles different server responses, including error cases, without needing to make actual API calls. This is particularly useful in continuous integration environments where accessing real APIs might be restricted.

In large applications with extensive API interactions, Mock Service Worker allows developers to create mock APIs and simulate various server responses. This helps ensure that all components of the application interact properly with the API, increasing code reliability and catching potential bugs early in the development cycle.

To set up Mock Service Worker in a Vue 3 application, start by creating a mock directory with JSON files representing mock server responses. Next, configure the Mock Service Worker in the testing environment, such as Vitest or Jest, by setting up handlers that return mock responses for specific API endpoints. Finally, integrate these settings into the test suite to begin testing with the mocked responses.

Yes, asynchronous components in Vue 3 can be effectively tested using Mock Service Worker by wrapping them in a Suspense component and using spies on fetch or Axios calls to simulate and manage async behavior. This setup allows for testing both successful and error responses from the API, ensuring the component handles all states correctly.

Mock Service Worker can simulate error responses by setting up error handlers that return specific HTTP status codes and error messages when certain API endpoints are called. This allows developers to test how the application reacts to and handles API failures, enhancing the robustness of error management within the application.

Mock Service Worker offers the capability to simulate various edge cases such as delayed API responses or custom error messages. By creating handlers that mimic these scenarios, developers can ensure that the application is resilient and performs well even under unusual or adverse conditions.

Lisi Linhart
Lisi Linhart
24 min
15 May, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This Talk discusses testing V3 applications with Mock Service Worker, which is a library that allows simulating server responses in tests. It covers setting up Mock Service Worker by creating mock API responses and connecting it with the application. The Talk also explains how to write unit tests for asynchronous components using Vue's suspense component. It demonstrates how to test components that interact with APIs and handle error responses. Additionally, it mentions the testing library for components without API calls and emphasizes the importance of testing component interactions and API integration.

1. Testing V3 Applications with Mock Service Worker

Short description:

Hi there. Today I'll talk about testing V3 applications with mux-serviceworker. We'll explore how to use V3 with mux-serviceworker to improve code quality and testing. Testing V3 applications is crucial for catching bugs early and increasing confidence in code. Mock Service Worker is a library that allows you to simulate server responses in tests, making it useful for large applications with API interactions. It's also great for running unit tests in a continuous integration environment. Let's look at an example using mock service worker in a Vue 3 app to mock API responses and test components that interact with the API.

Hi there. I want to tell you today about testing V3 applications with mux-serviceworker. I'm Lizzie. I'm a frontend architect at Storyblock. You can find me on Twitter, but most importantly, you can find all the examples that I made for this talk in this GitHub repository.

And let's dive right into it. So this talk is based a little bit on Harry Potter. And we will figure out how we can use V3 together with mux-serviceworker to improve our code quality and to test in a better and more integrated way.

So why is it important to test V3 applications? It's really crucial to perfecting your code, to making sure it's doing what it should. It can really help you to catch bugs before they go into production, because if you catch a bug in production, it's a lot more expensive. So the earlier you catch the bugs, the better. And it can really help to increase the confidence in your code and the code you're writing and also the code you're changing.

So what is Mock Service Worker? Mock Service Worker is a really nice library that you can install into your application and it allows you to simulate server responses in your tests. So you can create a mock API and you can test how actually your application is handling the responses of the server and also handle edge cases of server responses, which might return errors. Why would you use that? It's really important in large applications that have a lot of API interactions. So many large applications like Storyblock, they have a lot of API interaction and you want to make sure that all these different components, they're actually working as they should work with these different responses you can get from the API. It's also really nice if you run your unit tests in a continuous integration environment. For example, you run your unit tests in GitHub Actions, and inside of that continuous integration environment, you cannot call the API. So you need to mock the API and run the unit tests with actual mocked responses. And that's where using mock service worker is really nice.

All right, let's look at the example I built and how we can actually set it up. To start using mock service worker, you can start using it in a view 3 app. You need some kind of testing environment. So in this example, we'll be using vitest, but it works with Chest just the same. And you need mock service worker, which is the library that is in the core of this talk. So the example I built, it's showing my magical beasts. We have a headline. We have some cards with the USB stick, and we can click on those cards and see some more details of the magical beast. And all the content here, it's loaded from an API. So I have a story block space where I set up some content.

2. Setting up Mock Service Worker

Short description:

I have a page that has the headline and the different magical beast. I fetch the actual content from the Storyblocks API to show the details of the magical beast. To mock the API, I create a mock directory with JSON files that replicate the API responses. Then, I set up the mock service worker and handlers. This involves creating a setup file and connecting mock service worker with YDist.

I have a page that has the headline and the different magical beast. And then I can also see what's actually returned there. So through the API from story block, I get the actual content that I can then use to show my content, the same for the more specific pages. So I have a magical beast and then I have some content here that shows all the details of that magical beast.

All right. So let's start. The first thing for making a mock service worker setup is that you actually need some kind of API, you need some kind of asynchronous way of interaction. So in my example, I have a component that fetches, just does a simple fetch to Storyblocks API and that has all the responses. And then from that response, I build the actual page that we see. And the important part here is that now we need to mock the API. So our first step is to actually create a mock directory. In the root of our project, it could also be somewhere else, but I will do it in the root. And then we set up the mock service worker.

So what do I mean with a mock directory? If we look into the example, we have a folder there that's called mocks. And then we have two JSON files. So we have the beast JSON, that's the start page. And then we have the niffler JSON, that's a mock of the actual, more specific page. How can you get those JSONs? The simplest thing is to have your application, and then check in the network what is actually being returned by the API. So if we reload that, my mock here is basically this request and this response we have here. So the story, I could just copy that and paste that here into my beast JSON file. So this one is just a copy of what I had on that page. So that's really the first part, to have some mocks that can be used by the mock service worker, but also by other unit tests that might not need the mock service worker.

Then the next step is to actually set up mock service worker and to set up some handlers. So for setting up the mock service worker, we need to actually create a setup file. So in the white disk config, we can configure some setup files. So you will provide the path to the file that is setting up our testing environment. Then here in test setup, I have this index.js file that has my global testing setup. So that's the setup that is used in all the tests that I'm writing. I also have some other stuff here, but the important part is here, the mock service worker setup file, where I connect mock service worker with YDist. So before all, after all, and after each test, we're starting the server, we're closing the server, and then we're resetting the handles after each test.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

One Year Into Vue 3
Vue.js London Live 2021Vue.js London Live 2021
20 min
One Year Into Vue 3
Top Content
Vue 3 may still sound new to many users, but it's actually been released for over a year already. How did Vue 3 evolve during this period? Why did it take so long for the ecosystem to catch up? What did we learn from this process? What's coming next? We will discuss these questions in this talk!
Network Requests with Cypress
TestJS Summit 2021TestJS Summit 2021
33 min
Network Requests with Cypress
Top Content
Whether you're testing your UI or API, Cypress gives you all the tools needed to work with and manage network requests. This intermediate-level task demonstrates how to use the cy.request and cy.intercept commands to execute, spy on, and stub network requests while testing your application in the browser. Learn how the commands work as well as use cases for each, including best practices for testing and mocking your network requests.
Vue: Feature Updates
Vue.js London 2023Vue.js London 2023
44 min
Vue: Feature Updates
Top Content
The creator of Vue js gives an update on the new features of the technology.
Testing Pyramid Makes Little Sense, What We Can Use Instead
TestJS Summit 2021TestJS Summit 2021
38 min
Testing Pyramid Makes Little Sense, What We Can Use Instead
Top Content
Featured Video
Gleb Bahmutov
Roman Sandler
2 authors
The testing pyramid - the canonical shape of tests that defined what types of tests we need to write to make sure the app works - is ... obsolete. In this presentation, Roman Sandler and Gleb Bahmutov argue what the testing shape works better for today's web applications.
Full-Circle Testing With Cypress
TestJS Summit 2022TestJS Summit 2022
27 min
Full-Circle Testing With Cypress
Top Content
Cypress has taken the world by storm by brining an easy to use tool for end to end testing. It’s capabilities have proven to be be useful for creating stable tests for frontend applications. But end to end testing is just a small part of testing efforts. What about your API? What about your components? Well, in my talk I would like to show you how we can start with end-to-end tests, go deeper with component testing and then move up to testing our API, circ
Test Effective Development
TestJS Summit 2021TestJS Summit 2021
31 min
Test Effective Development
Top Content
Developers want to sleep tight knowing they didn't break production. Companies want to be efficient in order to meet their customer needs faster and to gain competitive advantage sooner. We ALL want to be cost effective... or shall I say... TEST EFFECTIVE!But how do we do that?Are the "unit" and "integration" terminology serves us right?Or is it time for a change? When should we use either strategy to maximize our "test effectiveness"?In this talk I'll show you a brand new way to think about cost effective testing with new strategies and new testing terms!It’s time to go DEEPER!

Workshops on related topic

Designing Effective Tests With React Testing Library
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Top Content
Featured Workshop
Josh Justice
Josh Justice
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn
Vue3: Modern Frontend App Development
Vue.js London Live 2021Vue.js London Live 2021
169 min
Vue3: Modern Frontend App Development
Top Content
Featured WorkshopFree
Mikhail Kuznetcov
Mikhail Kuznetcov
The Vue3 has been released in mid-2020. Besides many improvements and optimizations, the main feature of Vue3 brings is the Composition API – a new way to write and reuse reactive code. Let's learn more about how to use Composition API efficiently.

Besides core Vue3 features we'll explain examples of how to use popular libraries with Vue3.

Table of contents:
- Introduction to Vue3
- Composition API
- Core libraries
- Vue3 ecosystem

Prerequisites:
IDE of choice (Inellij or VSC) installed
Nodejs + NPM
How to Start With Cypress
TestJS Summit 2022TestJS Summit 2022
146 min
How to Start With Cypress
Featured WorkshopFree
Filip Hric
Filip Hric
The web has evolved. Finally, testing has also. Cypress is a modern testing tool that answers the testing needs of modern web applications. It has been gaining a lot of traction in the last couple of years, gaining worldwide popularity. If you have been waiting to learn Cypress, wait no more! Filip Hric will guide you through the first steps on how to start using Cypress and set up a project on your own. The good news is, learning Cypress is incredibly easy. You'll write your first test in no time, and then you'll discover how to write a full end-to-end test for a modern web application. You'll learn the core concepts like retry-ability. Discover how to work and interact with your application and learn how to combine API and UI tests. Throughout this whole workshop, we will write code and do practical exercises. You will leave with a hands-on experience that you can translate to your own project.
Detox 101: How to write stable end-to-end tests for your React Native application
React Summit 2022React Summit 2022
117 min
Detox 101: How to write stable end-to-end tests for your React Native application
Top Content
WorkshopFree
Yevheniia Hlovatska
Yevheniia Hlovatska
Compared to unit testing, end-to-end testing aims to interact with your application just like a real user. And as we all know it can be pretty challenging. Especially when we talk about Mobile applications.
Tests rely on many conditions and are considered to be slow and flaky. On the other hand - end-to-end tests can give the greatest confidence that your app is working. And if done right - can become an amazing tool for boosting developer velocity.
Detox is a gray-box end-to-end testing framework for mobile apps. Developed by Wix to solve the problem of slowness and flakiness and used by React Native itself as its E2E testing tool.
Join me on this workshop to learn how to make your mobile end-to-end tests with Detox rock.
Prerequisites- iOS/Android: MacOS Catalina or newer- Android only: Linux- Install before the workshop
API Testing with Postman Workshop
TestJS Summit 2023TestJS Summit 2023
48 min
API Testing with Postman Workshop
Top Content
WorkshopFree
Pooja Mistry
Pooja Mistry
In the ever-evolving landscape of software development, ensuring the reliability and functionality of APIs has become paramount. "API Testing with Postman" is a comprehensive workshop designed to equip participants with the knowledge and skills needed to excel in API testing using Postman, a powerful tool widely adopted by professionals in the field. This workshop delves into the fundamentals of API testing, progresses to advanced testing techniques, and explores automation, performance testing, and multi-protocol support, providing attendees with a holistic understanding of API testing with Postman.
1. Welcome to Postman- Explaining the Postman User Interface (UI)2. Workspace and Collections Collaboration- Understanding Workspaces and their role in collaboration- Exploring the concept of Collections for organizing and executing API requests3. Introduction to API Testing- Covering the basics of API testing and its significance4. Variable Management- Managing environment, global, and collection variables- Utilizing scripting snippets for dynamic data5. Building Testing Workflows- Creating effective testing workflows for comprehensive testing- Utilizing the Collection Runner for test execution- Introduction to Postbot for automated testing6. Advanced Testing- Contract Testing for ensuring API contracts- Using Mock Servers for effective testing- Maximizing productivity with Collection/Workspace templates- Integration Testing and Regression Testing strategies7. Automation with Postman- Leveraging the Postman CLI for automation- Scheduled Runs for regular testing- Integrating Postman into CI/CD pipelines8. Performance Testing- Demonstrating performance testing capabilities (showing the desktop client)- Synchronizing tests with VS Code for streamlined development9. Exploring Advanced Features - Working with Multiple Protocols: GraphQL, gRPC, and more
Join us for this workshop to unlock the full potential of Postman for API testing, streamline your testing processes, and enhance the quality and reliability of your software. Whether you're a beginner or an experienced tester, this workshop will equip you with the skills needed to excel in API testing with Postman.
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.