<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dmytro Barabash on Medium]]></title>
        <description><![CDATA[Stories by Dmytro Barabash on Medium]]></description>
        <link>https://medium.com/@tutizaraz?source=rss-4bc098519e97------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RofV5vEnQlx2pFWhUlmWWQ.jpeg</url>
            <title>Stories by Dmytro Barabash on Medium</title>
            <link>https://medium.com/@tutizaraz?source=rss-4bc098519e97------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:42:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tutizaraz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Inside MSW.js: A Journey into Top-Level Tactics for Harnessing GraphQL’s Full Potential]]></title>
            <link>https://medium.com/@tutizaraz/inside-msw-js-a-journey-into-top-level-tactics-for-harnessing-graphqls-full-potential-ee6ef5bf2673?source=rss-4bc098519e97------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee6ef5bf2673</guid>
            <category><![CDATA[mock-service-worker]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[mock-server]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dmytro Barabash]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 10:46:52 GMT</pubDate>
            <atom:updated>2023-06-22T11:10:10.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3_9gnCkrvlITg7BMsBl4w.png" /></figure><p>There are instances where frontend development surges ahead of the backend. In such scenarios, the challenge is to effectively mock data on the frontend. How about adopting an approach that minimizes difficulties when integrating the actual backend API at a later stage?</p><p>Let’s start by picturing a scenario that most likely won’t be new to you and something you, as a developer, have probably experienced before.</p><p>You’re a frontend engineer engaged in <strong>Project X</strong>. Prior to initiating the development of a new user interface component, you interface with the backend engineer. You deliberate over the data structure that will be transmitted. However, the API endpoint remains unimplemented on the backend. Despite this, demonstrating your progress to the client remains a priority, and this is when <a href="https://mswjs.io/">Mock Service Worker (MSW)</a> proves to be invaluable.</p><p>Utilizing Mock Service Worker allows you to employ declarative request handlers for capturing requests. These handlers operate based on URL, RegExp, or custom criteria, and utilize a response resolver function to deliver a mock response. This process streamlines the development workflow in scenarios where real backend services are yet to be implemented.</p><pre>import { setupWorker, rest } from &#39;msw&#39;<br><br>const worker = setupWorker(<br>  rest.get(&#39;/user/:id&#39;, (req, res, ctx) =&gt; {<br>    const { id } = req.params<br>    const userDatabase = {<br>      1: { name: &#39;Alice&#39;, age: 25 },<br>      2: { name: &#39;Bob&#39;, age: 30 }<br>    }<br><br>    if (!userDatabase[id]) {<br>      return res(<br>        ctx.status(404),<br>        ctx.json({<br>          errorMessage: &#39;User not found&#39;,<br>        }),<br>      )<br>    }<br><br>    return res(<br>      ctx.json({<br>        user: userDatabase[id],<br>      }),<br>    )<br>  }),<br>)<br><br>// Register the Service Worker and enable the mocking<br>worker.start()</pre><p>In this example, we’re mocking a GET request to /user/:idendpoint. Depending on the id provided in the request, the mock service responds with a corresponding user’s data or a 404 error if the user is not found.</p><p>The <a href="https://mswjs.io/">MSW library</a> introduces a Service Worker into the mix. This worker is designed to intercept the application’s outbound requests via the <em>fetch</em> event. It then routes these requests to the client-side library. If there exists a mocked response, this is sent to the worker, which then generates the corresponding response. This unique approach allows for comprehensive and seamless request handling.</p><p>Let’s delve into a <strong>top-level summary</strong> of the Mock Service Worker request workflow, derived from the official documentation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcO2DWPwRWb_lAWHi6joTw.png" /></figure><p>Let’s delve deeper into the code and attempt to understand how it operates at a surface level.</p><p><a href="https://mswjs.io/">MSW</a> comes bundled with a variety of preconfigured request handlers, designed to facilitate work with common API types. For instance, when dealing with a REST API, you would employ the provided REST handlers. Conversely, for a GraphQL API, you’d utilize the GraphQL request handlers. This flexibility is one of the key strengths of <a href="https://mswjs.io/">MSW</a>. However, moving forward, we will be examining an example involving GraphQL.</p><pre>query GetPostsByAuthor {<br>  posts(author: &quot;AuthorName&quot;) {<br>    title<br>    content<br>    date<br>  }<br>}</pre><p>In order to intercept a GraphQL query, you need to supply its name as the first argument to the graphql.query() request handler. Given the query definition from above, the corresponding request handler would be constructed as follows:</p><pre>import { graphql } from &#39;msw&#39;<br><br>graphql.query(&#39;GetPostsByAuthor&#39;, (req, res, ctx) =&gt; {<br>  return res(<br>    ctx.data({<br>      posts: [<br>        {<br>          title: &#39;First Post&#39;,<br>          content: &#39;This is the content of the first post&#39;,<br>          date: &#39;2023-01-01&#39;<br>        },<br>        {<br>          title: &#39;Second Post&#39;,<br>          content: &#39;This is the content of the second post&#39;,<br>          date: &#39;2023-02-01&#39;<br>        },<br>      ],<br>    }),<br>  )<br>})</pre><p>In the context of <a href="https://mswjs.io/">MSW</a>, you can utilize the req.variables object to gain access to all the variables associated with the intercepted query.</p><pre>query GetPostsByAuthor($id: ID!) {<br>  posts(id: $id, author: &quot;AuthorName&quot;) {<br>    title<br>    content<br>    date<br>  }<br>}</pre><pre>import { graphql } from &#39;msw&#39;<br><br>graphql.query(&#39;GetPostsByAuthor&#39;, (req, res, ctx) =&gt; {<br>  const { id } = req.variables<br><br>  return res(<br>    ctx.data({<br>      posts: [<br>        {<br>          id,<br>          title: &#39;First Post&#39;,<br>          content: &#39;This is the content of the first post&#39;,<br>          date: &#39;2023-01-01&#39;<br>        },<br>        {<br>          id,<br>          title: &#39;Second Post&#39;,<br>          content: &#39;This is the content of the second post&#39;,<br>          date: &#39;2023-02-01&#39;<br>        },<br>      ],<br>    }),<br>  )<br>})</pre><p>Here’s how I demonstrated my approach to implementing mock data for my Project X.</p><p>You might think that’s all there is, but it’s not. Next, we’ll explore an example of how to mock mutations.</p><pre>mutation AddPost($title: String!, $content: String!) {<br>  addPost(title: $title, content: $content) {<br>    id<br>    title<br>    content<br>  }<br>}</pre><p>In order to intercept a GraphQL mutation, you should input its name as the initial argument to the graphql.mutation() request handler. Based on the mutation definition provided earlier, the corresponding request handler would look something like this:</p><pre>graphql.mutation(&#39;AddPost&#39;, (req, res, ctx) =&gt; {<br>  const { title, content } = req.variables;<br><br>  const newPost = {<br>    id: &#39;123&#39;, // fake id<br>    title,<br>    content,<br>  };<br>  return res(<br>    ctx.data({<br>      addPost: {<br>        id: newPost.id,<br>        title: newPost.title,<br>        content: newPost.content,<br>      },<br>    }),<br>  );<br>});</pre><p>In our article, we explored a basic demonstration of data mocking using the <a href="https://mswjs.io/">MSW library</a>. We took a deep dive into the main concept behind data mocking, explaining how it works at its core. Additionally, we thoroughly examined simple examples that showcase how to construct queries and mutations.</p><p>Overall, this library enables us not only to mock data for rendering specific parts of the interface but also to mock data in unit and integration tests. However, I won’t delve into these aspects in this article as it will be your homework to explore them further.</p><p>Twitter: <a href="https://twitter.com/tutizaraz">https://twitter.com/tutizaraz</a><br>GitHub: <a href="https://github.com/tutizaraz">https://github.com/tutizaraz</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee6ef5bf2673" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>