<?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 Samuel Fajreldines on Medium]]></title>
        <description><![CDATA[Stories by Samuel Fajreldines on Medium]]></description>
        <link>https://medium.com/@samuelfaj?source=rss-91243bf63d50------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*X8iDzXXCObiezwvSwdtbww.png</url>
            <title>Stories by Samuel Fajreldines on Medium</title>
            <link>https://medium.com/@samuelfaj?source=rss-91243bf63d50------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:23:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samuelfaj/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[All the Types of Tests in Software Development]]></title>
            <link>https://techblog.securityscorecard.com/all-the-types-of-tests-in-software-development-7f48283b5690?source=rss-91243bf63d50------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f48283b5690</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Samuel Fajreldines]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 13:52:31 GMT</pubDate>
            <atom:updated>2025-03-07T13:52:31.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XQmRIYCGguCXyxlU" /><figcaption>Photo by <a href="https://unsplash.com/@thisisengineering?utm_source=medium&amp;utm_medium=referral">ThisisEngineering</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Software testing is essential for delivering reliable, scalable, and secure applications. By rigorously testing every part of an application, teams catch bugs earlier, reduce technical debt, and achieve higher quality standards. Below is a detailed overview of the most common types of tests in software development, along with practical examples using JavaScript and Node.js. This guide demonstrates how multiple levels of testing can be integrated into a comprehensive testing strategy that ensures your applications remain robust — even as they evolve over time.</p><h3>The Importance of a Holistic Testing Strategy</h3><p>In modern software development, codebases can grow quickly and become highly complex, making it crucial to adopt a multi-faceted testing strategy. This strategy spans from low-level unit tests to high-level end-to-end tests, as well as specialized forms of testing like security and performance. By combining different test types, software teams can ensure coverage across the entire stack, identifying issues early and reducing long-term costs.</p><p>Below, each type of test is explained in depth, followed by a brief code example or usage scenario in JavaScript/Node.js to illustrate how you might implement it. While the specific technologies and frameworks may vary (e.g., Mocha, Jest, Jasmine, Cypress, or Playwright), the core principles remain consistent regardless of the chosen toolset.</p><h3>1. Unit Testing</h3><h3>Definition</h3><p>Unit tests focus on small, individual pieces of code. They verify that a “unit” of functionality, such as a function or method, behaves as expected under a variety of conditions. By isolating each component, teams rapidly identify exactly where and why an issue occurs.</p><h3>Why Unit Tests Matter</h3><p>• Rapid feedback loops: Catching errors in small sections of code makes debugging faster and less complex.<br>• Enhanced confidence: Well-tested modules reduce uncertainty when refactoring or adding features.<br>• Simplified code review: Developers can review code and tests together to confirm correctness.</p><h3>Example in Node.js</h3><p>Using Jest, a popular testing framework for JavaScript/TypeScript:</p><pre>// mathOperations.js<br>function add(a, b) {<br>  return a + b;<br>}<br><br>module.exports = { add };</pre><pre>// mathOperations.test.js<br>const { add } = require(&#39;./mathOperations&#39;);<br><br>test(&#39;adds two numbers correctly&#39;, () =&gt; {<br>  expect(add(2, 3)).toBe(5);<br>});</pre><p><strong>Explanation:</strong> Here, the function add is tested in isolation. Additional tests can be written to validate edge cases like negative numbers or floating-point values.</p><h3>2. Integration Testing</h3><h3>Definition</h3><p>Integration tests examine how separate modules or services interact with each other. This type of test goes beyond checking individual functions to evaluate the data flow and the correctness of responses between interconnected components (e.g., databases, APIs, or external services).</p><h3>Why Integration Tests Matter</h3><p>• Validating data flow: Ensures that modules interface properly, reducing the risk of unexpected behavior.<br>• Early detection of contract issues: Identifies mismatches in data formats, API endpoints, or shared libraries.<br>• Greater realism: Provides a more accurate representation of real-world usage than isolated unit tests.</p><h3>Example in Node.js</h3><p>Consider a simple Express.js application with a database call:</p><pre>// userController.js<br>const express = require(&#39;express&#39;);<br>const router = express.Router();<br>const UserModel = require(&#39;./UserModel&#39;);<br><br>router.get(&#39;/users/:id&#39;, async (req, res) =&gt; {<br>  const user = await UserModel.findById(req.params.id);<br>  if (!user) return res.status(404).send(&#39;User not found&#39;);<br>  res.json(user);<br>});<br><br>module.exports = router;</pre><pre>// integration.test.js<br>const request = require(&#39;supertest&#39;);<br>const express = require(&#39;express&#39;);<br>const userController = require(&#39;./userController&#39;);<br>const app = express();<br><br>app.use(&#39;/&#39;, userController);<br><br>describe(&#39;GET /users/:id&#39;, () =&gt; {<br>  it(&#39;should return a user when valid id is provided&#39;, async () =&gt; {<br>    // Mock database operations or use an in-memory DB<br>    const response = await request(app).get(&#39;/users/123&#39;);<br>    expect(response.status).toBe(200);<br>    expect(response.body).toHaveProperty(&#39;id&#39;, &#39;123&#39;);<br>  });<br>});</pre><p><strong>Explanation:</strong> This test verifies the interaction between the Express.js route and the data model. While not a full end-to-end test, it checks if data retrieval and routing logic are functioning together correctly.</p><h3>3. Functional Testing</h3><h3>Definition</h3><p>Functional testing examines a system’s components against specified requirements, ensuring that each part of the application performs its designated tasks. Unlike unit tests, functional tests generally look at bigger chunks of the system, focusing on “what” the software is supposed to do rather than “how” it does it.</p><h3>Why Functional Tests Matter</h3><p>• Requirement validation: Confirms that implemented features meet business and user requirements.<br>• More realistic coverage: Goes beyond isolated checks and simulates how users interact with specific features.<br>• Early detection of user-facing issues: Reduces the chance of shipping incomplete or incorrect functionality.</p><h3>Example in Node.js</h3><p>A login workflow might be tested functionally:</p><pre>// login.test.js<br>const request = require(&#39;supertest&#39;);<br>const app = require(&#39;./app&#39;); // Your Express.js app with auth routes<br><br>describe(&#39;User Login Functionality&#39;, () =&gt; {<br>  it(&#39;should return a token if user credentials are valid&#39;, async () =&gt; {<br>    const response = await request(app)<br>      .post(&#39;/auth/login&#39;)<br>      .send({ username: &#39;testUser&#39;, password: &#39;secret123&#39; });<br>    expect(response.status).toBe(200);<br>    expect(response.body).toHaveProperty(&#39;token&#39;);<br>  });<br><br>  it(&#39;should return 401 if credentials are invalid&#39;, async () =&gt; {<br>    const response = await request(app)<br>      .post(&#39;/auth/login&#39;)<br>      .send({ username: &#39;testUser&#39;, password: &#39;wrongPwd&#39; });<br>    expect(response.status).toBe(401);<br>  });<br>});</pre><p><strong>Explanation:</strong> Functional tests check if the system behaves according to expectations when provided with typical inputs. This ensures that the login feature fulfills its main purpose.</p><h3>4. End-to-End (E2E) Testing</h3><h3>Definition</h3><p>End-to-end tests simulate real-world user interactions, evaluating the full journey from the frontend layer through backend services, databases, and external integrations. By replicating true user experience, E2E tests validate that all layers of the application work together seamlessly.</p><h3>Why E2E Tests Matter</h3><p>• High confidence in readiness: Provides assurance that the final product works as intended in production-like conditions.<br>• Streamlined QA: Reduces the need for exhaustive manual testing for core user flows.<br>• Reduced integration errors: Ensures that changes in the backend don’t break the frontend, and vice versa.</p><h3>Example in Node.js</h3><p>Using Cypress:</p><pre>// cypress/e2e/login.spec.js<br>describe(&#39;Login Flow E2E&#39;, () =&gt; {<br>  it(&#39;logs in a user with valid credentials&#39;, () =&gt; {<br>    cy.visit(&#39;http://localhost:3000/login&#39;);<br>    cy.get(&#39;#username&#39;).type(&#39;testUser&#39;);<br>    cy.get(&#39;#password&#39;).type(&#39;correctPassword&#39;);<br>    cy.get(&#39;button[type=&quot;submit&quot;]&#39;).click();<br>    cy.url().should(&#39;include&#39;, &#39;/dashboard&#39;);<br>    cy.contains(&#39;Welcome, testUser&#39;);<br>  });<br>});</pre><p><strong>Explanation:</strong> This test launches a real browser (or headless browser environment), simulates user input, and verifies expected outcomes. The focus is the entire flow from the login page to the user’s dashboard.</p><h3>5. Performance Testing</h3><h3>Definition</h3><p>Performance tests measure how an application behaves under various loads and stress conditions. The primary goal is to identify bottlenecks, assess scalability, and ensure that response times, throughput, and resource usage meet the desired quality of service.</p><h3>Why Performance Tests Matter</h3><p>• Proactive bottleneck detection: Helps discover performance issues before they affect users.<br>• Capacity planning: Guides infrastructure decisions to handle traffic spikes and scale appropriately.<br>• Optimal user experience: Ensures swift response times, especially under heavy usage.</p><h3>Example in Node.js</h3><p>Using a tool like Artillery or k6 to test API endpoints:</p><pre>// sampleLoadTest.yml (Artillery syntax)<br>config:<br>  target: &quot;http://localhost:3000&quot;<br>  phases:<br>    - duration: 30<br>      arrivalRate: 10<br>scenarios:<br>  - flow:<br>      - get:<br>          url: &quot;/users&quot;</pre><p><strong>Explanation:</strong> This YAML configuration script instructs Artillery to hit the /users endpoint at a defined rate (10 requests per second for 30 seconds). The resulting logs and metrics help teams evaluate how the server performs under that load.</p><h3>6. Security Testing</h3><h3>Definition</h3><p>Security testing aims to discover vulnerabilities, risks, or threats within an application. It involves attempting to exploit potential security gaps — like unprotected endpoints, SQL injection, Cross-Site Scripting (XSS), or Cross-Site Request Forgery (CSRF) — to ensure the application can withstand malicious attacks.</p><h3>Why Security Tests Matter</h3><p>• Protects sensitive data: Ensures that user and business data remain confidential and integral.<br>• Regulatory compliance: Many industries have strict regulations around data security, making these tests critical.<br>• Preserves brand trust: Avoids damaging security breaches that can erode user confidence.</p><h3>Example in Node.js</h3><p>Using security scanning tools like OWASP ZAP or npm modules (such as npm audit) to detect known vulnerabilities:</p><pre># Check for known vulnerabilities in the project&#39;s dependencies<br>npm audit</pre><p><strong>Explanation:</strong> While not strictly a “test” in the sense of pass/fail, security scans highlight dependencies and code patterns that could pose risks. More advanced scripts or penetration tests can be automated as part of a continuous integration pipeline.</p><h3>7. Acceptance Testing</h3><h3>Definition</h3><p>Acceptance tests validate whether the software meets business and stakeholder requirements. They focus on the functionality that directly corresponds to user stories, ensuring the final product aligns with expectations set in project specifications.</p><h3>Why Acceptance Tests Matter</h3><p>• Business alignment: Guarantees that the technical implementation matches the intended use case.<br>• Stakeholder satisfaction: Provides a clear “thumbs up” from the client or product owner before release.<br>• Reduction in rework: Minimizes last-minute changes arising from unmet requirements.</p><h3>Example in Node.js</h3><p>Using a Behavior-Driven Development (BDD) framework like Cucumber:</p><pre># login.feature<br>Feature: User Login<br>  In order to access my account<br>  As a registered user<br>  I want to be able to log in using valid credentials<br><br>Scenario: Successful login<br>  Given I am on the login page<br>  When I enter valid credentials<br>  Then I should be redirected to the dashboard<br>  And I should see a welcome message</pre><p><strong>Explanation:</strong> This is a typical acceptance test scenario. The test is usually backed by step definitions in JavaScript that execute the necessary actions within a test framework like Cucumber.js.</p><h3>8. Load and Stress Testing</h3><h3>Definition</h3><p>While performance testing often focuses on general metrics, load and stress testing specifically push the system to extremes. Load testing checks the system’s performance under expected peak conditions, whereas stress testing tries to break the system by exceeding normal operational capacity to see how it degrades or recovers.</p><h3>Why Load and Stress Tests Matter</h3><p>• Error handling under high load: Ensures the application fails gracefully when pushed beyond capacity.<br>• System reliability insight: Reveals how the system recovers once the load returns to normal levels.<br>• Preventing downtimes: Helps teams plan for scenarios like flash sales or sudden traffic spikes.</p><h3>Example in Node.js</h3><p>A stress test scenario with k6:</p><pre>// stressTest.js<br>import http from &#39;k6/http&#39;;<br>import { sleep } from &#39;k6&#39;;<br><br>export let options = {<br>  stages: [<br>    { duration: &#39;2m&#39;, target: 100 }, // ramp up from 0 to 100 users over 2 minutes<br>    { duration: &#39;5m&#39;, target: 100 }, // stay at 100 users for 5 minutes<br>    { duration: &#39;2m&#39;, target: 200 }, // ramp up to 200 users<br>    { duration: &#39;5m&#39;, target: 200 }, // stay at 200 users for 5 minutes<br>    { duration: &#39;1m&#39;, target: 0 },   // ramp down<br>  ],<br>};<br><br>export default function() {<br>  http.get(&#39;http://localhost:3000/api/resource&#39;);<br>  sleep(1);<br>}</pre><p><strong>Explanation:</strong> This script escalates concurrent users to a point well beyond normal usage, allowing monitoring tools to capture how the application handles the surge and potential errors.</p><h3>9. Regression Testing</h3><h3>Definition</h3><p>Regression testing retests existing functionality to confirm that recent code changes haven’t unintentionally broken previously working features. It often accompanies new releases, updates, or refactoring efforts.</p><h3>Why Regression Tests Matter</h3><p>• Preserving reliability: Maintains confidence that existing code still works after modifications.<br>• Sustained velocity: Minimizes the risk of introducing new bugs while adding features or refactoring.<br>• Incremental confidence: Builds trust in the continuous integration pipeline, enabling more frequent deployments.</p><h3>Example in Node.js</h3><p>A regression suite can comprise a collection of unit, integration, and E2E tests:</p><pre>// All test files combined under a &quot;regression&quot; script<br>{<br>  &quot;scripts&quot;: {<br>    &quot;test:regression&quot;: &quot;jest --config=jest.config.js --runInBand&quot;<br>  }<br>}</pre><p>Using a single command, teams re-run the entire test suite to catch any regression issues across the codebase.</p><h3>10. Exploratory Testing</h3><h3>Definition</h3><p>Exploratory testing is an unscripted, manual approach where testers (or even developers) freely explore the application to discover unexpected behaviors, usability concerns, or edge cases that automated tests might overlook.</p><h3>Why Exploratory Tests Matter</h3><p>• Creative discovery: Encourages a tester’s intuition and curiosity to find hidden issues.<br>• Human-centric approach: Uncovers usability problems and subtle UI/UX flaws that are hard to detect with purely automated methods.<br>• Complement to automation: Brings an additional layer of certainty when combined with formal test scripts.</p><h3>Example in Practice</h3><p>While exploratory testing is predominantly manual, a tester might:</p><ol><li>Log in as different users with varying permissions.</li><li>Attempt unusual workflows — like canceling an order midway or refreshing the page at critical steps.</li><li>Record any bugs or anomalies for further investigation.</li></ol><p><strong>Explanation:</strong> This method relies on creativity and curiosity. Though less structured, it’s often extremely effective for catching corner cases and usability bottlenecks.</p><h3>Building a Comprehensive Testing Pipeline</h3><p>Combining these test types into a cohesive pipeline provides coverage at every layer of your application. High-level best practices to consider:</p><ol><li><strong>Automated CI/CD Integration</strong><br>Integrate tests into your build pipeline (e.g., GitHub Actions, Jenkins, or GitLab CI). This ensures that each commit automatically triggers test runs, providing immediate feedback on code changes.</li><li><strong>Prioritize Writing Clear Tests</strong><br>Descriptive test names, well-structured mock data, and consistent patterns in your test files make maintenance simpler and debugging faster.</li><li><strong>Use Version Control for Tests</strong><br>Keep test files in the same repository as your code. This encourages a tight feedback loop between development and testing.</li><li><strong>Leverage Code Coverage Tools</strong><br>Code coverage reports reveal which lines of code remain untested. Tools like Istanbul (nyc) can direct efforts to areas most likely to harbor bugs.</li><li><strong>Emphasize Collaboration</strong><br>Encourage developers, QA engineers, and other stakeholders to collaborate on test requirements and scenarios. This ensures broader coverage and highlights different viewpoints.</li></ol><h3>Conclusion</h3><p>A robust testing strategy is fundamental for any serious software project. By understanding — and implementing — a range of testing approaches, from unit and integration tests to performance, security, and exploratory testing, teams can significantly reduce the risk of defects slipping into production. This layered approach provides confidence that an application’s core functionality, data integrity, performance metrics, security standards, and user requirements all meet the high expectations of modern software solutions.</p><p>Each test type contributes to overall quality, but together they form a powerful safety net that guards against unforeseen issues. With the right tools, consistent best practices, and continuous improvement, any team can build and maintain complex Node.js and JavaScript applications with greater speed and assurance. The key is to view testing not as an afterthought, but as an integral part of the development lifecycle — one that elevates both developer and user confidence in the final product.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f48283b5690" width="1" height="1" alt=""><hr><p><a href="https://techblog.securityscorecard.com/all-the-types-of-tests-in-software-development-7f48283b5690">All the Types of Tests in Software Development</a> was originally published in <a href="https://techblog.securityscorecard.com/">SecurityScorecard Techblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Split React Components for Easy Unit Testing]]></title>
            <link>https://techblog.securityscorecard.com/how-to-split-react-components-for-easy-unit-testing-b9bb27ba64a0?source=rss-91243bf63d50------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9bb27ba64a0</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Samuel Fajreldines]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 15:19:07 GMT</pubDate>
            <atom:updated>2025-02-06T15:19:07.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O6Ye9PLGrTqEYHfs" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Building scalable React applications often involves managing user interfaces with components that can grow complex over time. When a component spans hundreds of lines, it becomes more challenging to understand, maintain, and unit test. Splitting large components into smaller, focused units is one of the most effective ways to boost maintainability and ensure higher test coverage. Below is a deep dive into why modularizing React components is crucial, how to implement it, and what best practices can make your code more testable in real-world scenarios.</p><h3>Why Splitting Components Matters</h3><p>Large, monolithic components can become a tangled mess. Functionality, rendering logic, and state management may all intertwine, creating a codebase that is brittle and difficult to test. Unit tests often fail to isolate specific functionality because too many concerns coexist in one place. By splitting components, each piece of functionality stands alone, minimizing side effects and making it straightforward to write robust, isolated tests.</p><h3>Benefits of Modular Components</h3><ol><li>Maintainability: Changes can be isolated to smaller sections of the code, minimizing the risk of unexpected side effects.</li><li>Reusability: Smaller components focused on single responsibilities are more likely to be reused in different parts of the application.</li><li>Enhanced Testability: Isolated logic becomes simpler to mock or spy on in unit tests, significantly increasing coverage and reliability.</li><li>Clarity: A smaller component allows developers to see exactly what is happening within a piece of the UI, making the code self-documenting.</li></ol><p>From a broader software engineering perspective, the skill to decompose large pieces of logic into smaller, testable parts is fundamental in various contexts, whether working with JavaScript, TypeScript, PHP, or even across DevOps pipelines. The same principles — simplicity, single responsibility, and clear boundaries — apply to serverless functions, containerized deployments, and backend services.</p><h3>Identifying When to Split a Component</h3><p>Not all larger components warrant an immediate split; however, there are red flags that signal you should consider refactoring:</p><ul><li>Multiple State Variables: If a component holds a wide range of states that don’t directly relate to each other, it’s a clue that more than one responsibility is at play.</li><li>Excessive Lines of Code: Although there is no strict rule on line count, components hitting several hundred lines are prime candidates for decomposition.</li><li>Complex Conditional Rendering: Nested conditionals and complicated logic can make a component difficult to comprehend. Splitting out specialized subcomponents often alleviates the confusion.</li><li>Difficult Testing: If unit tests require numerous mocks, stubs, and setup just to verify a simple feature, that’s a strong indication the component is doing too much.</li></ul><h3>Strategy #1: Container and Presentational Components</h3><p>A well-known approach to simplifying React code is following the container and presentational component pattern. This is especially effective when the application relies heavily on state management libraries such as Redux.</p><ul><li>Container Component: Focuses on data fetching, state management, and passing data to child components. Usually, these components do not contain elaborate UI elements or styles.</li><li>Presentational Component: Dedicated to rendering. Receives data and callbacks via props and focuses on HTML and CSS.</li></ul><p>By separating these concerns, each component is straightforward to test. Presentational components usually require minimal mocking, as they only render data passed through props. Container components, on the other hand, can be tested in isolation to ensure they fetch and manage data correctly. Testing responsibilities shrink dramatically when each of these parts is wholly responsible for a specific task.</p><h3>Example</h3><pre>// ContainerComponent.js<br>import React, { useEffect, useState } from &#39;react&#39;;<br>import PresentationalComponent from &#39;./PresentationalComponent&#39;;<br>import axios from &#39;axios&#39;;<br><br>const ContainerComponent = () =&gt; {<br>  const [items, setItems] = useState([]);<br>  useEffect(() =&gt; {<br>    axios.get(&#39;/api/items&#39;)<br>      .then(response =&gt; setItems(response.data))<br>      .catch(error =&gt; console.error(error));<br>  }, []);<br>  return &lt;PresentationalComponent items={items} /&gt;;<br>};<br><br>export default ContainerComponent;</pre><pre>// PresentationalComponent.js<br>import React from &#39;react&#39;;<br><br>const PresentationalComponent = ({ items }) =&gt; {<br>  if (!items.length) {<br>    return &lt;div&gt;No items available&lt;/div&gt;;<br>  }<br>  <br>  return (<br>    &lt;ul&gt;<br>      {items.map(item =&gt; &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;)}<br>    &lt;/ul&gt;<br>  );<br>};<br><br>export default PresentationalComponent;</pre><h3>Testing Example</h3><p>For the presentational component, a unit test can verify how it renders the list:</p><pre>// PresentationalComponent.test.js<br>import React from &#39;react&#39;;<br>import { render, screen } from &#39;@testing-library/react&#39;;<br>import PresentationalComponent from &#39;./PresentationalComponent&#39;;<br><br>test(&#39;renders list of items&#39;, () =&gt; {<br>  const mockItems = [{ id: 1, name: &#39;Test Item&#39; }];<br>  render(&lt;PresentationalComponent items={mockItems} /&gt;);<br>  expect(screen.getByText(&#39;Test Item&#39;)).toBeInTheDocument();<br>});</pre><p>Testing is streamlined because there’s no state or side effects to simulate. The container component test can focus on ensuring data is fetched and passed to the child properly, typically by mocking the network request.</p><h3>Strategy #2: Composing Components Based on Responsibility</h3><p>Another approach involves dissecting a large component by the user flows and responsibilities. For example, a user profile page might contain multiple features — profile information, settings, and a list of recent activities. Each feature can live in its own component, each responsible for rendering or manipulating a single slice of data.</p><p>When building large React applications in either JavaScript or TypeScript, it is common to combine multiple frameworks or libraries for tasks like form handling, routing, and global state management. Even in full-stack scenarios — using frameworks like Laravel or CodeIgniter on the back end — maintaining clear boundaries in the front-end leads to code that is more maintainable and test-friendly across the stack.</p><h3>Steps to Break Down by Responsibility</h3><ol><li>Identify Logical Boundaries: Determine which sections of the UI belong together conceptually (e.g., a settings panel, a user profile card, a notifications list).</li><li>Create Dedicated Components: Each logical boundary becomes a small, independent component.</li><li>Extract Shared Logic: If several sections share logic (like data fetching for different endpoints), consider extracting that into a custom hook or a higher-order component.</li><li>Write Dedicated Tests: Unit tests focus on validating each boundary separately, rather than verifying the entire page at once.</li></ol><h3>Strategy #3: Custom Hooks</h3><p>In React, custom hooks are often used to share logic between functional components. If a large component merges complex rendering with data manipulation or side effects, extracting the logic into custom hooks simplifies both your component and your testing strategy. When the complexity of state transitions, data fetching, or authentication balloons, custom hooks can keep the primary component clean.</p><h3>Hook Example</h3><p>Consider a component that fetches user data, manages loading states, and handles potential errors. Splitting this into a hook builds a separation:</p><pre>// useUserData.js<br>import { useState, useEffect } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>export const useUserData = (userId) =&gt; {<br>  const [data, setData] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    let isMounted = true;<br>    axios.get(`/api/user/${userId}`)<br>      .then(response =&gt; {<br>        if (isMounted) {<br>          setData(response.data);<br>          setLoading(false);<br>        }<br>      })<br>      .catch(err =&gt; {<br>        if (isMounted) {<br>          setError(err);<br>          setLoading(false);<br>        }<br>      });<br>    return () =&gt; {<br>      isMounted = false;<br>    };<br>  }, [userId]);<br><br>  return { data, loading, error };<br>};</pre><pre>// UserProfile.js<br>import React from &#39;react&#39;;<br>import { useUserData } from &#39;./useUserData&#39;;<br><br>const UserProfile = ({ userId }) =&gt; {<br>  const { data, loading, error } = useUserData(userId);<br>  if (loading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error!&lt;/div&gt;;<br>  return &lt;div&gt;{data.name}&lt;/div&gt;;<br>};<br><br>export default UserProfile;</pre><h3>Testing the Hook</h3><p>Since custom hooks are pure functions that rely on React’s life cycle, they can be tested using specialized test utilities like React Testing Library’s renderHook. By isolating the logic for fetching user data, the test can focus solely on the hook:</p><pre>// useUserData.test.js<br>import { renderHook } from &#39;@testing-library/react-hooks&#39;;<br>import { useUserData } from &#39;./useUserData&#39;;<br>import axios from &#39;axios&#39;;<br><br>jest.mock(&#39;axios&#39;);<br><br>test(&#39;returns user data after fetching&#39;, async () =&gt; {<br>  const mockData = { name: &#39;Alice&#39; };<br>  axios.get.mockResolvedValueOnce({ data: mockData });<br>  const { result, waitForNextUpdate } = renderHook(() =&gt; useUserData(1));<br>  expect(result.current.loading).toBe(true);<br>  await waitForNextUpdate();<br>  <br>  expect(result.current.data).toEqual(mockData);<br>  expect(result.current.loading).toBe(false);<br>  expect(result.current.error).toBeNull();<br>});</pre><p>This level of isolation wouldn’t be possible if everything lived in one large component. By decoupling rendering from data-fetching logic, each part can be tested separately.</p><h3>Strategy #4: Leveraging TypeScript for Better Structure</h3><p>Using TypeScript in React can make component splitting even more robust. Strong typing ensures each subcomponent adheres to a defined contract, minimizing the chances of introducing bugs when refactoring. When each smaller component specifies explicit prop types, the application becomes easier to scale without losing track of data relationships or possible null references.</p><h3>Tips for TypeScript Integration</h3><ol><li>Define Interfaces or Types for Props: Always be explicit about what props a component expects.</li><li>Use Utility Types: TypeScript provides Partial, Pick, and Omit to shape component props as needed.</li><li>Separate Type Declarations: Store types in dedicated files or directories for clarity, especially if they’re used across multiple components.</li><li>Combine with ESLint and Prettier: A consistent linting and formatting setup ensures that smaller TypeScript components remain legible and bug-free.</li></ol><h3>Practical Considerations for DevOps and Serverless Deployments</h3><p>Though component splitting is often framed in purely front-end terms, it has broader implications for overall software engineering workflows, including DevOps and serverless environments. Clear, testable React components assist continuous integration pipelines in two ways:</p><ol><li>Faster Test Runs: Smaller, focused tests reduce runtime in environments like GitLab CI, Jenkins, or GitHub Actions.</li><li>More Reliable Deployments: Clear test feedback loops minimize the risk of deploying broken code to AWS Lambda, Google Cloud Functions, or Azure Functions front ends.</li></ol><p>Modular front-end code can seamlessly integrate into microservices or serverless architectures where each function or service handles a specific responsibility. When the front end is equally modular, the entire application stack benefits from simpler debugging and more predictable release cycles.</p><h3>Strategy #5: Code Reviews and Automated Tooling</h3><p>Refactoring large React components into smaller, testable units can turn into a continuous practice. Automated tooling and best-practice guidelines make it easier to maintain standards across the team:</p><ul><li><strong>Linting Rules</strong>: Tools like ESLint can flag components exceeding a specified number of lines or complexity, prompting refactoring.</li><li><strong>Code Reviews</strong>: Encourage peer reviews focusing on component size, clarity, and testability.</li><li><strong>Continuous Integration</strong>: Automate unit tests for each pull request to ensure new features don’t balloon components unnecessarily.</li></ul><p>Over time, these automated and collaborative practices lead to a front-end architecture that remains clean, scalable, and easy to test.</p><h3>Putting It All Together</h3><p>Splitting React components is about more than just code aesthetics: it fundamentally improves maintainability, reusability, and testability. By leveraging container and presentational components, composing by responsibility, creating custom hooks, and using TypeScript, a React codebase can remain flexible and reliable. This approach extends beyond simple UI considerations, tying into larger engineering practices like DevOps, microservices, and serverless deployments, which all demand modularity and clarity.</p><p>Adopting these strategies involves an initial investment of time to refactor and set up the necessary tests. However, the payoff is well worth it: fewer bugs escape into production, new team members ramp up more quickly, and continuous integration pipelines run more smoothly. With a well-structured React application, the testing process becomes an asset rather than a chore, ultimately accelerating development cycles across the entire project.</p><p>A disciplined commitment to splitting components and writing high-quality unit tests supports more predictable, maintainable software. Whether dealing with TypeScript or JavaScript frameworks, whether deploying on AWS, Google Cloud, or Azure, the fundamental principle holds: keep components small, focused, and testable. Following this principle consistently paves the way for seamless scaling and a more confident development process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9bb27ba64a0" width="1" height="1" alt=""><hr><p><a href="https://techblog.securityscorecard.com/how-to-split-react-components-for-easy-unit-testing-b9bb27ba64a0">How to Split React Components for Easy Unit Testing</a> was originally published in <a href="https://techblog.securityscorecard.com/">SecurityScorecard Techblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS ECS: Managing Multiple Containers Easily.]]></title>
            <link>https://samuelfaj.medium.com/aws-ecs-managing-multiple-containers-easily-5343b770de68?source=rss-91243bf63d50------2</link>
            <guid isPermaLink="false">https://medium.com/p/5343b770de68</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Samuel Fajreldines]]></dc:creator>
            <pubDate>Mon, 15 May 2023 03:49:15 GMT</pubDate>
            <atom:updated>2023-05-15T04:00:41.223Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*NVax3EghVaRV2utS.png" /><figcaption>I ❤ Docker</figcaption></figure><p>At some point, you may have encountered the following question: “How can I manage and update multiple services running simultaneously on my server?” You may have tried supervisord, pm2, and others… But things can get really complicated when services have different build processes or use different languages.</p><p>In this post, we will discuss creating an individual container for each service, using AWS ECS to effectively manage them, and finally implementing GitLab CI to ensure consistent and effortless updates of these containers. Continue reading to discover how to make the management of your server a more peaceful and efficient process!</p><h3>Chapter 1: Terraform</h3><p>Terraform is a tool that allows you to write Infrastructure as Code (IaC), making it easier to manage and automate IT resources.</p><p>We start the configuration by creating a file called <em>main.tf</em>. This file will be the foundation of our infrastructure.</p><pre>provider &quot;aws&quot; {<br>    region = &quot;us-east-1&quot;<br>}</pre><p>This code specifies that we will be using AWS as our infrastructure provider, specifically in the us-east-1 region.</p><p>Next, we create the <em>aws-ecs.tf</em> file. This file will be responsible for creating the AWS ECS cluster and defining its permissions:</p><pre># This resource block creates an Amazon Elastic Container Service (ECS) cluster.<br># An ECS cluster is a logical grouping of tasks or services. In this case, the <br># cluster is named &quot;devninja_worker&quot;.<br>resource &quot;aws_ecs_cluster&quot; &quot;devninja_worker&quot; {<br>  name = &quot;devninja_worker&quot;<br>}<br><br># Here we&#39;re creating an AWS IAM (Identity and Access Management) role.<br># IAM roles are a secure way to grant permissions to entities that you trust.<br># This IAM role is named &quot;ecs_role&quot;.<br>resource &quot;aws_iam_role&quot; &quot;ecs_role&quot; {<br>  name = &quot;ecs_role&quot;<br><br>  # The &#39;assume_role_policy&#39; is a policy that grants an entity permission to assume the role.<br>  # In this case, it allows the EC2 service to assume this role.<br>  assume_role_policy = &lt;&lt;EOF<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;ec2.amazonaws.com&quot;<br>      },<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Sid&quot;: &quot;&quot;<br>    }<br>  ]<br>}<br>EOF<br>}<br><br># This block attaches a policy to the &quot;ecs_role&quot; IAM role.<br># The policy being attached provides the permissions necessary for ECS to make calls to AWS APIs on your behalf.<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecs_role_attachment&quot; {<br>  role       = aws_iam_role.ecs_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role&quot;<br>}<br><br># This block attaches another policy to the &quot;ecs_role&quot; IAM role.<br># The policy being attached provides read-only access to Amazon ECR (Elastic Container Registry).<br># This allows ECS tasks to pull Docker images from ECR.<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ecs_ecr_attachment&quot; {<br>  role       = aws_iam_role.ecs_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly&quot;<br>}<br><br># This creates an IAM instance profile that we can associate with our EC2 instances.<br># EC2 instances use instance profiles to make secure API requests.<br># Here, we are associating the &quot;ecs_role&quot; IAM role with the instance profile.<br>resource &quot;aws_iam_instance_profile&quot; &quot;ecs_instance_profile&quot; {<br>  name = &quot;ecs_instance_profile&quot;<br>  role = aws_iam_role.ecs_role.name<br>}</pre><p>This code creates an ECS cluster named devninja_worker and sets a series of permission policies for it.</p><p>Now that we have our cluster, we should add an instance (EC2) to it.</p><p>To add an instance to AWS ECS, it is necessary that it has a compatible Amazon Machine Image (AMI) (Amazon ECS-optimized Amazon Linux 2 AMI). Furthermore, when the machine starts, it must run the startup command.</p><p>We will create a folder called assets and, inside it, the file ecs-instance.sh:</p><p><em>assets/ecs-instance.sh:</em></p><pre>#!/bin/bash<br>echo ECS_CLUSTER=${cluster_name} &gt;&gt; /etc/ecs/ecs.config</pre><p>This script sets the ECS_CLUSTER variable in the ECS configuration file, which specifies to which cluster the EC2 instance will belong.</p><p>We continue the configuration with the <em>aws-ecs-ec2.tf</em> file:</p><pre># This resource block creates an AWS Security Group. <br># Security groups act as a virtual firewall for your instance to control inbound and outbound traffic.<br>resource &quot;aws_security_group&quot; &quot;ecs_tasks&quot; {<br>  # The name of the security group.<br>  name        = &quot;ecs_tasks_sg&quot;<br>  # Description for the security group.<br>  description = &quot;Allow inbound traffic on all ports&quot;<br><br>  # Ingress rules define what kind of traffic is allowed into the instances attached to this security group.<br>  ingress {<br>    # &#39;from_port&#39; and &#39;to_port&#39; both being 0 means all ports are allowed.<br>    from_port   = 0<br>    to_port     = 0<br>    # &#39;protocol&#39; being &#39;ALL&#39; means all protocols are allowed.<br>    protocol    = &quot;ALL&quot;<br>    # &#39;cidr_blocks&#39; being [&quot;0.0.0.0/0&quot;] means the traffic can originate from anywhere.<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  # Egress rules define what kind of traffic is allowed out from the instances attached to this security group.<br>  egress {<br>    # Similar to the ingress rule above, all traffic is allowed to go out to any IP on any protocol and port.<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;ALL&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}<br><br># This resource block creates an AWS EC2 instance. EC2 instances are virtual servers in Amazon&#39;s Elastic Compute Cloud (EC2) for running applications.<br>resource &quot;aws_instance&quot; &quot;ecs_instance&quot; {<br>  # The ID of the AMI, or Amazon Machine Image, which provides the information required to launch the instance.<br>  # You will need to replace this with the latest Amazon ECS-optimized Amazon Linux 2 AMI.<br>  ami           = &quot;ami-0ebb9b1c37ef501ab&quot;<br>  <br>  # The instance type. This defines the hardware of the host computer for the instance.<br>  instance_type = &quot;t3.small&quot;<br>  <br>  # The name of the key pair to use for the instance.<br>  key_name      = &quot;ttl-servers&quot;<br><br>  # An instance profile is a way to grant the necessary permissions to the EC2 instance that your ECS tasks run on.<br>  # We&#39;re referring to the name of the IAM instance profile that we created earlier.<br>  iam_instance_profile = aws_iam_instance_profile.ecs_instance_profile.name<br><br>  # User data is used to configure the instance upon launch. <br>  # Here, we&#39;re providing a shell script (ecs_instance.sh) as a template file, which sets the ECS cluster name.<br>  user_data = templatefile(&quot;${path.module}/assets/ecs_instance.sh&quot;, { cluster_name = aws_ecs_cluster.ttl_worker.name })<br><br>  # A list of security group IDs to assign to the instance. Here we&#39;re using the ID of the security group we created earlier.<br>  vpc_security_group_ids = [aws_security_group.ecs_tasks.id]<br><br>  # Tags are used to assign metadata to AWS resources. Here, we&#39;re assigning a Name tag to the instance.<br>  tags = {<br>    Name = &quot;ECS Instance&quot;<br>  }<br>}</pre><p>This code creates an EC2 instance and connects it to our ECS cluster. Note that we are using the latest version of the ECS-optimized AMI in a <strong>t3.small</strong> instance type.</p><p>Now that we have the AWS ECS cluster set up and an EC2 machine integrated with it, we should be able to upload our Dockerfile to AWS. For this, we will use AWS ECR and the <em>aws-ecr.tf</em> file:</p><pre># This resource block creates an AWS ECR (Elastic Container Registry) repository.<br>resource &quot;aws_ecr_repository&quot; &quot;devninja_ecr_1&quot; {<br><br>  # The &#39;name&#39; attribute specifies the name of the ECR repository.<br>  name = &quot;devninja_ecr_1&quot;<br><br>  # The &#39;image_tag_mutability&#39; attribute determines whether image tags can be overwritten.<br>  # Setting this to &#39;MUTABLE&#39; allows existing image tags to be overwritten by subsequent pushes.<br>  image_tag_mutability = &quot;MUTABLE&quot;<br><br>  # The &#39;image_scanning_configuration&#39; block is used to configure image scanning settings for the repository.<br>  image_scanning_configuration {<br><br>    # The &#39;scan_on_push&#39; attribute determines whether images are scanned for vulnerabilities upon being pushed to the repository.<br>    # Setting this to &#39;true&#39; enables automatic scanning upon each push.<br>    scan_on_push = true<br>  }<br>}</pre><p>This code creates an ECR repository called <strong>devninja_ecr_1</strong>, where we will store our Docker images.</p><p>Finally, it’s time to run our container in an ECS service. Each service requires a ‘task definition’. An AWS ECS task definition is a JSON file that describes one or more containers that make up your application. This definition specifies the container settings, including the resources they need, such as CPU and memory, which Docker images to use, which network ports to expose, and much more. It is, in essence, the ‘recipe’ for your application within the AWS ECS environment.</p><p>For this, we will create the <em>aws-ecs-task.tf</em> file:</p><pre># Setting up logging with CloudWatch<br>resource &quot;aws_cloudwatch_log_group&quot; &quot;devninja_worker_nodejs&quot; {<br>  name = &quot;/ecs/devninja_worker_nodejs&quot;<br>  retention_in_days = 14  # Logs will be retained for 14 days<br>}<br><br># Task Definition (We will use the Apache image as an example)<br>resource &quot;aws_ecs_task_definition&quot; &quot;devninja_worker_nodejs&quot; {<br>  family                   = &quot;devninja_worker_nodejs&quot;<br>  network_mode             = &quot;bridge&quot;  # Using bridge network mode<br>  cpu                      = &quot;256&quot;  # CPU value for the task<br>  memory                   = &quot;128&quot;  # Memory value for the task<br>  requires_compatibilities = [&quot;EC2&quot;]  # This task requires EC2 compatibility<br><br>  # Container definitions specify the Docker image and configuration options for each container in the task<br>  container_definitions = &lt;&lt;DEFINITION<br>  [<br>    {<br>      &quot;name&quot;: &quot;devninja_worker_nodejs&quot;,<br>      &quot;image&quot;: &quot;${aws_ecr_repository.devninja_ecr_1.repository_url}:main&quot;,  # Using the Docker image from our ECR repository<br>      &quot;cpu&quot;: 256,<br>      &quot;memory&quot;: 128,<br>      &quot;essential&quot;: true,<br>      &quot;portMappings&quot;: [<br>        {<br>          &quot;containerPort&quot;: 3000,<br>          &quot;hostPort&quot;: 3000,<br>          &quot;protocol&quot;: &quot;tcp&quot;<br>        }<br>      ],<br>      &quot;logConfiguration&quot;: {<br>        &quot;logDriver&quot;: &quot;awslogs&quot;,<br>        &quot;options&quot;: {<br>          &quot;awslogs-group&quot;: &quot;/ecs/devninja_worker_nodejs&quot;,<br>          &quot;awslogs-region&quot;: &quot;us-east-1&quot;,<br>          &quot;awslogs-stream-prefix&quot;: &quot;ecs&quot;<br>        }<br>      }<br>    }<br>  ]<br>  DEFINITION<br>}<br><br># Adding our task to the cluster<br>resource &quot;aws_ecs_service&quot; &quot;devninja_worker_nodejs&quot; {<br>  name            = &quot;devninja_worker_nodejs&quot;<br>  cluster         = aws_ecs_cluster.devninja_worker.id<br>  task_definition = aws_ecs_task_definition.devninja_worker_nodejs.arn<br>  desired_count   = 1  # We want one running instance of this task<br>  launch_type     = &quot;EC2&quot;  # This service will run on EC2 instances<br>}</pre><p>This block of code does several things. First, it creates a CloudWatch log group that will store the logs of our application. Then, it defines a ‘task definition’ for a container holding our AWS ECR image, including the amount of CPU and memory that the container should use, and the log configuration that the container should follow and the ports that need to be opened by the container.</p><p>Finally, it adds our ‘task definition’ to our ECS cluster. Note that we are using the “EC2” launch type, which means that our container will run on an EC2 instance.</p><p>At this point, we have an ECS cluster configured and running with a single service. But how can we ensure that changes to our code are reflected in our service? The answer is Gitlab CI.</p><p>To be continued…</p><p>I hope you’ve found this guide helpful so far. If you have any questions or suggestions, please don’t hesitate to leave a comment below!</p><p>P.S.: You can find all the post files here: <a href="https://github.com/samuelfaj/aws-ecs-terraform-ci">https://github.com/samuelfaj/aws-ecs-terraform-ci</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5343b770de68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>