<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Iheanacho Ebere</title>
    <description>The latest articles on DEV Community by Iheanacho Ebere (@nachothegre8t).</description>
    <link>https://dev.to/nachothegre8t</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1004787%2F18f1f58a-3ad0-43ee-8946-a4ae6f4c8cf3.png</url>
      <title>DEV Community: Iheanacho Ebere</title>
      <link>https://dev.to/nachothegre8t</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/nachothegre8t"/>
    <language>en</language>
    <item>
      <title>Mocking Axios GET Requests: A Practical Guide for Reliable React Testing using Jest</title>
      <dc:creator>Iheanacho Ebere</dc:creator>
      <pubDate>Tue, 23 Jan 2024 08:53:43 +0000</pubDate>
      <link>https://dev.to/nachothegre8t/mocking-axios-get-requests-a-practical-guide-for-reliable-react-testing-using-jest-3kik</link>
      <guid>https://dev.to/nachothegre8t/mocking-axios-get-requests-a-practical-guide-for-reliable-react-testing-using-jest-3kik</guid>
      <description>&lt;p&gt;For projects involving API data fetching, testing can be challenging, requiring actual API calls to validate results. However, this approach introduces issues like expense and speed variations due to network conditions. Mocking emerges as a solution, enabling developers to isolate their testing environment from external dependencies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What Is Mocking?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Mocking is a technique that substitutes real objects or functions with simulated versions during testing. This practice allows developers to isolate components, control responses, and improve test speed and reliability.&lt;/p&gt;

&lt;p&gt;During my exploration, I stumbled upon a fantastic article by Volodymyr Hudyma, titled &lt;a href="https://vhudyma-blog.eu/3-ways-to-mock-axios-in-jest/"&gt;3 Ways To Mock Axios In Jest&lt;/a&gt;. The article outlines three approaches to mocking Axios, with two involving additional packages.&lt;/p&gt;

&lt;p&gt;In this guide, we'll create a component utilizing Axios to make a GET request for fetching a list of users and rendering it in the DOM. Through this example, we'll dive into one approach to mocking in Jest.&lt;/p&gt;

&lt;p&gt;The objective of this comprehensive guide is to provide you with a clear understanding of how to efficiently mock external API response when utilizing Axios, ensuring a consistent and reliable testing environment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;JavaScript Fluency: Understanding JavaScript is essential for working with React and testing frameworks.&lt;/li&gt;
&lt;li&gt;React Basics: Familiarity with React components and their lifecycle is required to follow the tutorial effectively.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Project Setup&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Component Creation: We'll build a React component that uses Axios to retrieve a user list and render it on the screen.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState } from "react"
import axios from "axios"                                                                       



function UserList() {
    const [userList, setUserList] = useState([])

    useEffect(()=&amp;gt;{
        const fetchUserList = async() =&amp;gt;{
            try{
                await axios.get("https://jsonplaceholder.typicode.com/users").then((res) =&amp;gt; setUserList(res.data))
            } catch(err) {
                console.log(err)
            }
        }

        fetchUserList()
    },[])

    return (
        &amp;lt;div&amp;gt;
            &amp;lt;h2&amp;gt;Users&amp;lt;/h2&amp;gt;
            {
                userList.map((user)=&amp;gt;{
                    return(
                        &amp;lt;div key={user.id}&amp;gt;
                            &amp;lt;p&amp;gt;{user.name}&amp;lt;/p&amp;gt;
                            &amp;lt;p&amp;gt;{user.email}&amp;lt;/p&amp;gt;
                        &amp;lt;/div&amp;gt;
                    )
                })
            }
        &amp;lt;/div&amp;gt;
    )
}

export default UserList
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This component serves as a fundamental illustration of making an API call using the useEffect and useState hooks to manage state changes before the DOM reloads.&lt;/p&gt;

&lt;p&gt;To effectively test this component, it's essential to isolate it from the external API and external modules by mocking Axios and controlling its response when called. This approach grants us complete control over the component, allowing precise interaction during testing. Below is an example of how our "userList.test.js" file should be structured:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { render, screen, waitFor } from "@testing-library/react";
import UserList from "./userList";
import axios from "axios";
//mock the axios module
jest.mock("axios");

