<?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"><channel><title><![CDATA[Pococare]]></title><description><![CDATA[Pococare]]></description><link>https://tech.pococare.com</link><generator>RSS for Node</generator><lastBuildDate>Thu, 17 Sep 2026 00:07:08 GMT</lastBuildDate><atom:link href="https://tech.pococare.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Test your react component using Playwright]]></title><description><![CDATA[Testing is an integral part of the software development process. When it comes to web development, testing React components is crucial to ensure that your application functions as expected. Playwright is a powerful tool that can help you automate bro...]]></description><link>https://tech.pococare.com/test-your-react-component-using-playwright</link><guid isPermaLink="true">https://tech.pococare.com/test-your-react-component-using-playwright</guid><category><![CDATA[qa testing]]></category><category><![CDATA[react testing]]></category><category><![CDATA[playwright]]></category><category><![CDATA[React]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Atul]]></dc:creator><pubDate>Sun, 24 Sep 2023 19:24:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695581632559/33074d4f-2cf3-4808-9a89-2a1411cb983e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Testing is an integral part of the software development process. When it comes to web development, testing React components is crucial to ensure that your application functions as expected. Playwright is a powerful tool that can help you automate browser interactions and effectively test your React components. In this article, we'll explore React component testing using Playwright, providing you with a comprehensive guide to get started.</p>
<h2 id="heading-what-is-a-playwright"><strong>What is a Playwright?</strong></h2>
<p>Playwright is an open-source automation framework that enables developers to test web applications across different browsers, including Chromium, Firefox, and WebKit. Developed by Microsoft, Playwright offers a unified API for automating browser actions, making it an excellent choice for end-to-end testing and browser automation.</p>
<h2 id="heading-why-use-playwright-for-react-component-testing"><strong>Why Use Playwright for React Component Testing?</strong></h2>
<p>Playwright is an excellent choice for React component testing for several reasons:</p>
<ol>
<li><p><strong>Cross-Browser Testing</strong>: Playwright allows you to test your React components in multiple browsers, including Chromium, Firefox, and WebKit. This ensures that your components work consistently across different browsers, which is crucial for delivering a great user experience.</p>
</li>
<li><p><strong>Real User Interactions</strong>: Playwright can simulate real user interactions, such as clicking, typing, and navigating. This helps you test your React components in a way that closely resembles how users interact with your application.</p>
</li>
<li><p><strong>Headless and Headful Mode</strong>: Playwright supports both headless and headful modes, making it versatile for different testing scenarios. You can run tests headlessly for continuous integration (CI) pipelines or run them in headful mode to visually inspect the test execution.</p>
</li>
<li><p><strong>Accessibility Testing</strong>: Playwright includes built-in accessibility testing tools, allowing you to ensure that your React components are accessible to all users, including those with disabilities.</p>
</li>
</ol>
<h2 id="heading-set-up-react-app"><strong>Set Up React App</strong></h2>
<p>Step 1 - Create a react app using the given command.</p>
<pre><code class="lang-bash">npx create-react-app react-app
</code></pre>
<p>After running the above command output looks like</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695578205500/4d5fce16-e0e0-41b0-a3dd-9baa8414f2ce.png" alt class="image--center mx-auto" /></p>
<p>Step 2 - Go to the root directory and launch the React app.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> react-app
npm start
</code></pre>
<p>After running the npm start command your react app will be started on <em>http://localhost:3000</em></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695578872389/26be8712-b0a3-48f6-a3c1-f30197b29799.png" alt class="image--center mx-auto" /></p>
<p>Take a look at your Visual Studio Code - the project has been successfully created. Now, let's see what it looks like, shown below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695578992544/17cef274-12a9-4f9d-b311-36ff3d0fd7b2.png" alt class="image--center mx-auto" /></p>
<p>Notice that the application is up and running.</p>
<h2 id="heading-set-up-playwright">Set up Playwright</h2>
<p>Step 1 - Run the below command to initiate Playwright in react-app that you have created.</p>
<pre><code class="lang-bash">npm init playwright@latest -- --ct
</code></pre>
<p>After running the given command output will look like</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695580271420/37838f4f-d437-49bb-a491-403c62fc4bb6.png" alt class="image--center mx-auto" /></p>
<p>Select<strong>Javascript</strong> by pressing the down arrow button + enter.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695580414003/7af63a4f-8222-4953-b47e-a50a26891f56.png" alt /></p>
<p>Select <strong>React 18</strong></p>
<p>Now, Playwright is initiated in your project you can see screenshoot.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695580594548/1f9690d4-b939-478a-b3be-dfe30d05162a.png" alt class="image--center mx-auto" /></p>
<p>Now you can see, that Playwright is installed in your project.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695580790159/a555e63b-b43d-4de0-8ab4-f973deb6f3cd.png" alt /></p>
<h2 id="heading-test-your-react-component">Test your react component.</h2>
<p>Now Let’s take an example to test <strong>Counter</strong> Component using Playwright.</p>
<p><strong>Step 1</strong> - update the name of the existing file <strong>src/App.test.js -&gt; App.spec.js</strong></p>
<p><strong>Step 2</strong> - Create a Counter component.</p>
<p>Let's give the name of the js file as ‘Counter.js’ and the spec name ‘Counter.spec.js’</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695581923348/c5d4666e-6f01-438f-9565-3465e9b47534.png" alt /></p>
<p><strong>Step 3</strong> - Paste the following code to <code>Counter.js</code> file</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params">{ initial = <span class="hljs-number">0</span> }</span>) </span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(initial)

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> "<span class="hljs-attr">black</span>", <span class="hljs-attr">backgroundColor:</span> "<span class="hljs-attr">green</span>", <span class="hljs-attr">margin:</span> <span class="hljs-attr">10</span> }} <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"decrement"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count - 1)}&gt;
                -
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">data-cy</span>=<span class="hljs-string">"counter"</span>&gt;</span>{count}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> "<span class="hljs-attr">black</span>", <span class="hljs-attr">backgroundColor:</span> "<span class="hljs-attr">green</span>", <span class="hljs-attr">margin:</span> <span class="hljs-attr">10</span> }} <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"increment"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;
                +
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre>
<p><strong>Step 4</strong> - Paste the following code to <code>Counter.spec.js</code> file.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { test, expect } <span class="hljs-keyword">from</span> <span class="hljs-string">'@playwright/experimental-ct-react'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./Counter.jsx'</span>;
<span class="hljs-keyword">const</span> counterSelector = <span class="hljs-string">'[data-cy="counter"]'</span>;
<span class="hljs-keyword">const</span> incrementSelector = <span class="hljs-string">"[aria-label=increment]"</span>;
<span class="hljs-keyword">const</span> decrementSelector = <span class="hljs-string">"[aria-label=decrement]"</span>;
test.use({ <span class="hljs-attr">viewport</span>: { <span class="hljs-attr">width</span>: <span class="hljs-number">500</span>, <span class="hljs-attr">height</span>: <span class="hljs-number">500</span> } });

