All You Need Is a Contract…

How many times have you had to wait for your backend team to finish building the API so you can start your tasks? What if all you needed to move that task to in progress was the API contract? What if there was a library that did this for REST and GraphQL APIs and, at the same time, taking your tests to the next level? Join me and prepare to enhance your developer experience while learning all the battle-earned experiences of using one of my favorite libraries: Mock Service Worker.

This talk has been presented at React Advanced 2023, check out the latest edition of this React Conference.

Watch video on a separate page

FAQ

The three main issues are unmaintainable code, unmaintainable and flaky tests, and tasks arriving late into the sprint.

The team solved the issue of unmaintainable code by using React Query, which helped manage server state more effectively.

Server state is the state that exists somewhere on the Internet external to your application. It is challenging because it involves caching, deduping requests, and data prefetching.

The team addressed unmaintainable and flaky tests by using Mock Service Worker (MSW) to intercept actual requests and return mock data based on predefined contracts.

Mock Service Worker (MSW) is an API mocking library that uses ServiceWorker API to intercept requests and return mock data. It works by defining request handlers and response resolvers to specify the API and the data to be returned.

Yes, MSW can be used in both browser and Node environments. In the browser, it uses service workers, and in Node environments, it uses a node intercepting package.

The team handled tasks arriving late into the sprint by defining contracts at the beginning of the sprint and using MSW to mock the APIs. This allowed them to work on frontend tasks while the backend was still in development.

The key steps are: 1. Delete all existing mocks. 2. Define the request handlers and response resolvers. 3. Start the service worker or server before running tests.

MSW improves the testing process by providing a single source of truth for mock data, reducing flakiness, and simplifying the setup and maintenance of test environments.

Before opting for DIY overengineering, consider that someone may have already solved your problem and published an open-source package that is maintained, tested, and secure. Using such tools can save time and resources.

Daniel Afonso
Daniel Afonso
29 min
20 Oct, 2023

Comments

Sign in or register to post your comment.
Video Summary and Transcription
The speaker discusses the challenges of server state and test maintenance, and how they found solutions using React Query and Mock Service Worker. They emphasize the benefits of defining contracts for faster development and stress reduction. The speaker also highlights the advantages of using Mock Service Worker over mock servers and explains how it allows for easy customization and test overrides. They mention the upcoming release of V2 of MS-Double and encourage the audience to stay updated.

1. Introduction and Annoyances as a Developer

Short description:

In this part, the speaker expresses gratitude towards the audience and acknowledges the hard work of the conference organizers. They also mention three things that annoy them as a developer: unmaintainable code, tests affected by unmaintainability, and late tasks in sprints. The speaker promises to share a story about how they and their team fixed these issues.

Okay, so let me just clear up the room. There's not going to be contract testing here. This is a joke we were talking before coming on stage. Also, I'm going to move a lot, so I'm trying to figure out the spot. That's cool, if I don't get blinded by the light.

Before anything else, React Advance, thank you so much for having me here. It's a pleasure. I'll walk around for that spot because apparently the camera won't get me on the other one, so I'll try not to move a lot.

I just wanted to start this talk with like, I would like to give a cheerful applause, because there was so many hard work setting up this conference for everyone from Git nation, everyone from the tech team. I don't know if you're aware, but when we started today, we were having some issues plugging everything, and now everything is working up already so far, so can I get an everyone that's working on this? Okay. Thank you so much.

So, let's start this because already one minute went away, and there are really three things that annoy me as a developer. The first one is when you have unmaintainable code. You know the feeling. Your code is not really that good sometimes. The more you add, the worse it gets. It's struggling. Yeah, it's hard. And then the second thing that really annoys me, it's when that unmaintainability finds a way of getting into your tests. Now it's not bad that your code is not good, your tests are not good as well. Probably you're not sleeping that well at night because you know what flaky tests feel like. And the third thing that really annoys me, and I'll promise to not start a rant here, is when you have a task that arrives late into the sprint. I know some of you relate to the feeling. Let's picture we have a team where two parts are working on a task and the first part takes 98% of the time, and once the task gets to you, you have 2% of the time. So obviously your product manager is going to expect you to deliver that thing yesterday. And this is a feeling that I could start talking about here and I wouldn't stop.

So let's continue, because I have a story about how me and my team fixed these issues a couple of years ago. So let's start at the beginning on how we had just cleared up the first issue. Me and my team had just defeated the unmaintainable code monster. Because this had been something that is been working around, it was threatening us, it was hard.

2. Server State Challenges and Test Issues

Short description:

