<?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 Vidhi Kapadia on Medium]]></title>
        <description><![CDATA[Stories by Vidhi Kapadia on Medium]]></description>
        <link>https://medium.com/@vidhi.k?source=rss-1cfef8114866------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Vidhi Kapadia on Medium</title>
            <link>https://medium.com/@vidhi.k?source=rss-1cfef8114866------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:39:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vidhi.k/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[Build VS Code Extension Using VueJS]]></title>
            <link>https://medium.com/simform-engineering/build-vs-code-extension-using-vuejs-0714262af709?source=rss-1cfef8114866------2</link>
            <guid isPermaLink="false">https://medium.com/p/0714262af709</guid>
            <category><![CDATA[vscode-extension-vuejs]]></category>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[vscode-extension]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Vidhi Kapadia]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 07:14:03 GMT</pubDate>
            <atom:updated>2024-08-28T07:15:28.435Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Supercharge Your Workflow: Craft Custom VS Code Extensions with VueJS</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgLr_DpTRCXG4fPxKdSCDw.png" /></figure><p>Ever dreamt of creating your own VS Code extension? Buckle up because JavaScript, along with VueJS, can be your secret weapon! This guide dives into the exciting world of VS Code extension development using VueJS, empowering you to craft intuitive and interactive extensions that streamline your coding experience.</p><p><strong>Table of contents:</strong></p><ol><li>How to set up and use a <a href="https://vuejs.org/guide/introduction.html">VueJS</a> + <a href="https://github.com/microsoft/vscode-webview-ui-toolkit">Webview UI Toolkit</a></li><li>How to run the extension in development mode</li><li>Context menu options</li><li>Nested Context menu</li><li>Customize the sidebar in Webview</li><li>Message handling from Webview to Extension and Extension to Webview</li><li>Deploying of VS Code extension</li></ol><h4>How to set up and use a VueJS + Webview UI Toolkit</h4><ul><li>Download the boilerplate code for creating a VS Code extension using VueJS + Webview from the official documentation.</li><li>Run the following commands to download the code from the repository.</li></ul><pre>git init<br>git remote add origin https://github.com/microsoft/vscode-webview-ui-toolkit-samples.git<br>git config core.sparseCheckout true<br>echo &quot;frameworks/hello-world-vue&quot; &gt;&gt; .git/info/sparse-checkout<br>git pull origin main<br>cd frameworks <br>cd hello-world-vue<br>code .</pre><pre># Install dependencies for both the extension and webview UI source code<br>npm run install:all<br><br># Build webview UI source code<br>npm run build:webview</pre><p>To run the extension in VS Code after opening the sample, follow these steps:</p><ol><li>Press F5 to open a new Extension Development Host window.</li><li>In the host window, open the command palette (Ctrl+Shift+P or Cmd+Shift+P on Mac) and type Hello World (Vue): Show .</li></ol><h4><strong>How to test code in development mode</strong></h4><p>To test, you need to create a build using npm run build:webview each time. After that, open a new VS Code window using F5 and perform a hard reload using ctrl + R . I understand this can be time-consuming, but it’s necessary for testing in development mode.</p><pre># Run this code in terminal<br>npm run build:webview<br>npm run compile<br><br># In new terminal<br>npm run watch<br><br># Press F5 and new development window will open<br>ctrl + R</pre><h4>What is the extension.ts file?</h4><p>The extension.ts file is a fundamental part of a VS Code extension written in TypeScript. It serves as the entry point for your extension&#39;s functionality, acting like the main script that gets executed when your extension activates.</p><h4>Context menu options</h4><p>We’ll learn how to add a context menu option, which only appears when text is selected in the editor.</p><h4>package.json</h4><p>First, we define the contributions of our extension in the package.json file. This file specifies the command and context menu entry:</p><pre>&quot;contributes&quot;: {<br>  &quot;commands&quot;: [<br>    {<br>      &quot;command&quot;: &quot;editor.showContextMenu&quot;,<br>      &quot;title&quot;: &quot;Codebuzzer&quot;<br>    }<br>  ],<br>  &quot;menus&quot;: {<br>    &quot;editor/context&quot;: [<br>      {<br>        &quot;command&quot;: &quot;editor.showContextMenu&quot;,<br>        &quot;when&quot;: &quot;editorHasSelection&quot;,<br>        &quot;title&quot;: &quot;Codebuzzer&quot;<br>      }<br>    ]<br>  }<br>}</pre><ul><li><strong>Commands</strong>: Registers a command with the identifier editor.showContextMenu and the title &quot;Codebuzzer.&quot;</li><li><strong>Menus</strong>: Adds this command to the editor’s context menu, with the condition (when clause) that text must be selected (editorHasSelection). The menu item will be titled &quot;Codebuzzer.&quot;</li></ul><h4>extension.ts</h4><p>Next, we implement the functionality of our extension in extension.ts .</p><pre>import * as vscode from &quot;vscode&quot;;<br><br>export async function activate(context: vscode.ExtensionContext) {<br><br>  // Register the command for context menu contribution<br>  const submenuContribution = vscode.commands.registerCommand(<br>    &quot;editor.showContextMenu&quot;,<br>    () =&gt; {<br>      const selection = vscode.window.activeTextEditor?.selection;<br><br>      if (selection &amp;&amp; !selection.isEmpty) {<br>        // Inform the user that the context menu option was triggered<br>        vscode.window.showInformationMessage(&quot;Context menu option selected with text.&quot;);<br>      } else {<br>        // Inform the user if no text is selected<br>        vscode.window.showInformationMessage(&quot;Select some text to get suggestions.&quot;);<br>      }<br>    }<br>  );<br><br>  // Add the command to the subscriptions so it gets disposed properly<br>  context.subscriptions.push(submenuContribution);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Il8pwinFvbGzMvKreqzsg.png" /><figcaption>Context Menu</figcaption></figure><h4>Nested context menu options</h4><p>A nested context menu will allow us to organize related commands under the submenu, making the context menu more structured and user-friendly.</p><h4>package.json</h4><p>First, we define the contributions of our extension in the package.json file. This file specifies the commands, submenu, and context menu entries:</p><pre>&quot;contributes&quot;: {<br>  &quot;commands&quot;: [<br>    {<br>      &quot;command&quot;: &quot;demo.explain&quot;,<br>      &quot;title&quot;: &quot;Explain&quot;<br>    },<br>    {<br>      &quot;command&quot;: &quot;demo.refactor&quot;,<br>      &quot;title&quot;: &quot;Refactor&quot;<br>    },<br>    {<br>      &quot;command&quot;: &quot;demo.fix&quot;,<br>      &quot;title&quot;: &quot;Fix&quot;<br>    },<br>    {<br>      &quot;command&quot;: &quot;demo.optimize&quot;,<br>      &quot;title&quot;: &quot;Optimize&quot;<br>    },<br>    {<br>      &quot;command&quot;: &quot;demo.appendCode&quot;,<br>      &quot;title&quot;: &quot;Append Code&quot;<br>    },<br>    {<br>      &quot;command&quot;: &quot;demo.replaceExistingCode&quot;,<br>      &quot;title&quot;: &quot;Replace Existing Code&quot;<br>    }<br>  ],<br>  &quot;submenus&quot;: [<br>    {<br>      &quot;id&quot;: &quot;submenuId&quot;,<br>      &quot;label&quot;: &quot;Codebuzzer&quot;<br>    },<br>    {<br>      &quot;id&quot;: &quot;refactorSubMenuId&quot;,<br>      &quot;label&quot;: &quot;Refactor&quot;<br>    }<br>  ],<br>  &quot;menus&quot;: {<br>    &quot;editor/context&quot;: [<br>      {<br>        &quot;when&quot;: &quot;editorHasSelection&quot;,<br>        &quot;submenu&quot;: &quot;submenuId&quot;<br>      }<br>    ],<br>    &quot;submenuId&quot;: [<br>      {<br>        &quot;command&quot;: &quot;demo.explain&quot;<br>      },<br>      {<br>        &quot;command&quot;: &quot;demo.fix&quot;<br>      },<br>      {<br>        &quot;label&quot;: &quot;Refactor&quot;,<br>        &quot;submenu&quot;: &quot;refactorSubMenuId&quot;<br>      },<br>      {<br>        &quot;command&quot;: &quot;demo.optimize&quot;<br>      }<br>    ],<br>    &quot;refactorSubMenuId&quot;: [<br>      {<br>        &quot;command&quot;: &quot;demo.appendCode&quot;,<br>        &quot;when&quot;: &quot;editorHasSelection&quot;<br>      },<br>      {<br>        &quot;command&quot;: &quot;demo.replaceExistingCode&quot;,<br>        &quot;when&quot;: &quot;editorHasSelection&quot;<br>      }<br>    ]<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZbocE98SzCpQBP9qYlZSg.gif" /><figcaption>Nested Context Menu</figcaption></figure><h4>Customise sidebars using Webview panels</h4><p>Creates a Webview Panel titled “Codebuzzer,” which will appear beside the currently active editor. It also enables JavaScript within the Webview and restricts resource loading to specific directories.</p><pre>const panel = window.createWebviewPanel(<br>        // Panel view type<br>        &quot;showHelloWorld&quot;,<br>        // Panel title<br>        &quot;Codebuzzer&quot;,<br>        // The editor column the panel should be displayed in<br>        ViewColumn.Beside,<br>        // Extra panel configurations<br>        {<br>          // Enable JavaScript in the webview<br>          enableScripts: true,<br>          // Restrict the webview to only load resources from the `out` and `webview-ui/build` directories<br>          localResourceRoots: [<br>            Uri.joinPath(extensionUri, &quot;out&quot;),<br>            Uri.joinPath(extensionUri, &quot;webview-ui/build&quot;),<br>          ],<br>        }<br>      );</pre><p>Ins the webview-ui folder , in /scr/App.vue , you can write any VueJS code you want. Here I have written <strong>Hello World</strong> inside h1 tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2i6moJIikRnqAcy96-ZZ7Q.gif" /><figcaption>Customise sidebar in webview</figcaption></figure><h4>Passing a message from the extension to Webview</h4><p>To send a message from the VS Code extension to Webview, you can use the postMessage method. This method sends data to Webview, where it can be handled by a corresponding script running in Webview.</p><pre>const panel = vscode.window.createWebviewPanel(<br>    &quot;showHelloWorld&quot;, <br>    &quot;Codebuzzer&quot;, <br>    vscode.ViewColumn.One, <br>    { enableScripts: true }<br>);<br><br>// Function to send a message to the Webview<br>function sendMessageToWebview() {<br>    panel.webview.postMessage({ command: &#39;update&#39;, text: &#39;Hello from the extension!&#39; });<br>}</pre><h4>Handling messages in Webview</h4><p>In your Webview’s HTML/JavaScript, you can listen for messages from the extension using the window.addEventListener(&#39;message&#39;, ...) method.</p><p>In VueJS, we can listen to events inside onmounted .</p><pre>onMounted(() =&gt; {<br>      window.addEventListener(&#39;message&#39;, event =&gt; {<br>            const message = event.data; // The JSON data that the extension sent<br>            if (message.command === &#39;update&#39;) {<br>                document.getElementById(&#39;message&#39;).textContent = message.text;<br>            }<br>        });<br>});</pre><h4>Passing a message from Webview to the extension</h4><p>To send a message from Webview back to the extension, use the vscode.postMessage method, which is provided by the VS Code API.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;My Webview&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;button id=&quot;send&quot;&gt;Send Message to Extension&lt;/button&gt;<br><br>    &lt;script&gt;<br>        const vscode = acquireVsCodeApi();<br><br>        document.getElementById(&#39;send&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>            vscode.postMessage({<br>                command: &#39;alert&#39;,<br>                text: &#39;Hello from the Webview!&#39;<br>            });<br>        });<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>Handling messages in the extension</h4><p>In your extension, you can handle messages sent from Webview using the onDidReceiveMessage method.</p><pre>panel.webview.onDidReceiveMessage(message =&gt; {<br>    switch (message.command) {<br>        case &#39;alert&#39;:<br>            vscode.window.showInformationMessage(message.text);<br>            break;<br>    }<br>});</pre><h3>Deploying a Visual Studio Code (VS Code) extension</h3><ol><li><strong>Prepare your extension<br></strong>Before deploying, ensure that your extension is ready for distribution:</li></ol><ul><li><strong>Test thoroughly</strong>: Make sure your extension works as expected and is free from bugs.</li><li><strong>Update </strong><strong>package.json</strong>: Ensure that your package.json file has the correct metadata, including the extension&#39;s name, version, description, and keywords. Also, make sure all dependencies are correctly listed.</li></ul><p><strong>2. Install </strong><strong>vsce </strong><br>The Visual Studio Code Extension Manager (vsce) is a command-line tool used to package and publish VS Code extensions. You can install it globally using npm:</p><pre>npm install -g vsce</pre><p><strong>3</strong>. <strong>Package your extension<br></strong>Once your extension is ready, you can package it into a .vsix file using vsce:</p><pre><br>vsce package</pre><p><strong>4. Create a publisher</strong><br>To publish your extension to the Marketplace, you need a publisher account. If you don’t already have one, follow these steps:</p><ol><li><strong>Sign in to Visual Studio Code Marketplace</strong>: Go to the <a href="https://marketplace.visualstudio.com/">Visual Studio Code Marketplace</a> and sign in with your Microsoft or GitHub account.</li><li><strong>Create a publisher</strong>: After signing in, go to the <a href="https://marketplace.visualstudio.com/manage">Publishers Management Page</a> and create a new publisher.</li></ol><p><strong>5. Obtain a personal access token<br></strong>You need a Personal Access Token (PAT) from Azure DevOps to authenticate your publisher account during the publishing process.<br>1. Go to your <a href="https://dev.azure.com/">Azure DevOps profile</a>.</p><p>2. Navigate to <strong>Personal Access Tokens</strong> and create a new token with the following settings:</p><ul><li><strong>Organization</strong>: All accessible organizations</li><li><strong>Expiration</strong>: Choose an appropriate expiration period</li><li><strong>Scopes</strong>: Set the scope to <strong>Marketplace</strong> (all scopes within Marketplace)</li></ul><p>3. Copy the token and keep it secure.</p><p><strong>6. Publish your extension</strong><br>With the PAT and vsce, you can publish your extension to the Marketplace:</p><pre>vsce publish</pre><p><strong>7. Verify the deployment</strong><br>After publishing, visit the Visual Studio Code Marketplace and verify that your extension is listed. You can install it in your local VS Code instance to ensure everything works as expected.</p><h3>Additional tips:</h3><ul><li><strong>Automatic publishing</strong>: If you have a CI/CD pipeline, you can automate the packaging and publishing process using the vsce commands.</li><li><strong>Manual installation</strong>: If you want to distribute your extension without publishing it to the Marketplace, you can share the .vsix file directly, and users can install it manually by selecting Extensions: Install from VSIX... in the VS Code command palette.</li></ul><h4>Conclusion</h4><p>This blog covered the complete process of creating and deploying a VS Code extension using VueJS and Webview UI Toolkit. It includes setup, development, customizing context menus and sidebars, and handling communication between the Webview and extension.</p><blockquote><strong>For more updates on the latest tools and technologies, follow the </strong><a href="https://medium.com/simform-engineering"><strong>Simform Engineering</strong></a><strong> blog.</strong></blockquote><blockquote><strong>Follow us: </strong><a href="https://twitter.com/simform"><strong>Twitter</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/simform/"><strong>LinkedIn</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0714262af709" width="1" height="1" alt=""><hr><p><a href="https://medium.com/simform-engineering/build-vs-code-extension-using-vuejs-0714262af709">Build VS Code Extension Using VueJS</a> was originally published in <a href="https://medium.com/simform-engineering">Simform Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocking HTTP Request in React using Mock Service Worker]]></title>
            <link>https://medium.com/simform-engineering/mocking-http-request-in-react-using-mock-service-worker-0f9c5400b035?source=rss-1cfef8114866------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f9c5400b035</guid>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Vidhi Kapadia]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 13:55:20 GMT</pubDate>
            <atom:updated>2023-12-28T13:55:20.034Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Enhance API testing efficiency with React Testing Library and Mock Service Worker</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nMxbnJ1yjGtUgxMzATpNw.png" /></figure><p>Have you ever found yourself deploying a new feature and feeling concerned about the possibility of introducing new bugs with each update? A minor change in an API could potentially disrupt the Frontend. What if there were a way to identify issues in an existing app simply by running test cases? In this blog post, we will delve into the use of React Testing Library to replicate DOM manipulation and Mock Service Worker (MSW) to mock HTTP requests. If you’re unfamiliar with React Testing Library, please take a moment to <a href="https://medium.com/simform-engineering/react-testing-library-introduction-61482daeeb">check out our introduction to it</a>.</p><h3>Understanding the need for mocking HTTP requests</h3><p>Mocking HTTP requests during testing is essential for several compelling reasons:</p><ol><li><strong>Speed</strong>: Mocking HTTP requests is significantly faster than making actual API calls, improving test execution speed.</li><li><strong>Isolation and Stability:</strong> Tests are less affected by external factors, ensuring stability.</li><li><strong>Data Control:</strong> Developers can create specific scenarios for testing, ensuring components can handle specific edge cases.</li><li><strong>Consistency: </strong>Mocked responses remain constant, reducing the likelihood of test failures due to external API changes.</li><li><strong>Cost Reduction:</strong> Mocking prevents costs associated with real API calls, particularly when running individual test cases.</li></ol><h3><strong>Popular mocking libraries used with React</strong></h3><p>You can choose from many popular mocking libraries options, each offering unique features and advantages:</p><ol><li><a href="https://mswjs.io/docs/getting-started"><strong>MSW(Mock Service Worker)</strong></a><strong> </strong>is an API mocking library that allows you to write client-agnostic mocks<strong> </strong>and reuse them everywhere, regardless of tools or frameworks.</li><li><a href="https://github.com/nock/nock"><strong>Nock </strong></a>is a Node.js library specifically designed for mocking HTTP requests which offers a rich set of features for controlling request behaviour and defining expected responses.</li><li><a href="https://www.npmjs.com/package/axios-mock-adapter"><strong>axios-mock-adapter</strong></a><strong> </strong>is a lightweight and easy-to-use mocking library specifically designed for Axios.</li></ol><p>Among the various API mocking libraries available, <strong>MSW</strong> stands out as a powerful tool. We’ll explore how to mock API calls and write test cases using MSW to build robust and reliable applications.</p><h3>Axios or Fetch ? MSW works with both</h3><p>MSW simplifies your testing process as it’s independent of any specific HTTP library like Axios or Fetch.</p><h3>Prerequisite</h3><p>Before we start, ensure these in your development environment:</p><ol><li>Install Node.js and npm on your development machine.</li><li>Set up a React development environment with Vite.</li></ol><h3>How to setup Jest and Testing library in a React project with Vite</h3><p>Since we are using <a href="https://vitejs.dev/">Vite</a> for creating a React application, we will use <a href="https://vitest.dev/">Vitest</a> package, which is compatible with Vite.</p><p><strong>Step 1:</strong> Install the necessary dependencies.</p><pre>npm install -D vitest jsdom @testing-library/react jest jest-environment-jsdom @testing-library/jest-dom</pre><p><strong>Step 2: </strong>After the installation, add test script in the package.json.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df460261e3b8ad38415c8001cedb0d7b/href">https://medium.com/media/df460261e3b8ad38415c8001cedb0d7b/href</a></iframe><p><strong>Step 3:</strong> Create a new file in the root of your project with the name setupTests.js .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4164dac6b644ee50bdc41be9cb751957/href">https://medium.com/media/4164dac6b644ee50bdc41be9cb751957/href</a></iframe><p><strong>Step 4</strong>: Next, open the vite.config.js file and add the following code to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1920f2974d49914b2e05c13a318651e4/href">https://medium.com/media/1920f2974d49914b2e05c13a318651e4/href</a></iframe><p><strong>Note:</strong> When we use create-react-app for creating the project, there’s no requirement for a separate installation of Jest since it’s already included.</p><h3>Creating UI for writing test cases</h3><p>We will create a simple Todo List App that allows users to fetch a list of existing tasks and add new tasks to it.</p><p>Here, we will use the freely available JSON Placeholder API for demonstration and testing purposes.</p><p>Inside the components folder, create three files namely TodoWrapper.jsx<strong> , </strong>Todos.jsx and TodoForm.jsx.</p><p>Get the whole code from <a href="https://github.com/vidhiksimform/mock_api_demo/tree/dev">this </a>repository.</p><p><strong>Step 1: </strong>Inside the TodoWrapper.jsx component, a get request is made to fetch a list of todos .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cce696ce2005a284cbda768ca51c7ef4/href">https://medium.com/media/cce696ce2005a284cbda768ca51c7ef4/href</a></iframe><p><strong>Step 2:</strong> Inside the Todos.jsx component, we map over the todos props and display them in a list.</p><p>If there is no data inside todos props, it will display No todo found<strong> .</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e73d31a9515dbe700c7017b31f37c0d9/href">https://medium.com/media/e73d31a9515dbe700c7017b31f37c0d9/href</a></iframe><p><strong>Step 3: </strong>For adding a new todo to a list, write text inside the input textbox and click on the submit button. On clicking the button, it will call post API and the new todo will be added to a list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08aa07c278919afc8ade11080ae80862/href">https://medium.com/media/08aa07c278919afc8ade11080ae80862/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfaIkhZYJMPR4Njtkzs2qA.png" /><figcaption>Display todos</figcaption></figure><p>The most recommended library for mocking when writing tests with the <strong>React Testing library</strong> is <strong>MSW (Mock Service Worker)</strong>.</p><h3>MSW setup</h3><p><strong>Step 1:</strong> Install msw library as a dev dependency.</p><pre>npm install msw --save-dev</pre><p><strong>Step 2:</strong> Create a file server.js inside the mocks folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aba8a36eb5bf1d74ee7bc11f90bab586/href">https://medium.com/media/aba8a36eb5bf1d74ee7bc11f90bab586/href</a></iframe><p><strong>Step 3:</strong> Create a file handlers.js for handling the HTTP request.</p><p>For our scenarios, we need to mock REST API. Other option available is GRAPHQL API .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9454a232165e6f0c2842463068598f20/href">https://medium.com/media/9454a232165e6f0c2842463068598f20/href</a></iframe><p>Here, we are mocking GET and POST API responses.</p><ul><li>The first argument is the same URL that we are using to fetch todos.</li><li>The second argument is the function that returns Mocked JSON Data and it should match the exact response which the component expects.</li></ul><h3>Testing with MSW</h3><p>Now we have MSW set with the server and handlers, let’s write our test for TodoWrapper component.</p><p>Create a file named TodoWrapper.test.jsx inside the _tests_ folder.</p><p>First, let’s ensure that the component renders without any errors and displays the heading correctly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0969c542da14fa14faef51208164df7e/href">https://medium.com/media/0969c542da14fa14faef51208164df7e/href</a></iframe><p>To run the test in Vite, use the following command.</p><pre>npm run test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdCPW3J9iNkKtBcQ3M0gFw.png" /><figcaption>First test case for checking component renders successfully</figcaption></figure><p>Now, we need to write a test case to ensure the list of todos is displayed when the component mounts and fetch data from the HTTP request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ab3944afeb2e0e293b86cc4880639ba/href">https://medium.com/media/5ab3944afeb2e0e293b86cc4880639ba/href</a></iframe><p>We have used findAllByRole method from React testing library as we expect multiple list items to be present in the DOM.</p><p>For our assertion, we expect todo’s array to have a length of 3. Now, where did the 3 come from? Well, it’s the length of the mocked array response that we have passed in handlers file.</p><p>If we run this test, our test fails. You can see that expected length 3 and received length is 10. This is because we have not told our test to use a mock service worker. It has called the actual API endpoint, which returns an array of 10 todos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOwh625LVpbk-HpQV0N_Ew.png" /><figcaption>Test fails as it calls actual HTTP endpoint</figcaption></figure><p>To tell our test to use MSW, let’s modify the setupTests.js with the code snippet below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1166d1e39e5c743537099d85294f149/href">https://medium.com/media/f1166d1e39e5c743537099d85294f149/href</a></iframe><p>Now, if we run our test, it passes. This ensures MSW is considered when running the tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xf-DFzydWfuLh7kj4uFf1g.png" /><figcaption>Test passes after adding Jest functions in setupTest file</figcaption></figure><p>Let’s also assert against the mocked response that we passed in our MSW server and check if it renders correctly on DOM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f90abf2b082266931568febfc2606dc0/href">https://medium.com/media/f90abf2b082266931568febfc2606dc0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c129bcd8810c69133e03472116563b20/href">https://medium.com/media/c129bcd8810c69133e03472116563b20/href</a></iframe><p>So now you can see the test for fetching todo passed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrYFD5Iv1QqU8kDjI2e_iw.png" /><figcaption>Display todo list testcase</figcaption></figure><h4>Let’s write some more tests</h4><p>A test case that verifies the TodoForm component correctly handles user input, adds the entered todo to the list, and displays the added todo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68a5fe23d32f007e90ecd96d4b3316b1/href">https://medium.com/media/68a5fe23d32f007e90ecd96d4b3316b1/href</a></iframe><p>Here, we are using fireEvent from<strong> </strong>@testing-library/react<strong> </strong>to simulate user interaction with input elements and Add Todo button.</p><p>The user enters the text ideas into the input field using fireEvent.change(). Then, it triggers the Add Todo button&#39;s click event using fireEvent.click() .</p><p>waitFor() to ensure that the assertion is executed only after the API response has been processed and the list has been updated.</p><p>MSW intercepts the API request and returns a mock response with a status code of 201, representing a successful todo creation.</p><p>The assertion checks whether the list item containing the text ideas is present in the DOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GgYAlr-KaDUYXb4gXwI2Q.png" /><figcaption>Add todo testcase</figcaption></figure><h3>MSW error handling</h3><p>If we take a look at our TodoWrapper’s component, we are setting an error message when the HTTP request fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*-CDLBpRB1ZPB-9ZDG69w1g.png" /><figcaption>Setting error message</figcaption></figure><p>The same error message is displayed on the DOM that there is an error fetching todos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReFPIfHke-e21iCjTycYcQ.png" /><figcaption>Displays an error message</figcaption></figure><p>Let’s see how to tell MSW to respond with an error status when an HTTP request fails.</p><p>So instead of mocking requests in setupTests.js file, we will mock requests for error handling in the test itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b9c9d5a847959a32b9ab1cb8d72f036/href">https://medium.com/media/6b9c9d5a847959a32b9ab1cb8d72f036/href</a></iframe><p>It is important to note that this handler for the 500 status code applies to this single test. As we are resetting the handlers using afterEach(() =&gt; server.resetHandlers())<strong> </strong>after each test runs.</p><p>Now, as we run the test, we see all the four test cases are running as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNTS3f1eo3enJZEUDCZKSA.png" /><figcaption>Error handling testcase</figcaption></figure><p><strong><em>For the complete source code, check out the </em></strong><a href="https://github.com/vidhiksimform/mock_api_demo"><strong><em>GitHub repository</em></strong></a><strong><em>.🚀</em></strong></p><h3>Conclusion</h3><p>In this blog, we emphasized the importance of mocking HTTP requests. We explored setting up a testing environment for a React app created using Vite from scratch. Using a basic todo list example, we demonstrated how to mock HTTP requests using Mock Service Worker (MSW).</p><p>It’s worth noting that MSW offers a wide range of additional features, so feel free to explore its <a href="https://mswjs.io/docs/getting-started/">documentation</a> for more comprehensive insights.</p><blockquote><strong>For more updates on the latest development trends, follow the </strong><a href="https://medium.com/simform-engineering"><strong>Simform Engineering</strong></a><strong> blog.</strong></blockquote><blockquote><strong>Follow Us: </strong><a href="https://twitter.com/simform"><strong>Twitter</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/simform/"><strong>LinkedIn</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f9c5400b035" width="1" height="1" alt=""><hr><p><a href="https://medium.com/simform-engineering/mocking-http-request-in-react-using-mock-service-worker-0f9c5400b035">Mocking HTTP Request in React using Mock Service Worker</a> was originally published in <a href="https://medium.com/simform-engineering">Simform Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>