test(<span class="hljs-string">'Two time Increment in the Counter '</span>, <span class="hljs-keyword">async</span> ({ mount }) =&gt; {
    <span class="hljs-keyword">const</span> component = <span class="hljs-keyword">await</span> mount(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span>/&gt;</span></span>);
  <span class="hljs-keyword">await</span> component.locator(incrementSelector).click();
    <span class="hljs-keyword">await</span> expect(component.locator(counterSelector)).toHaveText(<span class="hljs-string">'1'</span>);
    <span class="hljs-keyword">await</span> component.locator(incrementSelector).click();
    <span class="hljs-keyword">await</span> expect(component.locator(counterSelector)).toHaveText(<span class="hljs-string">'2'</span>);
});

test(<span class="hljs-string">'Increment then the decrement the Counter '</span>, <span class="hljs-keyword">async</span> ({ mount }) =&gt; {
    <span class="hljs-keyword">const</span> component = <span class="hljs-keyword">await</span> mount(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span>/&gt;</span></span>);
  <span class="hljs-keyword">await</span> component.locator(incrementSelector).click();
    <span class="hljs-keyword">await</span> expect(component.locator(counterSelector)).toHaveText(<span class="hljs-string">'1'</span>);
    <span class="hljs-keyword">await</span> component.locator(decrementSelector).click();
    <span class="hljs-keyword">await</span> expect(component.locator(counterSelector)).toHaveText(<span class="hljs-string">'0'</span>);
});
</code></pre>
<p>In the above test case, we are covering two scenarios. First ‘Two time Increment in the Counter’. The second scenario is ‘Increment then the decrement the Counter’.</p>
<p><strong>Step 5</strong> - Run the test cases using the below command.</p>
<pre><code class="lang-bash">npm run test-ct
</code></pre>
<p><strong>Step 6 -</strong> See output using the below command.</p>
<pre><code class="lang-bash">npx playwright show-report
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695582680221/437770bb-ebce-4a96-b389-6c327afe3d5d.png" alt /></p>
<p>Now you can see the test report of the Counter component.</p>
<p>Find Source Code Here: <a target="_blank" href="https://github.com/theatulanand/react-playwright">https://github.com/theatulanand/react-playwright</a></p>
<p>Follow us for more articles related to software development and testing.</p>
]]></content:encoded></item><item><title><![CDATA[How to send push notifications with Firebase, React and NestJS]]></title><description><![CDATA[Firebase Cloud Messaging (FCM) is a versatile cloud-based messaging platform that empowers app developers to send messages and notifications to users' devices, delivering text, images, links, and more. In this guide, we'll explore the benefits of usi...]]></description><link>https://tech.pococare.com/how-to-send-push-notifications-with-firebase-react-and-nestjs</link><guid isPermaLink="true">https://tech.pococare.com/how-to-send-push-notifications-with-firebase-react-and-nestjs</guid><category><![CDATA[Firebase]]></category><category><![CDATA[React]]></category><category><![CDATA[nestjs]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[web push notifications]]></category><dc:creator><![CDATA[Mohima Bahadur]]></dc:creator><pubDate>Tue, 12 Sep 2023 05:12:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1694451164864/5ec3fba7-7c2b-40f1-8cfd-44564a44b746.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Firebase Cloud Messaging (FCM) is a versatile cloud-based messaging platform that empowers app developers to send messages and notifications to users' devices, delivering text, images, links, and more. In this guide, we'll explore the benefits of using FCM and walk you through setting up FCM notifications in your web applications using React.js and Nest.js.</p>
<h2 id="heading-benifits-of-using-fcm">Benifits of using FCM:-</h2>
<ul>
<li><p><strong>Cross-Platform:</strong> FCM works on Android, iOS, and web apps, simplifying multi-platform messaging.</p>
</li>
<li><p><strong>Reliability:</strong> FCM is known for its dependable message delivery, even during high-demand periods.</p>
</li>
<li><p><strong>Cost-Effective:</strong> It offers a free tier suitable for most small to medium-sized apps.</p>
</li>
<li><p><strong>Security:</strong> Ensure secure communication between servers and devices.</p>
</li>
</ul>
<p><strong>Cloud Integration:</strong> Easily integrates with other Firebase services for enhanced functionality.</p>
<h3 id="heading-create-firebase-project">Create Firebase project:</h3>
<ul>
<li><p><strong>Go to the Firebase Console:</strong> Visit the Firebase Console by going to <a target="_blank" href="https://console.firebase.google.com/">https://console.firebase.google.com/</a>.</p>
</li>
<li><p><strong>Sign In:</strong> Sign in with your Google account. If you don't have one, you'll need to create a Google account first.</p>
</li>
<li><p><strong>Add a New Project:</strong> Click on the "Add project" button to create a new Firebase project.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694452720910/4362b5f3-8e29-4472-9588-2283f01df719.png" alt /></p>
</li>
<li><p><strong>Enter Project Name:</strong> Give your project a name. This name should be unique within Firebase, so choose something descriptive.</p>
</li>
<li><p><strong>(Optional) Set Up Google Analytics:</strong> You can choose to enable Google Analytics for your project. This will help you gather data about your app's usage. You can also enable this later if needed.</p>
</li>
<li><p><strong>Click "Create Project":</strong> Once you've filled in the necessary information, click the "Create Project" button.</p>
</li>
<li><p><strong>Wait for Project Creation:</strong> Firebase will set up your project, which may take a moment.</p>
</li>
</ul>
<p><strong>Project Created:</strong> Once the project is created, you'll be taken to the project dashboard, where you can see the below image.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694453243489/1152b72f-38af-4ad7-90e5-6c028bf09803.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-how-to-set-up-your-firebase-project">How to set up your Firebase project?</h3>
<p>Here's a step-by-step guide.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694454826794/db412de5-dbcd-4d05-a409-1c59ca3a8b54.png" alt class="image--center mx-auto" /></p>
<ol>
<li>Click on web notification button.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694455287296/343637f3-0a58-40ac-8e08-88435477a129.png" alt class="image--center mx-auto" /></p>
<p>Click on '<strong>Register app</strong>' button.</p>
<h3 id="heading-now-set-up-your-firebase-to-your-react-app">Now set up your firebase to your react-app</h3>
<ol>
<li><p>Create your react app.</p>
</li>
<li><p>Install Firebase in your React app</p>
</li>
<li><p>Create a firebase.js file inside your src folder.</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> firebaseConfig = <span class="hljs-keyword">const</span> firebaseConfig = {
   <span class="hljs-attr">apiKey</span>: <span class="hljs-string">"YOUR_API_KEY"</span>,
   <span class="hljs-attr">authDomain</span>: <span class="hljs-string">"YOUR_AUTH_DOMAIN"</span>,
   <span class="hljs-attr">projectId</span>: <span class="hljs-string">"YOUR_PROJECT_ID"</span>,
   <span class="hljs-attr">storageBucket</span>: <span class="hljs-string">"YOUR_STORAGE_BUCKET"</span>,
   <span class="hljs-attr">messagingSenderId</span>: <span class="hljs-string">"YOUR_MESSAGING_SENDER_ID"</span>,
   <span class="hljs-attr">appId</span>: <span class="hljs-string">"YOUR_APP_ID"</span>
 };  
   <span class="hljs-comment">// Initialize Firebase</span>
   <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> app = initializeApp(firebaseConfig);
   <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> messaging = getMessaging(app);
