<?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 İbrahim Çağrı Koca on Medium]]></title>
        <description><![CDATA[Stories by İbrahim Çağrı Koca on Medium]]></description>
        <link>https://medium.com/@ibrahimcagrikoca?source=rss-30d9dbff34a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9UC-ZalRui2G2igZ</url>
            <title>Stories by İbrahim Çağrı Koca on Medium</title>
            <link>https://medium.com/@ibrahimcagrikoca?source=rss-30d9dbff34a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:07:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ibrahimcagrikoca/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[Avoid State Chaos: Using Data Providers in Vue 3 Effectively]]></title>
            <link>https://medium.com/@ibrahimcagrikoca/avoid-state-chaos-using-data-providers-in-vue-3-effectively-b0af4c145ecf?source=rss-30d9dbff34a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0af4c145ecf</guid>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[scalable-web-application]]></category>
            <category><![CDATA[composition-api]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[İbrahim Çağrı Koca]]></dc:creator>
            <pubDate>Tue, 27 May 2025 10:37:05 GMT</pubDate>
            <atom:updated>2025-05-27T10:37:05.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kfI9i42r1MR3Gj7LYSlv-w.png" /><figcaption><strong>Before</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1CmFkwOs7fx_J6EDOeCrrw.png" /><figcaption><strong>After</strong></figcaption></figure><p>With Vue 3’s powerful Composition API, state management has become significantly more flexible. However, as your application scales, managing complexity often becomes challenging. Unexpected component interactions, shared state conflicts, and performance degradation can quickly become major pain points.</p><p>The <strong>Data Provider Pattern</strong> provides a structured approach to maintain clarity and control in your Vue applications.</p><h3>What is the Data Provider Pattern?</h3><p>Vue’s `provide` and `inject` APIs allow passing data through component trees. Originally used for static context such as themes or locales, the Data Provider Pattern expands these APIs to handle dynamic and reactive state management within scoped contexts.</p><p>Its core principle is straightforward: <strong>Share state precisely where it’s needed.</strong> This approach avoids the pitfalls of global state, making state management explicit and clear.</p><h3>Why Use the Data Provider Pattern?</h3><h4><strong>Common Problem: Shared State Conflicts</strong></h4><p>Here’s a common scenario:</p><pre>export const useListContext = () =&gt; {<br> const params = ref({})<br> const items = ref([])<br> return { params, items }<br>}</pre><p>When multiple tabs or modals share this composable, they interfere with each other:</p><ul><li>❌ Tab A filters change Tab B’s data.</li><li>❌ Closing one modal doesn’t reset its state properly.</li><li>❌ Unexpected conflicts arise from shared references.</li></ul><h3>The Solution: Scoped Providers</h3><p>Here’s a simple Vue provider example:</p><pre>&lt;!-- Provider component creating a unique scoped context --&gt;<br>&lt;script setup&gt;<br>import { provide } from &#39;vue&#39;<br>import { useProductContext } from &#39;@/composables/useProductContext&#39;<br><br>// Providing scoped context to child components<br>provide(&#39;productContext&#39;, useProductContext())<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;slot /&gt;<br>&lt;/template&gt;</pre><p><strong>By isolating state within scoped providers:</strong></p><ul><li>Tabs have independent pagination, filtering, and loading states.</li><li>Modals operate independently</li><li>Components can safely reuse logic without interference.</li></ul><h3>Benefits of Adopting This Pattern</h3><h4>1.State Isolation</h4><p>State management becomes explicit and compartmentalized, significantly reducing side effects and conflicts across unrelated components.</p><h4>2. Improved Testability</h4><p>Composable states provided via <strong>provide</strong> can easily be mocked in tests:</p><pre>mount(ComponentUnderTest, {<br> global: {<br>   provide: {<br>     listContext: mockListContext()<br>   }<br> }<br>})</pre><p>This structure results in more reliable, maintainable tests.</p><h4>3. Performance Gains</h4><p>By Limiting reactivity to the relevant components reduces unnecessary re-renders, enhancing your application’s responsiveness and efficiency.</p><h4>4. Increased Reusability</h4><p>One component can adapt to multiple contexts seamlessly:</p><ul><li><strong>List.vue</strong> for archived products</li><li><strong>List.vue</strong> for active sales</li><li><strong>List.vue</strong> for approvals</li></ul><p>Each wrapped with their own provider.</p><h4>5. Clearer Architectural Patterns</h4><p>This approach aligns with familiar architectural concepts like React’s Context API or Redux Providers, making it easier to onboard new developers.</p><h3>Considerations and Trade-offs</h3><h4>Learning Curve</h4><p>Incorrect usage of <strong>provide() </strong>and <strong>inject()</strong> can quietly return <strong>undefined</strong>, potentially causing confusion and debugging difficulty, particularly for newcomers.</p><h4>Increased File Structure</h4><p><strong>You’ll have additional files for:</strong></p><ul><li>Composables (states/actions)</li><li>Providers</li><li>Components consuming via <strong>inject()</strong></li></ul><p>Yet, this organization significantly enhances clarity and maintainability.</p><h3>When to Apply This Pattern</h3><h4>✅ Ideal scenarios:</h4><ul><li>Complex condition-based interfaces</li><li>Scoped state in modals</li><li>Reusable UI widgets</li><li>Nested routing scenarios with different contexts</li></ul><h4>🚫 Avoid if:</h4><ul><li>Simple, single-use forms</li><li>Basic route-based state management</li><li>Components with minimal interactivity</li></ul><h3>Practical Implementation Example</h3><h4>Step 1: Define Context</h4><pre>export const useProductContext = () =&gt; {<br> const products = ref([])<br> const fetchProducts = async () =&gt; {<br>   products.value = await api.get()<br> }<br> return { products, fetchProducts }<br>}</pre><h4>Step 2: Create Provider</h4><pre>&lt;script setup&gt;<br>import { provide } from &#39;vue&#39;<br>import { useProductContext } from &#39;@/composables/useProductContext&#39;<br>provide(&#39;productContext&#39;, useProductContext())<br>&lt;/script&gt;<br>&lt;template&gt;&lt;slot /&gt;&lt;/template&gt;</pre><h4>Step 3: Consume Context</h4><pre>&lt;template&gt;<br>  &lt;ProductProvider&gt;<br>    &lt;SomeComponent /&gt;<br>  &lt;/ProductProvider&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import ProductProvider from &#39;./providers/ProductProvider.vue&#39;<br>import SomeComponent from &#39;./components/SomeComponent.vue&#39;<br>&lt;/script&gt;</pre><pre>// SomeComponent.vue<br>&lt;script setup&gt;<br>const { products, fetchProducts } = inject(&#39;productContext&#39;)<br>onMounted(fetchProducts)<br>&lt;/script&gt;</pre><h3>Visualizing the Pattern</h3><p>Here’s a simplified diagram of the Data Provider Pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qc8KdZ9GdtjnSFxNlJ8Qwg.png" /><figcaption>Using Data Providers</figcaption></figure><p>This visual demonstrates how each component independently manages its state, even while sharing common UI components.</p><h3>Final Thoughts</h3><p>Implementing the Data Provider Pattern can significantly improve the clarity, maintainability, and scalability of your Vue 3 application. Clearly defined boundaries and isolated state management are key to robust, predictable, and performant applications.</p><p><strong>Great architecture starts with clear boundaries. Define yours today.</strong></p><p>Start incrementally and experience the benefits of cleaner, more predictable state management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0af4c145ecf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of React Native Architecture: From Classic Bridge to Modern JSI, Fabric and…]]></title>
            <link>https://medium.com/@ibrahimcagrikoca/the-evolution-of-react-native-architecture-from-classic-bridge-to-modern-jsi-fabric-and-549f1d2c4317?source=rss-30d9dbff34a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/549f1d2c4317</guid>
            <category><![CDATA[jsi]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[İbrahim Çağrı Koca]]></dc:creator>
            <pubDate>Fri, 09 May 2025 13:02:16 GMT</pubDate>
            <atom:updated>2025-05-09T13:02:16.365Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Evolution of React Native Architecture: From Classic Bridge to Modern JSI, Fabric and TurboModules</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*OhmYGQJZ6KIlPsxvS2vbtA.png" /><figcaption>A decade-long journey from asynchronous Bridge calls to synchronous JSI performance.</figcaption></figure><h3>Introduction</h3><p>We are in the golden era of mobile development, where application performance, development speed and cross-platform compatibility matter more than ever. This is exactly where React Native shines: a JavaScript-based mobile development framework that offers a unified codebase for both iOS and Android with a developer-friendly approach.</p><p>The success of React Native lies not only in its “write once, run anywhere” philosophy but also in its continually evolving and improving architecture. Initially, it utilized a bridge-based communication model between JavaScript and native code. While this design was effective in earlier days, it began to show limitations as applications grew in size and complexity. Performance bottlenecks, latency issues, and inconsistent user experiences across platforms created the need for a more modern and robust architecture. This necessity led to the emergence of React Native’s “New Architecture” — comprising JSI (JavaScript Interface), TurboModules and the Fabric Renderer.</p><p>This article explores how React Native works under the hood, compares the legacy and modern architectures and outlines the migration process for development teams. Whether you’re a newcomer or an experienced developer, understanding this evolution is key to making informed architectural decisions for your mobile projects.</p><h3>The Legacy Architecture (Bridge-Based Model)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fska5rJnfiuNPxMUmBMMXQ.png" /><figcaption>The Old React Native Architecture</figcaption></figure><h3>Overview</h3><p>In its early versions, React Native functioned through the following architecture:</p><ul><li><strong>JavaScript Thread</strong>: Executes the business logic.</li><li><strong>Bridge</strong>: Facilitates communication between JavaScript and native modules.</li><li><strong>Native Modules &amp; UI Thread</strong>: Renders UI elements on the native side (iOS/Android).</li></ul><h3>Communication Model</h3><ul><li>Messages are first serialized to JSON on the JavaScript thread. This serialization process transforms complex JavaScript objects into a format that can be transmitted across the bridge.</li><li>These messages are then sent asynchronously and batched together, following a First-In-First-Out (FIFO) queue model. This batching helps reduce the number of bridge calls but can also lead to UI lag if the batch size grows large.</li><li>Once received on the native side, the batched commands are deserialized, parsed and executed. UI updates are handled after this step, resulting in a delay between the original JavaScript action and the visual update, especially during high-frequency interactions like scrolling or animations.</li></ul><h3>Limitations</h3><ul><li><strong>Performance</strong>: Frequent messaging (e.g., scrolling, animations) can clog the bridge.</li><li><strong>Latency</strong>: Synchronization delays between JS and native layers.</li><li><strong>Memory Overhead</strong>: Serialization and batching introduce additional costs.</li></ul><h3>The New Architecture (JSI, Fabric, TurboModules)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxZ4gdUohvwbht3y2_4ckg.png" /><figcaption>React Native Re-Architecture</figcaption></figure><p>Starting with version 0.68, React Native began its transition to the new architecture, which became the default by version 0.79.</p><h3>Core Innovations</h3><h4>1. JSI (JavaScript Interface)</h4><ul><li>Core element enabling React Native’s new architecture.</li><li>Facilitates direct access between JavaScript and native C++ objects.</li><li>Eliminates the need for serializing data across a bridge.</li><li>Allows synchronous function calls from JavaScript to native.</li><li>Reduces communication latency and improves runtime efficiency.</li><li>Foundation for enabling both TurboModules and Fabric Renderer.</li></ul><h4>2. TurboModules</h4><ul><li>Next-generation version of native modules in React Native.</li><li>Modules are loaded only when accessed (lazy-loaded).</li><li>Decreases initial app startup time and memory consumption.</li><li>Pairs with JSI to bypass the legacy bridge.</li><li>Speeds up access to native features like camera or storage.</li><li>Enhances runtime flexibility and overall application scalability.</li></ul><h4>3. Fabric Renderer</h4><ul><li>Modern rendering engine designed to replace the legacy UI Manager.</li><li>Improves user experience with faster and interruptible UI updates.</li><li>Introduces a consistent threading model for JS and native coordination.</li><li>Enables advanced, interruptible animations and responsive gestures.</li><li>Simplifies the way UI components are mapped between JS and native.</li></ul><h4>4. Codegen</h4><ul><li>Converts TypeScript or Flow type definitions into native code bindings.</li><li>Ensures type-safe communication between JavaScript and native layers.</li><li>Reduces manual boilerplate when writing custom native modules.</li><li>Validates module interfaces at build time, preventing runtime errors.</li><li>Enables tighter integration and cleaner APIs for TurboModules.</li></ul><h3>Architectural Layers</h3><p>React Native’s modern architecture is composed of several key layers that work together to deliver a faster, more scalable and developer-friendly environment</p><ul><li><strong>JavaScriptCore / Hermes</strong> — Executes all JavaScript logic. Hermes is Meta’s optimized JS engine for mobile, reducing app size and startup time.</li><li><strong>JSI (JavaScript Interface)</strong> — Acts as a low-level bridge replacement, enabling direct synchronous calls between JavaScript and native code.</li><li><strong>TurboModules</strong> — Load native modules only when needed, improving startup performance and reducing memory usage.</li><li><strong>Fabric</strong> — A new rendering engine that supports concurrent rendering and faster UI updates across platforms.</li><li><strong>Codegen</strong> — Automatically creates native bindings from JavaScript type definitions to ensure safe and efficient communication. For better compatibility with Medium’s editor, here’s a clean, copy-friendly format</li></ul><h3>Benefits</h3><p>React Native’s new architecture introduces tangible improvements across several dimensions of app development and runtime performance:</p><ul><li><strong>Lower Latency and Faster Execution</strong>: By replacing the asynchronous and batched bridge communication with direct access via JSI, actions such as UI updates and native module calls are executed more promptly and efficiently.</li><li><strong>Smoother Animations and Gesture Handling: </strong>Fabric’s concurrent rendering and prioritized updates enable better responsiveness, especially during intensive UI interactions like drag-and-drop, swiping, or animated transitions.</li><li><strong>Consistent UI Behavior Across Platforms: </strong>The unified threading and rendering model of Fabric ensures that behavior is aligned between iOS and Android, reducing platform-specific bugs and inconsistencies.</li><li><strong>Reduced App Startup Time: </strong>TurboModules are lazily loaded, meaning only the modules in use are initialized, leading to faster cold starts.</li><li><strong>Improved Type Safety and Developer Experience: </strong>With Codegen, native interfaces are validated at build time, reducing runtime crashes and the need for boilerplate code.</li></ul><h3>Migration Strategy</h3><h4>Who Should Migrate?</h4><ul><li><strong>New Projects</strong>: Strongly recommended to adopt the new architecture by default.</li><li><strong>Existing Projects</strong>: Should consider migration if facing performance bottlenecks or planning long-term scalability.</li></ul><h4>Migration Steps</h4><p>Migrating to the new architecture requires some hands-on configuration and validation. Here’s a simplified but actionable guide:</p><ol><li><strong>Enable the Architecture Flags</strong></li></ol><ul><li>For Android: Set newArchEnabled=true in your gradle.properties file.</li><li>For iOS: Add RCT_NEW_ARCH_ENABLED=1 in your Podfile and run pod install.</li></ul><p><strong>2. Update react-native.config.js</strong></p><ul><li>Define modules and their corresponding entry points so that Codegen can recognize and generate bindings for your native modules.</li></ul><p><strong>3. Check Third-Party Library Compatibility</strong></p><ul><li>Some native modules may not yet support the new architecture. Look for updates or community forks that add compatibility, or wrap such modules manually if needed.</li></ul><p><strong>4. Generate Bindings with Codegen</strong></p><ul><li>Run yarn react-native codegen to auto-generate the necessary bindings based on your module specifications.</li></ul><p><strong>5. Perform Platform-Specific Clean Builds</strong></p><ul><li>Clear old build caches: use ./gradlew clean for Android and xcodebuild clean for iOS.</li><li>Rebuild your app and validate functionality across both platforms.</li></ul><h3>Potential Challenges</h3><ul><li>Some third-party libraries may not yet support the new architecture.</li><li>Platform-specific testing is necessary to ensure stability.</li></ul><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*Ua1WZd8Hpsk_uzPXWvridA.png" /><figcaption>Outcome: faster, safer, more flexible</figcaption></figure><p>React Native has become a dominant force in mobile development by promising rapid development with near-native performance. However, its original bridge-based architecture posed limitations that became more evident as applications scaled in complexity and performance demand.</p><p>The transition to the new architecture — centered around the JavaScript Interface (JSI), TurboModules and the Fabric Renderer — has fundamentally redefined how React Native operates under the hood. This evolution unlocks lower latency, smoother animations, direct and synchronous native access and a significantly improved developer experience through tools like Codegen.</p><p>If you’re starting a new project today, embracing the new architecture is the best route forward. For existing applications, especially those facing performance bottlenecks or planning for long-term scalability, evaluating and planning a gradual migration to the new architecture is a smart investment.</p><p>React Native is not just keeping up — it’s evolving ahead. By adopting its modern architecture, developers can build faster, scale better and deliver experiences that feel truly native. The time to migrate is not later. It’s now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=549f1d2c4317" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jest: A Powerful Ally Enhancing Reliability in JavaScript Projects]]></title>
            <link>https://medium.com/@ibrahimcagrikoca/jest-a-powerful-ally-enhancing-reliability-in-javascript-projects-0b23326e102a?source=rss-30d9dbff34a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b23326e102a</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[İbrahim Çağrı Koca]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 14:10:43 GMT</pubDate>
            <atom:updated>2024-01-15T14:10:43.835Z</atom:updated>
            <content:encoded><![CDATA[<p>The success of JavaScript projects is measured not only by creating an aesthetic user interface but also by ensuring the code is reliable and error-free. Enhancing code quality, catching errors early, and establishing a reliable software development process are top priorities for developers today.</p><p>At this point, you may have heard of Jest and might be curious about understanding its significance in JavaScript projects. Jest is not just a testing tool; it is also an ally that provides reliability, performance, and efficiency for developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wg875iKXAJ0ac69auFvcOg.png" /></figure><h3>What is Jest?</h3><ul><li>Jest is a testing framework developed by Facebook and used in JavaScript projects.</li><li>It is employed in JavaScript and TypeScript-based projects to enhance code reliability and catch errors in the early stages.</li><li>It is particularly compatible with popular frontend frameworks like React, Vue and Angular.</li></ul><h4>Comprehensive Testing Tools</h4><ul><li>Jest offers an extensive set of tools for writing, running, and analyzing tests.</li><li>It includes features such as measuring test coverage, debugging, mocking, and managing asynchronous tests.</li></ul><h4>Snapshot Tests</h4><ul><li>Jest provides snapshot tests, especially useful for user interface (UI) testing. This involves capturing and saving the visual state of a component or page at a specific moment and later comparing it.</li></ul><h4>Code Coverage</h4><ul><li>Jest can generate code coverage reports, showing which parts of the project are tested and which are not</li></ul><h4>Continuous Integration</h4><ul><li>Jest can be integrated with popular Continuous Integration/Continuous Deployment (CI/CD) tools.</li><li>It ensures the project is continuously tested by automatically running tests with each new code change.</li></ul><h3>Vue Test Utils and Jest Setup and Basic Tests</h3><h4>Step 1: Vue Test Utils and Jest Installation</h4><p>As the first step, open the terminal in the directory of your project and enter the following commands sequentially:</p><pre>npm install --save-dev @vue/test-utils vue-jest</pre><h4>Step 2: Creating Jest and Vue Configuration Files</h4><p>Create jest.config.js and babel.config.js files in the root directory of your project:</p><pre>// jest.config.js<br>module.exports = {<br>  preset: &#39;@vue/cli-plugin-unit-jest&#39;,<br>  testMatch: [&#39;**/*.spec.js&#39;],<br>};</pre><pre>// babel.config.js<br>module.exports = {<br>  presets: [<br>    &#39;@vue/cli-plugin-babel/preset&#39;<br>  ]<br>};</pre><h4>Step 3: Basic Vue Test</h4><p>Now, let’s create a simple Vue component. Create a file named HelloWorld.vue:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;{{ message }}&lt;/h1&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  data() {<br>    return {<br>      message: &#39;Hello, Vue Test Utils!&#39;<br>    };<br>  }<br>};<br>&lt;/script&gt;</pre><p>Next, create a test file named HelloWorld.spec.js to test this component:</p><pre>import { mount } from &#39;@vue/test-utils&#39;;<br>import SampleComponent from &#39;@/components/SampleComponent.vue&#39;;<br><br>describe(&#39;SampleComponent&#39;, () =&gt; {<br>  it(&#39;should renders properly&#39;, () =&gt; {<br>    const wrapper = mount(SampleComponent);<br>    expect(wrapper.exists()).toBe(true);<br>  });<br><br>  it(&#39;should renders the correct message&#39;, () =&gt; {<br>    const wrapper = mount(SampleComponent);<br>    expect(wrapper.text()).toContain(&#39;Hello, Vue Test Utils!&#39;);<br>  });<br>});</pre><h4>Step 4: Running Tests</h4><p>Now, you can run the tests in the terminal with the following command:</p><pre>npm run jest</pre><h3>Asynchronous Test Scenarios</h3><h4>Step 1: Creating an Asynchronous Function</h4><p>Firstly, let’s create a simple asynchronous function to understand asynchronous test scenarios:</p><pre>// asyncFunction.js<br>export const fetchData = async () =&gt; {<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(() =&gt; {<br>      resolve(&#39;Asynchronous Data&#39;);<br>    }, 1000);<br>  });<br>}</pre><h4>Step 2: Asynchronous Test Scenario</h4><p>Now, let’s write an asynchronous test scenario in Jest to test this asynchronous function:</p><pre>// asyncFunction.test.js<br>const fetchData = require(&#39;./asyncFunction&#39;);<br><br>it(&#39;should get data correctly&#39;, async () =&gt; {<br>  const data = await fetchData();<br>  expect(data).toBe(&#39;Asynchronous Data&#39;);<br>});</pre><p>This test scenario calls the fetchData function, waits for the asynchronous operation to complete using await, and then checks the returned data.</p><h4>Step 3: Using Timeout</h4><p>If an asynchronous operation takes longer than expected, Jest defaults to waiting for 5 seconds. However, you can customize this timeout as follows:</p><pre>// asyncFunction.test.js<br>const fetchData = require(&#39;./asyncFunction&#39;);<br><br>test(&#39;should get data&#39;, async () =&gt; {<br>  const data = await fetchData();<br>  expect(data).toBe(&#39;Asynchronous Data&#39;);<br>}, 10000);// wait 10 seconds</pre><p>This informs Jest that this test scenario can take up to 10 seconds.</p><h3>Mocking and Simulation</h3><h4>Step 1: Mocking an External Service</h4><p>Firstly, let’s create a file named externalService.js to represent an external service:</p><pre>// externalService.js<br>export async function fetchData() {<br>  // You can use an actual HTTP request to simulate an external API call.<br>  const response = await fetch(&#39;https://example-api.com/data&#39;);<br>  const data = await response.json();<br>  return data;<br>}</pre><h4>Step 2: Jest Mocking and Test Scenario</h4><p>Now, let’s mock this external service with Jest and write a test scenario:</p><pre>// testFile.test.js<br>import { fetchData } from &#39;./externalService&#39;;<br><br>jest.mock(&#39;./externalService&#39;, () =&gt; ({<br>  fetchData: jest.fn(),<br>}));<br><br>it(&#39;should get data correctly&#39;, async () =&gt; {<br>  // Set the mock value that the external service would return<br>  const mockData = { message: &#39;Mock Data&#39; };<br>  fetchData.mockResolvedValue(mockData);<br><br>  // Call the external service to get the mocked value<br>  const result = await fetchData();<br><br>  // Check the expected mocked value<br>  expect(result).toEqual(mockData);<br><br>  // We can also check how many times Jest functions are called<br>  expect(fetchData).toHaveBeenCalledTimes(1);<br>});</pre><p>In this example, we use jest.mock to mock the fetchData function and set its resolved value using mockResolvedValue. Then, in the test scenario, we call this mocked function and check the expected value. toHaveBeenCalledTimes is used to check how many times the function was called.</p><h3>Application Tests in Jest</h3><p>Application tests aim to verify the general functionality of a software application and test user scenarios. Jest facilitates application tests with its provided features. These tests enhance the reliability of a web application, enabling early detection and correction of errors.</p><p>In this example, we’ll proceed with Vue.js, but a similar example can be used for React.js.</p><h3>Service File</h3><pre>// userService.js<br>export function getUser(id) {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      if (id === 1) {<br>        resolve({ id: 1, name: &#39;John Doe&#39; });<br>      } else {<br>        reject(new Error(&#39;User not found&#39;));<br>      }<br>    }, 1000);<br>  });<br>}</pre><h3>Vue Component</h3><pre>&lt;!-- UserComponent.vue --&gt;<br>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;User Information&lt;/h1&gt;<br>    &lt;button @click=&quot;fetchUser&quot;&gt;Fetch User&lt;/button&gt;<br>    &lt;div v-if=&quot;user&quot;&gt;<br>      &lt;p&gt;User ID: {{ user.id }}&lt;/p&gt;<br>      &lt;p&gt;User Name: {{ user.name }}&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div v-if=&quot;error&quot;&gt;<br>      &lt;p&gt;{{ error }}&lt;/p&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import { getUser } from &#39;@/services/userService&#39;;<br>import {ref} from &quot;vue&quot;;<br><br>const user = ref(null);<br>const error = ref(null)<br><br>const fetchUser = async () =&gt; {<br>  try {<br>    user.value = await getUser(1);<br>    error.value = null;<br>  } catch (e) {<br>    user.value = null;<br>    error.value = `Error fetching user: ${e.message}`;<br>  }<br>}<br>&lt;/script&gt;</pre><h4>Vue Component Testing</h4><pre>// UserComponent.spec.js<br>import { shallowMount } from &#39;@vue/test-utils&#39;;<br>import { getUser } from &#39;@/services/userService&#39;;<br>import UserComponent from &#39;@/components/UserComponent.vue&#39;;<br><br>jest.mock(&#39;@/services/userService&#39;);<br><br>describe(&#39;UserComponent&#39;, () =&gt; {<br>    let wrapper;<br>    const createWrapper = (options = {}) =&gt; {<br>        wrapper = shallowMount(UserComponent, {<br>            ...options<br>        });<br>    };<br>    it(&#39;fetches and displays user data on successful request&#39;, async () =&gt; {<br>        getUser.mockImplementation(() =&gt; ({ id: 1, name: &#39;John Doe&#39; }));<br><br>        createWrapper();<br><br>        await wrapper.find(&#39;button&#39;).trigger(&#39;click&#39;)<br>        expect(wrapper.vm.user.id).toBe(1);<br>        expect(wrapper.vm.user.name).toBe(&#39;John Doe&#39;);<br>        expect(wrapper.vm.error).toBeNull(); // Check error message<br>    });<br><br>    it(&#39;displays error message on failed request&#39;, async () =&gt; {<br>        getUser.mockImplementation(async () =&gt; {<br>            throw new Error(&#39;User not found&#39;)<br>        });<br>        createWrapper()<br><br>        await wrapper.find(&#39;button&#39;).trigger(&#39;click&#39;);<br>        expect(wrapper.vm.user).toBeNull(); // Check user id<br>        expect(wrapper.vm.error).toBe(&#39;Error fetching user: User not found&#39;);<br>    });<br>});</pre><h4>Service File Testing</h4><pre>// userService.test.js<br>import { getUser } from &#39;./userService&#39;;<br><br>describe(&#39;getUser function&#39;, () =&gt; {<br>    it(&#39;should resolve with user data when id is 1&#39;, async () =&gt; {<br>        const result = await getUser(1);<br>        expect(result).toEqual({ id: 1, name: &#39;John Doe&#39; });<br>    });<br><br>    it(&#39;should reject with an error when id is not 1&#39;, async () =&gt; {<br>        await expect(getUser(2)).rejects.toThrow(&#39;User not found&#39;);<br>    });<br>});</pre><p><strong>Conclusion</strong></p><p>In summary, Jest emerges as a robust testing ally, surpassing its role as a Facebook-developed framework. Its versatility with popular frontend frameworks, comprehensive testing toolset, and integration with CI/CD tools make Jest pivotal for code reliability. Examples, from basic setup to advanced scenarios, illustrate Jest’s practical application. Choosing Jest not only enhances JavaScript project quality but also fortifies the software development lifecycle, aligning with the demands of modern web development.</p><p>Thanks to: <a href="https://www.linkedin.com/in/bar%C4%B1s-berke-malkoc/">Barış Berke Malkoç</a></p><p>Github Repo: <a href="https://github.com/IbrahimCagriKoca/jest-testing-article">https://github.com/IbrahimCagriKoca/jest-testing-article</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b23326e102a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>