const dummyUserList = [
  {
    userId: 1,
    id: 1,
    name: "Nacho",
    email: "nacho@gmail.com"
  },
  {
    userId: 1,
    id: 2,
    name: "Nochi",
    email: "nochi@gmail.com"
  },
  {
    userId: 1,
    id: 3,
    name: "Davidszn",
    email: "david@gmail.com"
  },
];

describe("User component", () =&amp;gt; {
  it("should render user header", async () =&amp;gt; {
    render(&amp;lt;UserList /&amp;gt;);

    // Wait for the asynchronous data fetching to complete
    await waitFor(() =&amp;gt; {
      expect(screen.getByText(/users/i)).toBeInTheDocument();
    });
  });
  it("should render user list after fetching list", async ()=&amp;gt;{
    //resolving the get request with the dummyUserList
    axios.get.mockResolvedValue({ data: dummyUserList });

    // or you could use the following depending on your use case:
    // axios.get.mockImplementation(() =&amp;gt; Promise.resolve(dummyUserList))

    render(&amp;lt;UserList/&amp;gt;)
    //another alternative to wait for block is findby queries
    expect(await screen.findByText(/nacho@gmail.com/i)).toBeInTheDocument()

    // Optionally, you can check for the number of calls to axios.get
    expect(axios.get).toHaveBeenCalledTimes(1);
  })
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Jest mock method allows us to mocks a module and returns an auto-mocked version when required during the test. Test 1 ensures the component renders the header text "users" after asynchronous data fetching. Utilize &lt;a href="https://testing-library.com/docs/dom-testing-library/api-async/#waitfor"&gt;waitFor&lt;/a&gt; method to wait for the asynchronous operation to complete. Test 2 simulates the GET request using &lt;code&gt;axios.get.mockResolvedValue&lt;/code&gt; method to resolve the response with the &lt;em&gt;dummyUserList&lt;/em&gt; array then checks if the user list renders after fetching, using &lt;a href="https://testing-library.com/docs/queries/about"&gt;screen.findByText&lt;/a&gt; method. We can also optionally verify the number of calls to &lt;code&gt;axios.get&lt;/code&gt;. There are also various Jest mock methods such as &lt;a href="https://jestjs.io/docs/mock-function-api#jestfnimplementation"&gt;jest.fn&lt;/a&gt;, &lt;a href="https://jestjs.io/docs/jest-object#jestspyonobject-methodname"&gt;jest.spyOn&lt;/a&gt;, depending on the specific need or task.&lt;/p&gt;

&lt;p&gt;If you run the test using &lt;code&gt;npm test&lt;/code&gt;, you may encounter the following result:.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    SyntaxError: Cannot use import statement outside a module

      1 | import { useEffect, useState } from "react"
    &amp;gt; 2 | import axios from "axios"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How to fix the "Cannot use import statement outside a module" for axios libary?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This issue arises from a clash between the testing environment and the module, often related to the use of different JavaScript module systems (CommonJS vs. ES6 modules). It's a relatively rare but known issue, especially with Axios.&lt;/p&gt;

&lt;p&gt;A potential fix for this problem involves adding a few specific lines to your "package.json" file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"type": "module"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This informs Node.js that your project is using ES6 modules.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  "jest": {
    "transformIgnorePatterns": ["node_modules/(?!axios)/"]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The "transformIgnorePatterns" option is a solution that tells Jest to ignore transformation for files inside node_modules except for those in the axios module. Your "package.json" file should be configured as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "type": "module",
  "scripts": {
    "test": "npm test",
     // other scripts
  },
  "dependencies": {
    // your dependencies
  },
  "jest": {
    "transformIgnorePatterns": ["node_modules/(?!axios)/"]
}
  // other configurations
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After restarting the test, you should obtain the following results&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; PASS  src/user/userCard.test.js
  User component
    √ should render user header (327 ms)
    √ should render user list after fetching list (26 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        4.893 s
Ran all test suites matching /userCard.test.js/.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The test passed because we were able to intercept the axios 'GET' request and changed the response to our dummyList so the Dom renders data from the dummyList, which use to test the component.&lt;/p&gt;

&lt;p&gt;I hope this article has simplified the concept of mocking in React testing, especially in the context of handling bugs related to module systems. By intentionally choosing axios libary, I aimed to share a practical solution to a common issue I faced earlier on. Our exploration into the lost art of testing in React is far from over, and I'm excited to announce that the journey continues with the upcoming article on testing a react app using Redux.&lt;/p&gt;

&lt;p&gt;Stay jiggy, and happy testing!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;References&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://codedamn.com/news/nodejs/cannot-use-import-statement-outside-a-module"&gt;https://codedamn.com/news/nodejs/cannot-use-import-statement-outside-a-module&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.csrhymes.com/2022/03/09/mocking-axios-with-jest-and-typescript.html"&gt;https://www.csrhymes.com/2022/03/09/mocking-axios-with-jest-and-typescript.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.reddit.com/r/reactjs/comments/176a5hh/getting_syntaxerror_cannot_use_import_statement/?rdt=42688&amp;amp;onetap_auto=true"&gt;https://www.reddit.com/r/reactjs/comments/176a5hh/getting_syntaxerror_cannot_use_import_statement/?rdt=42688&amp;amp;onetap_auto=true&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>jest</category>
      <category>testing</category>
      <category>react</category>
    </item>
    <item>
      <title>Exploring the Basics of React Testing: A Journey into Rendering and Interaction</title>
      <dc:creator>Iheanacho Ebere</dc:creator>
      <pubDate>Wed, 10 Jan 2024 22:18:47 +0000</pubDate>
      <link>https://dev.to/nachothegre8t/exploring-the-basics-of-react-testing-a-journey-into-rendering-and-interaction-8oi</link>
      <guid>https://dev.to/nachothegre8t/exploring-the-basics-of-react-testing-a-journey-into-rendering-and-interaction-8oi</guid>
      <description>&lt;p&gt;When building a website and integrating diverse features, manual testing may appear viable at the outset. However, for larger projects, relying solely on manual testing becomes impractical prompting the need for the implementation of unit tests. Not only do unit tests enhance the integrity of your application, but they also provide a more scalable and efficient approach to ensuring the functionality of your codebase.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is unit test?&lt;/strong&gt;&lt;br&gt;
Unit testing is a testing methodology that assesses individual software units in isolation. It involves scrutinizing the output of a function for any given input. This process ensures the verification of component rendering for specific inputs to React components.&lt;/p&gt;

&lt;p&gt;In essence, writing unit tests is simply writing code to ascertain the code works as expected.&lt;/p&gt;

&lt;p&gt;In this article we are going to be looking at the fundamentals of react unit testing ,exploring essential concepts and structures.&lt;/p&gt;

&lt;p&gt;Both Jest and React Testing Library come pre-packaged with Create React App and adhere to the guiding principle that testing apps should resemble how the software will be used.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisties&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Npm and knowlegde on node and javascript&lt;/li&gt;
&lt;li&gt;Familiarity on &lt;a href="https://legacy.reactjs.org/"&gt;react&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In testing, the focus is on ensuring that your code performs as intended in comparing expected and actual outputs. The major aspects to test in your code include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Rendering with or without props: Check if a component renders correctly with or without specific props.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Rendering with state changes: Test how a component renders when there are changes in its state.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Reacting to user interactions: Assess how a component responds to user interactions.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However, certain elements do not require testing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Actual Implementation: We don't need to test the exact implementation, we just need to ensure component produces the expected output.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Third-Party Libraries: If utilizing third-party libraries like Material UI, there's no need to test them, as they are presumed to be well-tested.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In react unit testing , there's a conventional test block structure that is followed, which is :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a test block using either &lt;em&gt;describe-it/test&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;Inside the test block, the first thing we do is to render the component that we want to test.&lt;/li&gt;
&lt;li&gt;Select the elements that we want to interact with queries.&lt;/li&gt;
&lt;li&gt;Interact with those elements.&lt;/li&gt;
&lt;li&gt;Assert that the results are as expected.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;How To Setup Our Project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First create the react app with the create-react-app command. Since we'll be using Jest , its already pre-installed in your app.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npx create-react-app react-test-project&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Ensure the following line is in the setupTests.js file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import '@testing-library/jest-dom'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How To Write Our First Test ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Step 1: Create a component&lt;/p&gt;

&lt;p&gt;Let’s create a component called Counter, that renders "Counting App".&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from "react";

const Counter = () =&amp;gt; {

    return (
        &amp;lt;div&amp;gt;
            &amp;lt;p&amp;gt;Counting App&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
    );
};

export default Counter;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we just need to test if the Counter renders "Counting App". Now, where should we write the tests? We can write them inside files with .js suffix in “__ &lt;strong&gt;tests&lt;/strong&gt; __” folders or files with “.test.js” suffix or files with “.spec.js” suffix anywhere inside our src folder and jest will pick it up. &lt;/p&gt;

&lt;p&gt;Create a “counter.test.js” file inside the src folder and add the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Counter from "./counter";
import { render, screen } from "@testing-library/react";


describe("Counter Component", ()=&amp;gt; {
    it("should render counter component", ()=&amp;gt;{
        render(&amp;lt;Counter /&amp;gt;)
        expect(screen.getByText(/counting app/i)).toBeInTheDocument()
    })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; In order to let jest know about this test file, it’s important to use the extension .test.js.&lt;/p&gt;

&lt;p&gt;The above test can be described as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The “describe” block is employed to group together a set of tests under the overarching category of "Counter Component."&lt;/li&gt;
&lt;li&gt;The “it” block is used to define individual tests within the describe block. Alternatively, the “test” block can also be used for the same purpose. Both methods take two parameters:&lt;/li&gt;
&lt;li&gt;The first parameter names the test, such as "Render Counter Component."&lt;/li&gt;
&lt;li&gt;The second parameter is a callback function, outlining the specifics of the actual test.&lt;/li&gt;
&lt;li&gt;The render() method from the React Testing Library is utilized in the test to render the Counter component within a virtual DOM.&lt;/li&gt;
&lt;li&gt;The screen property, offered by the React Testing Library, facilitates the selection of elements for testing based on the previously assigned test IDs.&lt;/li&gt;
&lt;li&gt;The expect property is used to make assertions, comparing the actual results with the expected results.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With these foundational concepts in place, the testing process covers the basic rendering aspects. The subsequent step involves implementing counting functionality in the Counter component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from "react";

const Counter = () =&amp;gt; {
    const [countValue, setCountValue] = useState(0);

    const increaseCount = () =&amp;gt; {
        setCountValue((prevCount) =&amp;gt; prevCount + 1);
    };

    const decreaseCount = () =&amp;gt; {
        setCountValue((prevCount) =&amp;gt; prevCount - 1);
    };

    return (
        &amp;lt;div&amp;gt;
            &amp;lt;h2&amp;gt;Counting App&amp;lt;/h2&amp;gt;
            &amp;lt;button 
                data-testid="increase" 
                aria-label="Increase Count"
                onClick={increaseCount}
            &amp;gt;
                +
            &amp;lt;/button&amp;gt;
            &amp;lt;p data-testid="count"&amp;gt;{countValue}&amp;lt;/p&amp;gt;
            &amp;lt;button  
                data-testid="decrease" 
                aria-label="Decrease Count"
                onClick={decreaseCount}
            &amp;gt;
                -
            &amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
    );
};

export default Counter;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This component that simply increases and decreases a numeric value at the click of respective buttons. Now our updated test file should look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Counter from "./counter";
import { fireEvent, render, screen } from "@testing-library/react";

describe("Counter Component", () =&amp;gt; {
    it("should render counter component", () =&amp;gt; {
        render(&amp;lt;Counter /&amp;gt;)
        expect(screen.getByText(/counting app/i)).toBeInTheDocument()
    })

    it("should increment counter when increment btn is clicked", () =&amp;gt; {
        // render the component on virtual dom
        render(&amp;lt;Counter /&amp;gt;);

        //select the elements you want to interact with
        const counter = screen.getByTestId("count");
        //expect counter to initialize at 0.
        expect(counter).toHaveTextContent("0");
        //select increment btn
        const incrementBtn = screen.getByTestId("increase");

        //interact with those elements
        fireEvent.click(incrementBtn);

        //assert the expected result
        expect(counter).toHaveTextContent("1");
    })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the second test block, we are evaluating the rendering and increment functionality of the counter component. Here's a breakdown of the test:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Render the counter on the virtual DOM.&lt;/li&gt;
&lt;li&gt;Utilize the screen property to select elements.&lt;/li&gt;
&lt;li&gt;Set an expectation assertion to check if the counter initializes at 0.&lt;/li&gt;
&lt;li&gt;Use the fireEvent function to simulate a click on the increment button.&lt;/li&gt;
&lt;li&gt;The test asserts that the counter's text content changes and updates as expected.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now after running the test, the result obtained can be seen below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; PASS  src/counter/counter.test.js
  Counter Component
    √ should render counter component (39 ms)
    √ should increment counter when increment btn is clicked (22 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        4.188 s
Ran all test suites matching /counter/i.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The assertions confirm that the Counter component not only renders as anticipated but also functions correctly when incrementing. I trust these tests have provided a foundational understanding of exploring basic rendering and interactive features within a React component using the React Testing Library. However, this marks just the initial phase of our testing journey ,as you continue your journey into the world of testing, the next step involves exploring more advanced techniques. My upcoming article &lt;a href="https://dev.to/nachothegre8t/mocking-axios-get-requests-a-practical-guide-for-reliable-react-testing-using-jest-3kik"&gt;Mocking Axios GET Requests&lt;/a&gt;, will dive deeper into the critical aspects of mocking and asynchronous testing. Make sure to follow along for a comprehensive understanding of these advanced testing concepts.&lt;/p&gt;

&lt;p&gt;Stay focused, and happy testing!&lt;/p&gt;

&lt;p&gt;References&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://jestjs.io/docs/getting-started"&gt;https://jestjs.io/docs/getting-started&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://testing-library.com/docs/"&gt;https://testing-library.com/docs/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://legacy.reactjs.org/docs/getting-started.html"&gt;https://legacy.reactjs.org/docs/getting-started.html&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>beginners</category>
      <category>react</category>
      <category>jest</category>
      <category>webdev</category>
    </item>
    <item>
      <title>A Go Drawback Lesson: Exploring OOP in GoLang in greater depth.</title>
      <dc:creator>Iheanacho Ebere</dc:creator>
      <pubDate>Mon, 09 Jan 2023 23:15:53 +0000</pubDate>
      <link>https://dev.to/nachothegre8t/a-go-drawback-lesson-exploring-oop-in-golang-in-greater-depth-4f8g</link>
      <guid>https://dev.to/nachothegre8t/a-go-drawback-lesson-exploring-oop-in-golang-in-greater-depth-4f8g</guid>
      <description>&lt;p&gt;My quest to study Golang began in an &lt;a href="https://www.altschoolafrica.com/" rel="noopener noreferrer"&gt;alt-school Africa&lt;/a&gt;. They provided an exam to gauge how well we understood the essential OOP concept of Golang through a number of lectures and instructions. We were asked to offer a solution to the inventory systems using the OOP paradigm; the significance of an inventory cannot be overstated. This is as a result of its many advantages and social significance.&lt;/p&gt;

&lt;p&gt;In this article, I'd be discussing OOP in Goland and how I was able to provide some solutions to the inventory system.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;br&gt;
In order to follow through this article:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You need to have a basic understanding of programming.&lt;/li&gt;
&lt;li&gt;You need to have a basic understanding of Go programming concepts such as variables, data types, structures, maps, interfaces and packages.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The Assessment question&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;John has just opened up his car selling shop, to sell different cars. He gets the cars he needs to sell from different people and they all bring it to him.&lt;br&gt;
He needs to manage the list of cars he has, attach a price to them, and put them on display to be sold, basically John needs an inventory to manage cars &amp;amp; to manage sales. For instance,&lt;/p&gt;

&lt;p&gt;He needs to see the number of cars that are left to be sold&lt;br&gt;
He needs to see the sum of the prices of the cars left&lt;br&gt;
He needs to see the number of cars he has sold&lt;br&gt;
He needs to see the sum total of the prices of cars he has sold&lt;br&gt;
He needs to see a list of orders for the sales he made&lt;br&gt;
Using the knowledge of OOP in Go, Build simple classes for the following “objects”:&lt;/p&gt;

&lt;p&gt;Car&lt;br&gt;
Product&lt;br&gt;
Store&lt;br&gt;
The Car class can have any car attributes you can think of.&lt;/p&gt;

&lt;p&gt;The Product class should have attributes of a product i.e (the product, quantity of the product in stock, price of the product). A car is a product of the store, but there can be other products so the attribute of the car can be promoted to the Product. The Product class should have methods to display a product, and a method to display the status of a product if it is still in stock or not.&lt;/p&gt;

&lt;p&gt;The Store class should have attributes like&lt;/p&gt;

&lt;p&gt;Number of products in the store that are still up for sale&lt;br&gt;
Adding an Item to the store&lt;br&gt;
Listing all product items in the store&lt;br&gt;
Sell an item&lt;br&gt;
Show a list of sold items and the total price&lt;/p&gt;

&lt;p&gt;This assessment made me realize how unprepared I was for the most fundamental and crucial core notion of GoLang as well as programming in general,known as OOP(&lt;em&gt;Object-Oriented Programming&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is OOP?&lt;/strong&gt;&lt;br&gt;
I think of OOP as a programming architecture that is heavily based on the ideas of classes and objects. This grants us flexibilty of creating reusable pieces of code blueprints (usually called classes), which are used to create individual instances of objects. We can easily recognize some classes using this insight and the data from the assessment, such as:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Car&lt;/strong&gt;: Represents a specific car in the store which is also product, this means that it has all the attributes and methods of the Product struct.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Product&lt;/strong&gt;: Represents a product in the store including cars called &lt;em&gt;Embedding&lt;/em&gt;, this means the cars class also its inherits attributes from Product Class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Initial Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Car struct {
    name   string
    engine string
    model  string
}

type Product struct {
    Car
    Name     string
    quantity int
    price    float32
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Store&lt;/strong&gt;: Represents a store that sells product, including cars. Has a list of products in stock and a list of sold products.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package store

import (
    "Auto-shop/products"
    "fmt"
)

type Store struct {
    name         string
    productStore []products.Product
    soldProducts []products.Product
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is undeniable that Go is not an object-oriented programming language. Can we, however, use go language features to adhere to the principles of object-oriented methodologies? Yes.&lt;/p&gt;

&lt;p&gt;However, the key idea behind object-orientation is to separate the code into several manageable parts or objects. Each object has its own identity that is determined by the data (attributes) and the methods (behavior) that operate on the data. The attributes are typically hidden and can only be accessed through the methods defined within the object. This is called &lt;strong&gt;encapsulation&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This led us to construct a receiver function(methods) for our classes.&lt;/p&gt;

&lt;p&gt;Product class methods:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
func (p *Product) Display() string {
    return p.Name
}

func (p *Product) Quantity() int {
    return p.quantity
}

func (p *Product) Status() bool {
    if p.quantity &amp;lt;= 0 {
        fmt.Println("Product Out of Stock")
        return false
    }
    fmt.Printf("Quantity of Prduct in Stock: %v", p.quantity)
    return true
}

func (p *Product) Sell(quantity int) error {
    if p.quantity &amp;lt; quantity {
        return errors.New("not enough products to sell")
    }

    p.quantity = p.quantity - quantity

    return nil
}

func (p *Product) Price() int {
    return p.price
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Store class methods:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (s *Store) AddProduct(p products.Product) {
    s.productStore = append(s.productStore, p)
}

func (s *Store) ListItemsCount() int {
    fmt.Printf("list items count: %+v \n\n", s.productStore)
    var count int
    for _, v := range s.productStore {
        count += v.Quantity()
    }
    return count
}

func (s *Store) ListItems() {
    if len(s.productStore) &amp;gt; 0 {
        for _, v := range s.productStore {
            fmt.Printf("list items: %+v \n\n", v.Display())
        }
    } else {
        fmt.Println("No products in the store atm.")
    }
}

func (s *Store) ItemsTotalPrice() int {
    fmt.Printf("items total price:%+v \n\n", s.productStore)
    var price int
    for _, v := range s.productStore {
        price += v.Quantity() * v.Price()
    }
    return price
}

func (s *Store) SellItems(productName string, quantity int) {
    var product products.Product

    for _, v := range s.productStore {
        if v.Name == productName {
            product = v
            if quantity &amp;lt;= v.Quantity() {
                product.Sell(quantity)
                s.soldProducts = append(s.soldProducts, product)
                fmt.Printf("You just sold %d amount of %s. /n The remaining %s in the store is %d", quantity, productName, productName, v.Quantity())
            } else {
                fmt.Printf("Insufficient Product in stock")
            }

        } else {
            fmt.Printf("%s is not in store", productName)
        }
    }
}

func (s *Store) ShowSoldItemsCount() {
    var sumNumberSold int
    for _, v := range s.soldProducts {
        sumNumberSold += v.Quantity()
    }
    fmt.Printf("total number of items sold: %v /n", sumNumberSold)
}

func (s *Store) ShowSoldItems() {
    fmt.Printf("sold items: %+v \n\n", s.soldProducts)
}

func (s *Store) ShowSoldItemsPrice() {
    var sumAmountSold int
    for _, v := range s.soldProducts {
        sumAmountSold += v.Price() * v.Quantity()
    }
    fmt.Printf("total sold items price: %v \n\n", sumAmountSold)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Final Implementation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Thus, after delving deeper into the vast world of GoLang and attempting to comprehend more advanced concepts. I discovered that I had already broken the encapsulation rule in previous projects, which prompted me to completely refactor my code.&lt;/p&gt;

&lt;p&gt;Unlike Java or C++, where we have private or public to restrict the accessibility of attributes, Go has no such features. Instead, what it provides is a means for package-level accessibility i.e attributes starting with uppercase can be accessed directly outside the package when the object is created. Note how all my previous attributes started with Uppercase which is wrong and a rookie mistake!.&lt;/p&gt;

&lt;p&gt;This helped me understand one of the true applications of interfaces. Interfaces also introduces a new concept in Go known as &lt;em&gt;polymorphism&lt;/em&gt;. It provides the ability to write code through the implementation of types that can take on different behavior at runtime. In Go, polymorphism is achieved through interfaces and interfaces only.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var _ Product = &amp;amp;product{}

type Product interface {
    Quantity() int
    Price() float32
    Name() string

    Sell(quantity int) error
    Display()
    Status() bool
}

type car struct {
    name  string
    color string
}

type product struct {
    car
    productName string
    quantity    int
    price       float32
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above provides us with some sense of encapsulation, granting limited access to the attributes through interface. I also implemented this same concept on the store class while using product interface from the product package.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package store

import (
    "backendexam-project/product"
    "errors"
    "fmt"
)


type Store interface {
    AddItem(item product.Product)
}

type store struct {
    name      string
    Products  []product.Product //list of products
    SoldItems []product.Product
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Overall, the implementation of the Car, Product, and Store classes in Go using object-oriented programming principles allows us to manage the inventory and sales of a car and other product store efficiently. The initial implementation had some encapsulation and abstraction concerns with all of the data/attributes that were exposed. These issues were resolved by implementing interfaces efficiently.&lt;/p&gt;

&lt;p&gt;GitHub Url: &lt;a href="https://github.com/manlikeNacho/Auto-shop.git" rel="noopener noreferrer"&gt;https://github.com/manlikeNacho/Auto-shop.git&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In conclusion, the process of modifying the code to enhance its design after completing the second-semester exam question at AltSchool Africa has allowed us to better grasp OOP in Go and put best practices for creating scalable and maintainable systems into practice. Through this technical essay, we want to share what we've learned while also serving as a helpful resource for anyone else working through a similar issue.&lt;/p&gt;

&lt;p&gt;Resources&lt;br&gt;
The resources below might be helpful&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://github.com/luciotato/golang-notes/blob/master/OOP.md" rel="noopener noreferrer"&gt;https://github.com/luciotato/golang-notes/blob/master/OOP.md&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.developer.com/languages/oop-go/" rel="noopener noreferrer"&gt;https://www.developer.com/languages/oop-go/&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>watercooler</category>
    </item>
    <item>
      <title>The Omega</title>
      <dc:creator>Iheanacho Ebere</dc:creator>
      <pubDate>Mon, 09 Jan 2023 18:48:54 +0000</pubDate>
      <link>https://dev.to/nachothegre8t/the-omega-4f29</link>
      <guid>https://dev.to/nachothegre8t/the-omega-4f29</guid>
      <description>&lt;p&gt;My first post on Dev.to&lt;/p&gt;

</description>
      <category>productivity</category>
      <category>cleancode</category>
      <category>learning</category>
    </item>
  </channel>
</rss>