</code></pre>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694455978914/f1383b8e-d952-40de-9468-74161da9badc.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<p>Replace <code>firebaseConfig</code> with your firebase project <code>firebaseConfig</code> object.</p>
<ul>
<li><p>open app.jsx.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">import</span> { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
  <span class="hljs-keyword">import</span> { messaging } <span class="hljs-keyword">from</span> <span class="hljs-string">"./firebase"</span>;
  <span class="hljs-keyword">import</span> { getToken } <span class="hljs-keyword">from</span> <span class="hljs-string">"firebase/messaging"</span>;

  <span class="hljs-keyword">import</span> <span class="hljs-string">"./App.css"</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">requestPermission</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">const</span> permission = <span class="hljs-keyword">await</span> Notification.requestPermission();
      <span class="hljs-keyword">if</span> (permission === <span class="hljs-string">"granted"</span>) {
        <span class="hljs-comment">// Generate Token</span>
        <span class="hljs-keyword">const</span> token = <span class="hljs-keyword">await</span> getToken(messaging, {
          <span class="hljs-attr">vapidKey</span>: Your_Vapid_key
            <span class="hljs-comment">// replace with your vapid key,</span>
        });
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Token Gen"</span>, token);
        <span class="hljs-comment">// Send this token  to server ( db)</span>
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (permission === <span class="hljs-string">"denied"</span>) {
        alert(<span class="hljs-string">"You denied for the notification"</span>);
      }
    }

    useEffect(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-comment">// Req user for notification permission</span>
      requestPermission();
    }, []);

    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Push notification service<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }

  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>  For the code snippet above, you'll need to generate your project's Vapid key. Here are the steps.</p>
<ul>
<li><p>Go to <code>Project settings</code></p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694457189521/51a78688-b59d-48f1-8859-926ff28317ed.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
</li>
<li><p>Click on <code>cloud messaging</code> option.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694457291101/e94e5d1a-95d4-42d7-852e-61f9349a73f1.png" alt class="image--right mx-auto mr-0" /></p>
</li>
<li><p>Scroll down and click on <code>Generate key pair</code>button. This action will generate a string, which will serve as your Vapid key.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694457524208/f12c9130-a0aa-43ef-9554-355d9d36f4a6.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<ol>
<li>Now, run your React app using the <code>npm run star</code> command. Open your console, and you will be able to see that your token has been successfully generated.</li>
</ol>
<p>Create a file firebase-messaging-sw.js in the public folder.</p>
<pre><code class="lang-javascript">
importScripts(<span class="hljs-string">"https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"</span>);
importScripts(
  <span class="hljs-string">"https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"</span>
);
<span class="hljs-keyword">const</span> firebaseConfig = {
  <span class="hljs-attr">apiKey</span>: <span class="hljs-string">"YOUR_API_KEY"</span>,
  <span class="hljs-attr">authDomain</span>: <span class="hljs-string">"YOUR_AUTH_DOMAIN"</span>,
  <span class="hljs-attr">projectId</span>: <span class="hljs-string">"YOUR_PROJECT_ID"</span>,
  <span class="hljs-attr">storageBucket</span>: <span class="hljs-string">"YOUR_STORAGE_BUCKET"</span>,
  <span class="hljs-attr">messagingSenderId</span>: <span class="hljs-string">"YOUR_MESSAGING_SENDER_ID"</span>,
  <span class="hljs-attr">appId</span>: <span class="hljs-string">"YOUR_APP_ID"</span>
};

<span class="hljs-keyword">const</span> app = firebase.initializeApp(firebaseConfig);
<span class="hljs-keyword">const</span> messaging = firebase.messaging();

messaging.onBackgroundMessage(<span class="hljs-function">(<span class="hljs-params">payload</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">"[firebase-messaging-sw.js] Received background message "</span>,
    payload
  );
  <span class="hljs-keyword">const</span> notificationTitle = payload.notification.title;
  <span class="hljs-keyword">const</span> notificationOptions = {
    <span class="hljs-attr">body</span>: payload.notification.body,
    <span class="hljs-attr">icon</span>: payload.notification.image,
  };
  self.registration.showNotification(notificationTitle, notificationOptions);
});
</code></pre>
<p>Here's a simplified explanation of the code:</p>
<ul>
<li><p>We include two Firebase JavaScript libraries: 'firebase-app.js' and 'firebase-messaging.js.'</p>
</li>
<li><p>We configure Firebase with the 'firebaseConfig' object, which contains various settings for our app.</p>
</li>
<li><p>We initialize the Firebase app and messaging service.</p>
</li>
<li><p>We set up a listener for background messages, which allows our app to receive messages even when it's not in the foreground.</p>
</li>
<li><p>When a background message is received, we log it to the console and extract the notification title, body, and icon.</p>
</li>
<li><p>Finally, we display the notification using the extracted title, body, and icon.</p>
</li>
</ul>
<p>This code is essential for enabling push notifications in your web app with Firebase.</p>
<h3 id="heading-now-set-up-your-firebase-with-nestjs">Now set up your firebase with NestJS:-</h3>
<ol>
<li><p>Create nestJS project and install firebase-admin package.</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">//run this command </span>
 nest g resource fcm-notification <span class="hljs-comment">//for creat fcm-notificatiob module</span>
 npm install firebase-admin <span class="hljs-comment">// for install firebase-admin to your project</span>
</code></pre>
</li>
<li><p>Now go to <code>fcm-notification.Service.ts</code></p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> admin <span class="hljs-keyword">from</span> <span class="hljs-string">'firebase-admin'</span>;

 admin.initializeApp({
   <span class="hljs-attr">credential</span>: admin.credential.cert({
     <span class="hljs-attr">projectId</span>: PROJECT-ID,  <span class="hljs-comment">// replace with your app project-ID</span>
     <span class="hljs-attr">clientEmail</span>: CLIENT-KEY, <span class="hljs-comment">//replace with your app CLIENT-KEY</span>
     <span class="hljs-attr">privateKey</span>: PRIVATE-KEy <span class="hljs-comment">//replace with your app PRIVATE-KEy</span>
   }),
 });
 @Injectable()
 <span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FcmNotificationService</span> </span>{
   <span class="hljs-keyword">constructor</span>() {
   }
 }