The speaker discusses the challenges of server state and how they had to implement various functionalities themselves. They then discovered React query, which solved their server state issues. However, a new challenge arose with unmaintainable and flaky tests. The speaker eventually found a solution and introduces themselves as Daniel Alfonso, a developer advocate at OLX.

And what was the reason? Well, the reason was server state. Now, I don't know if you are aware of what server state is. It's typically the state that exists somewhere on the Internet as external to your application. And it has a bunch of challenges. Caching, deduping requests, data prefetching. There is a maintainer here from React query which you can talk about of many of these challenges and you can probably understand how much pain it is understanding and having to implement this thing by hand and I can tell you that me and my team, we didn't have React query back then or in the beginning, we didn't. So we were implementing all of these things by ourselves and the more code we were having, the worse got the unmaintainable code monster. So we started thinking, why are we implementing this ourselves again? What are we trying to prove to going in this direction? And well, a couple of months went by and this was when a couple of, well, these months went by, a co-worker, like the King Arthur in the Sword and the Stone movie. I think that's how you say it in English. Sorry, non-native English speaker here. One co-worker approached the stone and brought out a 10-stack query. So apparently, this new thing, React query, had just come up and it was the solution for our issues. And 10-stack query brought harmony to our code because now all the stuff and issues we had with server state were solved and we didn't have to worry about implementing that thing for a while that is.

Now, a new threat was lurking in the shadows. You see, that unmaintainability found a way outside of our code and going inside of our tests. Now, I don't know if you remember this image I showed you a couple of minutes ago, but this is Hydra. And you know what they say about Hydras. Cut one head, two more take its place. And this is kind of what was starting to happen with us because now our tests were not just unmaintainable. They were flaky. They were complex. I couldn't sleep at night because I had no trust on what the heck I was doing and now you're wondering, okay, what's the relation? What are we going to see? Well, safely now, a couple of years ago I can tell you that me and my team managed to fix these issues. And the fun part was that all we needed was a contract. So this is the part where I actually start the talk.

Let me just introduce myself real quickly. I'm Daniel Alfonso. I'm working as a developer advocate at OLX. I'm an AGIT instructor and an out-there ambassador and you can find me, I'm going to say Twitter because of the pool before on Twitter and pretty much any social network at the end So Daniel GC Alfonso. Also something about me, I recently published a book called State Management with React Query. Thanks.

QnA

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

Modern Web Debugging
JSNation 2023JSNation 2023
29 min
Modern Web Debugging
Top Content
This Talk discusses modern web debugging and the latest updates in Chrome DevTools. It highlights new features that help pinpoint issues quicker, improved file visibility and source mapping, and ignoring and configuring files. The Breakpoints panel in DevTools has been redesigned for easier access and management. The Talk also covers the challenges of debugging with source maps and the efforts to standardize the source map format. Lastly, it provides tips for improving productivity with DevTools and emphasizes the importance of reporting bugs and using source maps for debugging production code.
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Today's Talk discusses the future of performance tooling, focusing on user-centric, actionable, and contextual approaches. The introduction highlights Adi Osmani's expertise in performance tools and his passion for DevTools features. The Talk explores the integration of user flows into DevTools and Lighthouse, enabling performance measurement and optimization. It also showcases the import/export feature for user flows and the collaboration potential with Lighthouse. The Talk further delves into the use of flows with other tools like web page test and Cypress, offering cross-browser testing capabilities. The actionable aspect emphasizes the importance of metrics like Interaction to Next Paint and Total Blocking Time, as well as the improvements in Lighthouse and performance debugging tools. Lastly, the Talk emphasizes the iterative nature of performance improvement and the user-centric, actionable, and contextual future of performance tooling.
Remix Flat Routes – An Evolution in Routing
Remix Conf Europe 2022Remix Conf Europe 2022
16 min
Remix Flat Routes – An Evolution in Routing
Top Content
Remix Flat Routes is a new convention that aims to make it easier to see and organize the routes in your app. It allows for the co-location of support files with routes, decreases refactor and redesign friction, and helps apps migrate to Remix. Flat Folders convention supports co-location and allows importing assets as relative imports. To migrate existing apps to Flat Routes, use the Remix Flat Routes package's migration tool.
Get rid of your API schemas with tRPC
React Day Berlin 2022React Day Berlin 2022
29 min
Get rid of your API schemas with tRPC
Today's Talk introduces TRPC, a library that eliminates the need for code generation and provides type safety and better collaboration between front-end and back-end. TRPC is demonstrated in a Next JS application integrated with Prisma, allowing for easy implementation and interaction with the database. The library allows for seamless usage in the client, with automatic procedure renaming and the ability to call methods without generating types. TRPC's client-server interaction is based on HTTP requests and allows for easy debugging and tracing. The library also provides runtime type check and validation using Zod.
pnpm – a Fast, Disk Space Efficient Package Manager for JavaScript
DevOps.js Conf 2022DevOps.js Conf 2022
31 min
pnpm – a Fast, Disk Space Efficient Package Manager for JavaScript
Watch video: pnpm – a Fast, Disk Space Efficient Package Manager for JavaScript
pnpm is a fast and efficient package manager that gained popularity in 2021 and is used by big tech companies like Microsoft and TikTok. It has a unique isolated node module structure that prevents package conflicts and ensures each project only has access to its own dependencies. pnpm also offers superior monorepo support with its node module structure. It solves the disk space usage issue by using a content addressable storage, reducing disk space consumption. pnpm is incredibly fast due to its installation process and deterministic node module structure. It also allows file linking using hardlinks instead of symlinks.
How to Make a Web Game All by Yourself
JS GameDev Summit 2023JS GameDev Summit 2023
27 min
How to Make a Web Game All by Yourself
This talk guides you on how to make a web game by yourself, emphasizing the importance of focusing on tasks that interest you and outsourcing the rest. It suggests choosing a game engine that allows distribution on the web and aligns with your understanding and enjoyment. The talk also highlights the significance of finding fun in the creative process, managing scope, cutting features that don't align with the game's direction, and iterating to the finish line. It concludes by discussing the options for publishing the game on the web and leveraging unique web features.