</code></pre>
<p> Above code, we are importing <code>admin</code> is imported as a namespace from 'firebase-admin. Next <code>admin.initializeApp({ ... })</code> initializes the Firebase Admin SDK with the provided configuration.<br /> To access your Admin SDK configuration details, navigate to your project settings and select 'Service accounts.' From there, you can <code>generate a new private key</code> in the form of a downloadable JSON file, which will serve as your admin SDK configuration. For reference, please consult the image below.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694458885707/f5681c0b-5d7e-4147-999e-daa86c232c1f.png" alt class="image--center mx-auto" /></p>
<p> Now add sending notification function to your service folder.</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> admin <span class="hljs-keyword">from</span> <span class="hljs-string">'firebase-admin'</span>;

 admin.initializeApp({
   <span class="hljs-attr">credential</span>: admin.credential.cert({
     <span class="hljs-attr">projectId</span>: PROJECT-ID,  
     <span class="hljs-attr">clientEmail</span>: CLIENT-KEY,
     <span class="hljs-attr">privateKey</span>: PRIVATE-KEy
   }),
 });
 @Injectable()
 <span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FcmNotificationService</span> </span>{
   <span class="hljs-keyword">constructor</span>() {
   }

   <span class="hljs-keyword">async</span> sendingNotificationOneUser(token:string) {
     <span class="hljs-keyword">const</span> payload= {
       <span class="hljs-attr">token</span>: token
       <span class="hljs-attr">notification</span>: {
         <span class="hljs-attr">title</span>: <span class="hljs-string">"Hi there this is title"</span>,
         <span class="hljs-attr">body</span>: <span class="hljs-string">"Hi there this is message"</span>
       },
       <span class="hljs-attr">data</span>: {
         <span class="hljs-attr">name</span>:<span class="hljs-string">"Joe"</span>,
         <span class="hljs-attr">age</span>:<span class="hljs-string">"21"</span>
       }
       }
     <span class="hljs-keyword">return</span> admin.messaging().send(payload).then(<span class="hljs-function">(<span class="hljs-params">res</span>)=&gt;</span>{
       <span class="hljs-keyword">return</span> {
           <span class="hljs-attr">success</span>:<span class="hljs-literal">true</span>
       }

     }).catch(<span class="hljs-function">(<span class="hljs-params">error</span>)=&gt;</span>{
       <span class="hljs-keyword">return</span> {
         <span class="hljs-attr">success</span>:<span class="hljs-literal">false</span>
       }
     })
   }
 }
</code></pre>
<p> The <code>sendingNotificationOneUser</code> function sends a notification to a specific user. It uses the user's device token to target them, constructs the notification content (title, body, and additional data), and sends it through Firebase. If successful, it returns <code>success: true</code>; otherwise, it returns <code>success: false</code>.</p>
</li>
<li><p>Now go to Fcm-Notification.controller.ts.</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { Controller, Get, Post, Body, Patch, Param, Delete } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
 <span class="hljs-keyword">import</span> { FcmNotificationService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./fcm-notification.service'</span>;

 @Controller(<span class="hljs-string">'firebase'</span>)
 <span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FcmNotificationController</span> </span>{
   <span class="hljs-keyword">constructor</span>(
     private readonly sendingNotificationService: FcmNotificationService,
    ) {}

   @Post(<span class="hljs-string">'send-notification/'</span>)
   <span class="hljs-keyword">async</span> sendNotidication(@Body() body:{ <span class="hljs-attr">token</span>: string }) {
   <span class="hljs-keyword">const</span> {token}=body
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.sendingNotificationService.sendingNotificationOneUser()
   }
 }
</code></pre>
<p> In the code snippet provided, a route for sending notifications is defined in a NestJS controller. When a POST request is made to '/firebase/send-notification/', the function <code>sendNotidication</code> is called. It expects a JSON body with a 'token' field, which is passed to the <code>sendingNotificationOneUser</code> function from the <code>FcmNotificationService</code>. The result of the notification sending process is returned in the response.</p>
</li>
</ol>
<h3 id="heading-making-a-request-with-postman">Making a Request with Postman:-</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694459993537/70598746-ee66-47e6-954a-2cc605838b48.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694460090064/3f2baf72-46f7-470f-8b10-f34a69567df7.png" alt class="image--center mx-auto" /></p>
<p>That's all for now. I hope you find this tutorial helpful! Feel free to leave feedback or questions below, I would love to hear and work on them. Thank you :)</p>
]]></content:encoded></item><item><title><![CDATA[Automate API Testing with Postman]]></title><description><![CDATA[Automated API testing with Postman is a valuable practice that helps developers and testers ensure the quality and functionality of their APIs. Postman is a user-friendly and powerful tool designed to simplify API testing and streamline the testing p...]]></description><link>https://tech.pococare.com/automate-api-testing-with-postman</link><guid isPermaLink="true">https://tech.pococare.com/automate-api-testing-with-postman</guid><category><![CDATA[API TESTING]]></category><category><![CDATA[Postman]]></category><dc:creator><![CDATA[Atul]]></dc:creator><pubDate>Mon, 11 Sep 2023 05:05:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/FPK6K5OUFVA/upload/b4f21e1312fb2757d5007f17bfab2dd4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Automated API testing with Postman is a valuable practice that helps developers and testers ensure the quality and functionality of their APIs. Postman is a user-friendly and powerful tool designed to simplify API testing and streamline the testing process. This document will provide an overview of how to conduct automated API testing using Postman.</p>
<h2 id="heading-benefits-of-automated-api-testing-with-postman"><strong>Benefits of Automated API Testing with Postman:</strong></h2>
<ol>
<li><p><strong>Time Efficiency:</strong> Automating API testing with Postman saves time by running tests automatically, freeing up resources to focus on other critical tasks.</p>
</li>
<li><p><strong>Consistency:</strong> Automated testing ensures that API tests are performed consistently without manual errors, improving reliability and repeatability.</p>
</li>
<li><p><strong>Faster Feedback:</strong> Rapid execution of test scripts allows for quick feedback on API changes, enabling developers to fix issues promptly.</p>
</li>
<li><p><strong>Scalability:</strong> Postman supports testing multiple APIs simultaneously, making it suitable for projects of various sizes.</p>
</li>
<li><p><strong>Integration with CI/CD:</strong> Automated API testing can be integrated into Continuous Integration and Continuous Deployment (CI/CD) pipelines, ensuring thorough testing at every code change.</p>
</li>
</ol>
<p>If you're familiar with Postman basics, like sending requests and using collections, now let's dive into creating tests in Postman.</p>
<h1 id="heading-writing-test-cases-in-postman">Writing test cases in Postman</h1>
<p>Before writing test cases in Postman, ensure you have the following:</p>
<ol>
<li><p>Postman is installed on your system.</p>
</li>
<li><p>A basic understanding of APIs and HTTP methods.</p>
</li>
<li><p>Familiarity with JSON (JavaScript Object Notation) for response validation.</p>
</li>
</ol>
<h2 id="heading-where-to-write-test-cases"><strong>Where to write test cases.</strong></h2>
<p>In Postman, you can write and organize your test cases using the "Tests" tab within the Postman request editor. Here's how you can write test cases in Postman:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693851849518/5d4cb8ed-1264-40f2-abf3-d3724c44ca73.png?auto=compress,format&amp;format=webp" alt /></p>
<ul>
<li><p><strong>Create a Request:</strong> First, create a request by selecting the request type (GET, POST, PUT, DELETE, etc.) and entering the request URL along with any necessary headers, parameters, and request body.</p>
</li>
<li><p><strong>Navigate to the Tests Tab:</strong> After setting up the request details, click on the "Tests" tab located below the request editor. This is where you'll write your test scripts.</p>
</li>
<li><p><strong>Write Test Scripts:</strong> In the "Tests" tab, you can write JavaScript code to define your test scripts. These scripts will be executed after sending the request, and you can use them to validate the response received from the server.</p>
</li>
</ul>
<p>Here's a simple example of a test script that checks if the response status code is 201:</p>
<p><strong>COPY</strong></p>
<pre><code class="lang-plaintext">pm.test("Response status code is 201", function () {
    pm.expect(pm.response.code).to.equal(201);
});
</code></pre>
<p>You can add more test scripts to validate various aspects of the response, such as response headers, response body, specific data values, etc.</p>
<ul>
<li><p><strong>Run the Request:</strong> After writing your test scripts, you can click the "Send" button to send the request to the server. Postman will execute your test scripts and display the results in the "Tests Results" section below the request editor.</p>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693851935540/e1a22606-9e78-4f77-8cd7-38cbb33d5924.png?auto=compress,format&amp;format=webp" alt /></p>
</li>
<li><p><strong>View Test Results:</strong> The test results will show you whether your test scripts passed or failed. If a test fails, Postman will provide information about the failure, which can help you identify the issues in your API.</p>
</li>
<li><p><strong>Organize Test Scripts:</strong> You can organize your test scripts by creating multiple requests within a Postman collection. Each request can have its own set of test scripts. Collections allow you to group related requests and tests together, making it easier to manage and run your test suite.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693851998293/62bca48a-5ef5-4193-b9a9-04ba2b244858.png?auto=compress,format&amp;format=webp" alt /></p>
<p>Remember that the examples provided here are basic illustrations. You can write more complex test scripts using various assertions and conditions based on your API testing needs.</p>
<p>Additionally, Postman offers documentation and tutorials to help you learn more about writing test scripts and performing API testing effectively.</p>
<blockquote>
<p><strong><em>Refer this article for common test scripts in postman 👉</em></strong> <a target="_blank" href="https://tech.pococare.com/some-common-test-scripts-in-postman"><strong><em>Click Me</em></strong></a></p>
</blockquote>
<h1 id="heading-integrate-postman-automated-testing-with-cicd">Integrate Postman automated testing with CI/CD</h1>
<p>Now We’ll learn about How to integrate Postman automated testing with CI/CD of GitHub using Newman in the Nest JS Project.</p>
<p>Integrating Postman automated testing with CI/CD using Newman involves setting up a process that allows you to run Postman collections and tests automatically as part of your Continuous Integration and Continuous Deployment (CI/CD) pipeline. Newman is a command-line tool provided by Postman that allows you to run Postman collections from the command line, making it suitable for automation in CI/CD environments.</p>
<p>I’m assuming that you have already created a collection with test cases.</p>
<p>Here's a step-by-step guide on how to integrate Postman automated testing with CI/CD using Newman.</p>
<h3 id="heading-generate-postman-collection-api-url">Generate Postman Collection API URL.</h3>
<p>For generating Postman collection API Url, Follow the given steps:</p>
<ol>
<li><p>Click on the “View More Actions“ button of the collection.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693853478196/17d80046-3320-4444-a729-e5270e53b602.png?auto=compress,format&amp;format=webp" alt /></p>
</li>
<li><p>Click on the “Share“ Option</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693853584714/7e159cc6-045a-4095-9484-7e644aff7862.png?auto=compress,format&amp;format=webp" alt /></p>
<ol>
<li>Choose the “Via API” option.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693853662085/8c7b6e81-b0bd-4fcf-80e9-62a1de43b9ef.png?auto=compress,format&amp;format=webp" alt /></p>
<ol>
<li>Copy the Postman API URL using copy button.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693853692344/f71fb7ff-9cf9-49f3-b9e6-cc70934529a1.png?auto=compress,format&amp;format=webp" alt /></p>
<p>Your Collection API Generated Successfully.</p>
<h3 id="heading-configure-your-cicd-pipeline">Configure Your CI/CD Pipeline:</h3>
<ul>
<li><p>You'll need to set up a job or stage that will run your Postman tests using Newman.</p>
</li>
<li><p>In the pipeline configuration, you'll need to specify the commands to install Newman, run your tests, and possibly report the results.</p>
</li>
</ul>
<p>To configure your CI/CD pipeline, Follow the given steps:</p>
<ol>
<li>Create a <strong>.github</strong> folder in the root of the project.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693853738995/8f89ffa5-b018-42c3-a59f-45dd2ab1cc9f.png?auto=compress,format&amp;format=webp" alt /></p>
<ol>
<li><p>Create the <strong>workflows</strong> folder inside the <strong>.github</strong> folder.</p>
</li>
<li><p>Create <strong>yourFileName.yml</strong> file inside the workflows folder.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693853784120/0f19f41b-4da9-4e01-baca-53b29de6e2c4.png?auto=compress,format&amp;format=webp" alt /></p>
<ol>
<li><p>Now, write a shell script to run your Postman tests as part of the build or test phase.</p>
<p> <strong>COPY</strong></p>
<pre><code class="lang-plaintext">  name: Test Nest.js Application

  on:
    push:
      branches:
        - create-company // Replace with your branch name

  jobs:
    run-and-test:
      runs-on: ubuntu-latest
      steps:
        - uses: actions/checkout@v2
        - name: Install Node.js
          uses: actions/setup-node@v2
          with:
            node-version: '18'
        - name: Install Nest.js CLI
          run: npm install -g @nestjs/cli
        - name: Install Dependencies
          run: npm install
        - name: Run Nest.js Application on Localhost
          run: npm run start:dev &amp; sleep 10
        - name: Run API Tests with Newman
          run: |
            npm install -g newman
            newman run "Paste Generated Collection API Url"