Workshops on related topic

React, TypeScript, and TDD
React Advanced 2021React Advanced 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Mastering advanced concepts in TypeScript
React Summit US 2023React Summit US 2023
132 min
Mastering advanced concepts in TypeScript
Top Content
Featured WorkshopFree
Jiri Lojda
Jiri Lojda
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects.
You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
Integrating LangChain with JavaScript for Web Developers
React Summit 2024React Summit 2024
92 min
Integrating LangChain with JavaScript for Web Developers
Featured Workshop
Vivek Nayyar
Vivek Nayyar
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.
From Todo App to B2B SaaS with Next.js and Clerk
React Summit US 2023React Summit US 2023
153 min
From Todo App to B2B SaaS with Next.js and Clerk
Top Content
WorkshopFree
Dev Agrawal
Dev Agrawal
If you’re like me, you probably have a million side-project ideas, some that could even make you money as a micro SaaS, or could turn out to be the next billion dollar startup. But how do you know which ones? How do you go from an idea into a functioning product that can be put into the hands of paying customers without quitting your job and sinking all of your time and investment into it? How can your solo side-projects compete with applications built by enormous teams and large enterprise companies?
Building rich SaaS products comes with technical challenges like infrastructure, scaling, availability, security, and complicated subsystems like auth and payments. This is why it’s often the already established tech giants who can reasonably build and operate products like that. However, a new generation of devtools are enabling us developers to easily build complete solutions that take advantage of the best cloud infrastructure available, and offer an experience that allows you to rapidly iterate on your ideas for a low cost of $0. They take all the technical challenges of building and operating software products away from you so that you only have to spend your time building the features that your users want, giving you a reasonable chance to compete against the market by staying incredibly agile and responsive to the needs of users.
In this 3 hour workshop you will start with a simple task management application built with React and Next.js and turn it into a scalable and fully functioning SaaS product by integrating a scalable database (PlanetScale), multi-tenant authentication (Clerk), and subscription based payments (Stripe). You will also learn how the principles of agile software development and domain driven design can help you build products quickly and cost-efficiently, and compete with existing solutions.
Hands-on with AG Grid's React Data Grid
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
Top Content
WorkshopFree
Sean Landsman
Sean Landsman
Get started with AG Grid React Data Grid with a hands-on tutorial from the core team that will take you through the steps of creating your first grid, including how to configure the grid with simple properties and custom components. AG Grid community edition is completely free to use in commercial applications, so you'll learn a powerful tool that you can immediately add to your projects. You'll also discover how to load data into the grid and different ways to add custom rendering to the grid. By the end of the workshop, you will have created an AG Grid React Data Grid and customized with functional React components.- Getting started and installing AG Grid- Configuring sorting, filtering, pagination- Loading data into the grid- The grid API- Using hooks and functional components with AG Grid- Capabilities of the free community edition of AG Grid- Customizing the grid with React Components
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.