</code></pre>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Some common test scripts in Postman]]></title><description><![CDATA[In this article, we will look at some usual test scripts that people often use when they write test cases.
In Postman, test scripts are written using JavaScript in the "Tests" tab after sending an API request. Each test script is associated with a sp...]]></description><link>https://tech.pococare.com/some-common-test-scripts-in-postman</link><guid isPermaLink="true">https://tech.pococare.com/some-common-test-scripts-in-postman</guid><category><![CDATA[Testing]]></category><category><![CDATA[Postman]]></category><category><![CDATA[API TESTING]]></category><dc:creator><![CDATA[Atul]]></dc:creator><pubDate>Mon, 11 Sep 2023 05:01:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/FPK6K5OUFVA/upload/049b1e4bc5af17997e13cfed10fd2ac4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we will look at some usual test scripts that people often use when they write test cases.</p>
<p>In Postman, test scripts are written using JavaScript in the "Tests" tab after sending an API request. Each test script is associated with a specific API request and is executed automatically after the request is sent. The test script has access to the response data, request details, and various utility functions provided by Postman.</p>
<p>A basic test script structure looks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test script</span>
pm.test(<span class="hljs-string">"Test Description"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Assertion logic goes here</span>
});
</code></pre>
<h2 id="heading-common-test-scripts"><strong>Common Test Scripts</strong></h2>
<h3 id="heading-1-status-code-validation">1. Status Code Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test if the response status code is 200 (OK)</span>
pm.test(<span class="hljs-string">"Status code is 200"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    pm.response.to.have.status(<span class="hljs-number">200</span>);
});
</code></pre>
<h3 id="heading-2-response-time-validation">2. Response Time Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test if the response time is less than 500ms</span>
pm.test(<span class="hljs-string">"Response time is within acceptable range"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    pm.expect(pm.response.responseTime).to.be.below(<span class="hljs-number">500</span>);
});
</code></pre>
<h3 id="heading-3-response-body-validation">3. Response Body Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test if the response body contains a specific value</span>
pm.test(<span class="hljs-string">"Response body contains expected data"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    pm.expect(pm.response.text()).to.include(<span class="hljs-string">"expected_value"</span>);
});
</code></pre>
<h3 id="heading-4-json-response-validation">4. JSON Response Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test if the response is a valid JSON</span>
pm.test(<span class="hljs-string">"Response is valid JSON"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    pm.expect(pm.response.json()).to.be.an(<span class="hljs-string">"object"</span>);
});
</code></pre>
<h3 id="heading-5-header-validation">5. Header Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test if a specific header is present in the response</span>
pm.test(<span class="hljs-string">"Header is present in the response"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    pm.response.to.have.header(<span class="hljs-string">"header_name"</span>);
});
</code></pre>
<h3 id="heading-6-chaining-tests">6. Chaining Tests</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Chaining multiple test assertions</span>
pm.test(<span class="hljs-string">"Chaining multiple assertions"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    pm.expect(pm.response.json().property1).to.eql(<span class="hljs-string">"value1"</span>);
    pm.expect(pm.response.json().property2).to.eql(<span class="hljs-string">"value2"</span>);
});
</code></pre>
<h3 id="heading-7-dynamic-data-validation">7. Dynamic Data Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test if a specific value in the response matches the environment variable</span>
pm.test(<span class="hljs-string">"Dynamic data validation"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    pm.expect(pm.response.json().user_id).to.eql(pm.environment.get(<span class="hljs-string">"user_id"</span>));
});
</code></pre>
<h3 id="heading-8-setting-data-from-the-environment-variable">8. Setting data from the environment variable</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> jsonData = pm.response.json();
pm.environment.set(<span class="hljs-string">"companyIdToDelete"</span>, jsonData.data._id);
</code></pre>
<h3 id="heading-9-response-schema-validation">9. Response Schema Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test if the response adheres to a specific JSON schema</span>
pm.test(<span class="hljs-string">"Response schema validation"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> schema = {
        <span class="hljs-string">"type"</span>: <span class="hljs-string">"object"</span>,
        <span class="hljs-string">"properties"</span>: {
            <span class="hljs-string">"property1"</span>: { <span class="hljs-string">"type"</span>: <span class="hljs-string">"string"</span> },
            <span class="hljs-string">"property2"</span>: { <span class="hljs-string">"type"</span>: <span class="hljs-string">"number"</span> }
        }
    };
    pm.expect(tv4.validate(pm.response.json(), schema)).to.be.true;
});
</code></pre>
<h3 id="heading-10-dynamic-response-validation">10. Dynamic Response Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Validate dynamic data in the response by extracting values from the response and using them in assertions.</span>
<span class="hljs-comment">// Extract a value from the response and use it in an assertion</span>
pm.test(<span class="hljs-string">"Dynamic response validation"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> responseBody = pm.response.json();
    <span class="hljs-keyword">var</span> dynamicValue = responseBody.dynamic_property;

    pm.expect(dynamicValue).to.equal(pm.variables.get(<span class="hljs-string">"expected_dynamic_value"</span>));
});
</code></pre>
<h3 id="heading-11-api-versioning-validation">11. API Versioning Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test different API versions</span>
<span class="hljs-keyword">var</span> apiVersion = <span class="hljs-string">"v2"</span>;
pm.test(<span class="hljs-string">"API versioning validation"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    pm.request.headers.add({ <span class="hljs-attr">key</span>: <span class="hljs-string">"Accept-Version"</span>, <span class="hljs-attr">value</span>: apiVersion });
    pm.sendRequest(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) </span>{
        pm.expect(response.status).to.equal(<span class="hljs-number">200</span>);
        pm.expect(response.json().version).to.equal(apiVersion);
    });
});
</code></pre>
<h3 id="heading-12-file-upload-validation">12. File Upload Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test file upload</span>
pm.test(<span class="hljs-string">"File upload validation"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> formData = {
        <span class="hljs-attr">file</span>: {
            <span class="hljs-attr">value</span>: pm.globals.get(<span class="hljs-string">"fileData"</span>),
            <span class="hljs-attr">options</span>: {
                <span class="hljs-attr">filename</span>: <span class="hljs-string">"sample.txt"</span>,
                <span class="hljs-attr">contentType</span>: <span class="hljs-string">"text/plain"</span>
            }
        }
    };

    pm.sendRequest({
        <span class="hljs-attr">url</span>: <span class="hljs-string">"https://api.example.com/upload"</span>,
        <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
        <span class="hljs-attr">body</span>: formData
    }, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) </span>{
        pm.expect(response.status).to.equal(<span class="hljs-number">200</span>);
        pm.expect(response.json().success).to.be.true;
    });
});
</code></pre>
<h3 id="heading-13-authentication-and-authorization-testing">13. Authentication and Authorization Testing</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test authentication and authorization</span>
pm.test(<span class="hljs-string">"Authentication and authorization"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> authToken = pm.environment.get(<span class="hljs-string">"authToken"</span>);

    pm.request.headers.add({ <span class="hljs-attr">key</span>: <span class="hljs-string">"Authorization"</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">"Bearer "</span> + authToken });
    pm.sendRequest(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) </span>{
        pm.expect(response.status).to.equal(<span class="hljs-number">200</span>);
        pm.expect(response.json().authorized).to.be.true;
    });
});
</code></pre>
<h3 id="heading-14-data-extraction-and-transformation">14. Data Extraction and Transformation</h3>
<p>Extract data from the response and transform it for further use or validation.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Extract and transform data from the response</span>
pm.test(<span class="hljs-string">"Data extraction and transformation"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> responseArray = pm.response.json().data;
    <span class="hljs-keyword">var</span> transformedData = responseArray.map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">item</span>) </span>{
        <span class="hljs-keyword">return</span> {
            <span class="hljs-attr">id</span>: item.id,
            <span class="hljs-attr">name</span>: item.first_name + <span class="hljs-string">" "</span> + item.last_name<span class="hljs-string">"
        };
    });

    // Use transformed data for assertions or environment variables
    pm.expect(transformedData[0].name).to.include("</span>John<span class="hljs-string">");
    pm.environment.set("</span>transformedData<span class="hljs-string">", JSON.stringify(transformedData));
});</span>
</code></pre>
<h3 id="heading-15-session-management">15. Session Management</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">//Simulate session management by saving and reusing session tokens.</span>
<span class="hljs-comment">// Session management using session tokens</span>
<span class="hljs-keyword">var</span> sessionToken;

pm.test(<span class="hljs-string">"Login and session management"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Perform login and extract session token from the response</span>
    sessionToken = pm.response.json().session_token;
    pm.environment.set(<span class="hljs-string">"sessionToken"</span>, sessionToken);
});

pm.test(<span class="hljs-string">"Authenticated request using session token"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Use the saved session token for authenticated requests</span>
    pm.request.headers.add({ <span class="hljs-attr">key</span>: <span class="hljs-string">"Authorization"</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">"Bearer "</span> + sessionToken });
    pm.sendRequest(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) </span>{
        pm.expect(response.status).to.equal(<span class="hljs-number">200</span>);
    });
});
</code></pre>
<h3 id="heading-16-pagination-testing">16. Pagination Testing</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Test APIs that return paginated results and validate pagination logic.</span>
<span class="hljs-comment">// Pagination testing</span>
pm.test(<span class="hljs-string">"Pagination testing"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> response = pm.response.json();
    <span class="hljs-keyword">var</span> currentPage = response.page;
    <span class="hljs-keyword">var</span> totalPages = response.total_pages;

    <span class="hljs-comment">// Validate pagination logic</span>
    pm.expect(currentPage).to.be.at.least(<span class="hljs-number">1</span>);
    pm.expect(currentPage).to.be.at.most(totalPages);
});
</code></pre>
<h3 id="heading-17-load-testing">17. Load Testing</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">//Perform load testing by sending multiple concurrent requests.</span>
<span class="hljs-comment">// Load testing with concurrent requests</span>
<span class="hljs-keyword">var</span> concurrentRequests = <span class="hljs-number">10</span>;

pm.test(<span class="hljs-string">"Load testing"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> requests = [];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; concurrentRequests; i++) {
        requests.push(pm.sendRequest);
    }

    <span class="hljs-built_in">Promise</span>.all(requests).then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">responses</span>) </span>{
        responses.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) </span>{
            pm.expect(response.status).to.equal(<span class="hljs-number">200</span>);
        });
    });
});
</code></pre>
<h3 id="heading-18-database-validation">18. Database Validation</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// Validate API responses by comparing them with data from a database.</span>
<span class="hljs-comment">// Database validation using a mock database</span>
<span class="hljs-keyword">var</span> mockDatabase = [
    { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Item 1"</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Item 2"</span> }
];

pm.test(<span class="hljs-string">"Database validation"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> response = pm.response.json();

    mockDatabase.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">item</span>) </span>{
        <span class="hljs-keyword">var</span> matchingItem = response.find(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">responseItem</span>) </span>{
            <span class="hljs-keyword">return</span> responseItem.id === item.id;
        });

        pm.expect(matchingItem.name).to.equal(item.name);
    });
});
</code></pre>
<blockquote>
<p>You can generate test cases using Postbot, which is located in the top right corner of the test case writing area.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693852750310/6660a9e2-6c8d-43af-bb08-c9821eeb5f50.png" alt /></p>
<p>You can write more complex test scripts using various assertions and conditions based on your API testing needs. Postman offers documentation and tutorials to help you learn more about writing test scripts and performing API testing effectively.</p>
]]></content:encoded></item><item><title><![CDATA[Get started with GitHub GHCR, an Alternative of DockerHub.]]></title><description><![CDATA[What is GHCR?
GHCR stands for Github Container registry, The GitHub Container registry allows you to host and manage your Docker container images in your personal or organization account on GitHub. One of the benefits is that permissions can be defin...]]></description><link>https://tech.pococare.com/get-started-with-github-ghcr-an-alternative-of-dockerhub</link><guid isPermaLink="true">https://tech.pococare.com/get-started-with-github-ghcr-an-alternative-of-dockerhub</guid><category><![CDATA[Docker]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Docker Hub]]></category><dc:creator><![CDATA[Deepak Kumar]]></dc:creator><pubDate>Tue, 05 Sep 2023 19:07:38 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-what-is-ghcr"><strong>What is GHCR?</strong></h2>
<p>GHCR stands for Github Container registry, The GitHub Container registry allows you to host and manage your Docker container images in your personal or organization account on GitHub. One of the benefits is that permissions can be defined for the Docker image independent from any repository, It's similar in function to Docker Hub but is tightly integrated with GitHub.</p>
<p>To developer → setting → generate new token → usetoken → startbuilding images.</p>
<p><strong>To work with GHCR we have to create PAT (Personal Access Token).</strong></p>
<p>To use GHCR you need to generate a PAT (Personal Access Token) is a type of token used to authenticate and authorize access to resources on GitHub. PATs are commonly used to grant third-party applications or services limited access to your account without exposing your actual account credentials.</p>
<h2 id="heading-setting-up-github-container-registry-ghcr"><strong>Setting up GitHub Container Registry (GHCR)</strong></h2>
<p>Setting up GitHub Container Registry (GHCR) for storing Docker images involves a few steps. Here's a guide on how to set up an account on GHCR and push images for different services, similar to how you would on Docker Hub:</p>
<p><strong>Step 1: GitHub Account:</strong><br />If you don't already have a GitHub account, you'll need to create one. Visit <a target="_blank" href="https://github.com/">https://github.com/</a> to sign up.</p>
<p><strong>Step 2: Create a Repository:</strong><br />Create a repository on GitHub to store your Docker images. You can either create a new repository or use an existing one.</p>
<p><strong>Step 3: Authenticate with GitHub Personal Access Token (PAT):</strong><br />To push images to GHCR, you need to authenticate using a GitHub Personal Access Token (PAT) with the write:packages scope. Here's how to create and use a PAT:</p>
<ol>
<li><p>Go to your GitHub account settings and navigate to "Developer settings" &gt; "Personal access tokens."</p>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693934522739/c685e39e-2f51-4baf-a42a-0e70f3fc80fe.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Click on "Generate new token."</p>
</li>
<li><p>Select Tokens Classic .</p>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693934564899/9697c8a8-7a58-4bc5-82f5-048c02600bdb.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Give the token a name, select the write:packages scope, and generate the token.</p>
</li>
<li><p>Copy the generated token.</p>
</li>
</ol>
<p><strong>Step 4: Authenticate with Docker:</strong><br />Before you can push images to GHCR, you need to log in to the GitHub Container Registry using your GitHub username and the PAT you generated.</p>
<p>In your terminal, run:</p>
<pre><code class="lang-plaintext">docker login ghcr.io -u USERNAME -p YOUR_PAT
</code></pre>
<p>Replace USERNAME with your GitHub username and YOUR_PAT with the copied Personal Access Token.</p>
<p><strong>Step 5: Tag and Push Images:</strong><br />Now that you're logged in, you can tag your Docker images to push them to GHCR:</p>
<ol>
<li><p><strong>Build Your Image:</strong><br /> Navigate to the directory containing the Dockerfile for your service. Build your Docker image with a tag using the following command:</p>
<pre><code class="lang-plaintext"> docker build -t ghcr.io/USERNAME/REPO_NAME/IMAGE_NAME:TAG .
</code></pre>
</li>
<li><p><strong>Push Your Image:</strong><br /> Push the tagged image to GHCR:</p>
<pre><code class="lang-plaintext"> docker push ghcr.io/USERNAME/REPO_NAME/IMAGE_NAME:TAG
</code></pre>
</li>
</ol>
<p><strong>Step 6: View Your Images on GHCR:</strong><br />Visit the "Packages" section of your GitHub repository to view the images you've pushed to GHCR.</p>
<p>Also, you can use this method to reference</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693934453924/6f8992d8-1d92-4091-837e-62e088f42391.png" alt class="image--center mx-auto" /></p>
<h4 id="heading-see-in-the-image-to-the-push-refers-to-repository-ghcriouseridreponamehttpghcriodeepakpococarepocoverse-imagespoco-customer-websiteimagename">See in the image To The push refers to repository [<a target="_blank" href="http://ghcr.io/deepakpococare/pocoverse-images/poco-customer-website">ghcr.io/userId/repoName/</a>imageName ]</h4>
<p>copy this URL and past in the browser you will get interface like that below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693934333555/a48b3f44-db29-43a9-bf93-90bc0ed78633.png" alt class="image--center mx-auto" /></p>
<p>Remember that the repository structure for GHCR follows this format: ghcr.io/USERNAME/REPO_NAME/IMAGE_NAME:TAG.</p>
<p>By following these steps, you can set up your GitHub account to push Docker images to GHCR for different services, just like you would on Docker Hub, and you can use these images for deployment of the application .</p>
<p>Thank you .</p>
]]></content:encoded></item><item><title><![CDATA[When to Use Redux and When to Use Context API: Making the Right Choice for State Management]]></title><description><![CDATA[State management is a critical aspect of building robust and scalable applications, especially in the realm of modern web development. Two popular state management solutions in the React ecosystem are Redux and the Context API. Each has its strengths...]]></description><link>https://tech.pococare.com/redux-vs-context-api</link><guid isPermaLink="true">https://tech.pococare.com/redux-vs-context-api</guid><category><![CDATA[React]]></category><category><![CDATA[Redux]]></category><category><![CDATA[context API]]></category><dc:creator><![CDATA[Atul]]></dc:creator><pubDate>Tue, 05 Sep 2023 19:07:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1693940165895/45a6e5e6-893e-49ca-a63e-03a4c1e38494.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>State management is a critical aspect of building robust and scalable applications, especially in the realm of modern web development. Two popular state management solutions in the React ecosystem are Redux and the Context API. Each has its strengths and weaknesses, making them suitable for different scenarios. In this article, we will explore when to use Redux and when to use the Context API, helping you make informed decisions for your projects.</p>
<h3 id="heading-redux"><strong>Redux</strong></h3>
<p>Redux is a predictable state container for JavaScript applications, primarily used with React. It's known for its unidirectional data flow and centralized state management. Here are some scenarios where Redux shines:</p>
<ol>
<li><p><strong>Large-scale Applications:</strong> Redux is an excellent choice for complex applications with a vast amount of state. Its centralized store ensures that state changes are predictable and traceable.</p>
</li>
<li><p><strong>Shared State:</strong> When multiple components need access to the same state, Redux's global store eliminates the need for prop drilling or context sharing. This is especially beneficial in deeply nested component hierarchies.</p>
</li>
<li><p><strong>Time-Travel Debugging:</strong> Redux provides a powerful debugging tool called "time-travel debugging," allowing you to step backward and forward through state changes. This is invaluable for debugging complex applications.</p>
</li>
<li><p><strong>Middleware Integration:</strong> Redux's middleware architecture allows you to incorporate features like asynchronous actions, logging, and more seamlessly.</p>
</li>
<li><p><strong>Strict Data Flow:</strong> Redux enforces a strict unidirectional data flow, making it easier to reason about your application's state changes and maintain a predictable state.</p>
</li>
</ol>
<h3 id="heading-context-api"><strong>Context API</strong></h3>
<p>The Context API is a part of React itself and provides a way to share values like themes, user data, or localization preferences throughout the component tree without prop drilling. Here are some scenarios where the Context API is a suitable choice:</p>
<ol>
<li><p><strong>Small to Medium-sized Applications:</strong> For relatively simple applications where state management needs are not overly complex, the Context API can simplify the development process.</p>
</li>
<li><p><strong>Local Component State:</strong> When state is needed only within a single component or a limited subtree of the component hierarchy, using the Context API can reduce unnecessary complexity.</p>
</li>
<li><p><strong>Avoiding Prop Drilling:</strong> If you find yourself passing props down through multiple levels of components and it becomes cumbersome, the Context API can be a cleaner solution for sharing data.</p>
</li>
<li><p><strong>Quick Prototyping:</strong> For rapid prototyping or small projects, the Context API can help you get started quickly without the overhead of setting up Redux.</p>
</li>
<li><p><strong>React-specific Use Cases:</strong> If you are building a library or framework that integrates deeply with React and needs to manage its own state contextually, the Context API may be the preferred choice.</p>
</li>
</ol>
<h3 id="heading-when-to-choose-both"><strong>When to Choose Both</strong></h3>
<p>In some cases, you may find that using both Redux and the Context API is the best approach. For instance:</p>
<ol>
<li><p><strong>Mixed State Requirements:</strong> If your application has a mix of global and local state needs, you can use Redux for global state and the Context API for local component state.</p>
</li>
<li><p><strong>Integration with Legacy Code:</strong> When working on a project that already uses Redux, but wants to leverage the simplicity of the Context API for certain components, you can use them in parallel.</p>
</li>
<li><p><strong>Migration Planning:</strong> If you're transitioning from one state management solution to another, you can gradually refactor your application to use the new approach where it makes the most sense.</p>
</li>
</ol>
<p><strong>Conclusion</strong></p>
<p>The choice between Redux and the Context API depends on the specific needs of your project. Redux excels in managing large-scale applications with shared state and offers powerful debugging tools. On the other hand, the Context API is ideal for smaller applications, local state management, and avoiding prop drilling.</p>
<p>Remember that you don't need to limit yourself to just one approach. In many cases, a combination of both Redux and the Context API can provide the flexibility and simplicity required to build effective and maintainable React applications. The key is to assess your project's requirements and choose the solution that best fits your needs.</p>
]]></content:encoded></item></channel></rss>