<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abhishek Rathore on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Rathore on Medium]]></description>
        <link>https://medium.com/@rathore?source=rss-20cfddb2e89c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RnmVjsLOJqQxuaHI.</url>
            <title>Stories by Abhishek Rathore on Medium</title>
            <link>https://medium.com/@rathore?source=rss-20cfddb2e89c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 18:02:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rathore/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Beginner’s Guide to Ionic Angular Unit Testing (Part 3) — Async Testing]]></title>
            <link>https://medium.com/enappd/beginners-guide-to-ionic-angular-unit-testing-part-3-async-testing-31190a540f3b?source=rss-20cfddb2e89c------2</link>
            <guid isPermaLink="false">https://medium.com/p/31190a540f3b</guid>
            <category><![CDATA[automate-testing]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ionic]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Abhishek Rathore]]></dc:creator>
            <pubDate>Fri, 28 Aug 2020 06:58:47 GMT</pubDate>
            <atom:updated>2020-08-28T06:58:47.051Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beginner’s Guide to Ionic Angular Unit Testing (Part 3) — Async Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_nItaPiRYD0aJDZqF8sqg.png" /></figure><p>In this series, we are talking about Angular Testing using an Ionic Angular application. Till now we have seen the <a href="https://enappd.com/blog/beginners-guide-to-ionic-angular-unit-testing-part-1/151/">basic setup process</a>, the <a href="https://enappd.com/blog/beginners-guide-to-ionic-angular-unit-testing-part-1/151/">understanding of the core concept of Unit Testing</a> — in mainly Components Testing. However, we have not touched upon a very important aspect of Javascript programming — ASYNC functions(which have been making promises friendly). Async functions always <strong>return</strong> a promise.</p><p>Yes, all functions which have return values as <strong>Promise</strong> OR <strong>Observable </strong>— which makes our lives hard as a programmer 😅</p><p>For those who have been not following this <a href="https://enappd.com/blog/beginners-guide-to-ionic-angular-unit-testing-part-1/151/">series</a> — till now, we have created a simple Ionic Angular application with the following:</p><ol><li>List component for displaying Jobs (A Simple TODO Style App).</li><li>Service called ApiService -This List component adds data and gets data from a Service called ApiService</li></ol><p>Now for this part of series, we will call an AJAX call of Github Jobs API to fetch few Real life jobs posted over the web.</p><h3>Preparations 🧑‍🍳</h3><pre>fetchJobs(){</pre><pre>return this<br>  .http<br>  .get(<strong>&#39;https://github-jobs-proxy.appspot.com/positions?description=javascript&amp;location=san+francisco</strong>&#39;);</pre><pre>}</pre><p>We have this simple API call to our api.service.ts file which we are using to fetch Jobs. Don’t forget to import HTTPClient and then do the required initialization in the constructor.<br> We have used a proxies URL to bypass the CORS issue which happens when you call the official GitHub API for Jobs.</p><p>In our <strong>Tab1 Component</strong> file, we are adding a call to this function.</p><pre>ngOnInit(){</pre><pre>this.jobs = this.apiService.getJobs();<br><strong>   this.githubJobs = this.apiService.fetchJobs();  // &lt;&lt; ADD THIS<br></strong> <br>}</pre><p>Now as a final part of our preparation let’s add this to our HTML template. As we know this <strong>http.get() </strong>will return an Observable. By using the <strong>async pipe </strong>in Angular, in our template, we can automatically subscribe to it.</p><pre>&lt;ion-item&gt;</pre><pre>&lt;ion-label color=&quot;secondary&quot;&gt;Github Jobs By Observable&lt;/ion-label&gt;</pre><pre>&lt;/ion-item&gt;</pre><pre>&lt;ion-list&gt;</pre><pre>&lt;ion-item *ngFor=&quot;<strong>let job of githubJobs | async</strong>&quot;&gt;</pre><pre>&lt;ion-label&gt;<strong>{{job.title}}</strong>&lt;/ion-label&gt;</pre><pre>&lt;/ion-item&gt;</pre><pre>&lt;/ion-list&gt;</pre><p>As you can see we have added a list in which we are using *ngFor to loop over each item provided by Observable.</p><figure><img alt="Preview of List Created via Github Jobs API" src="https://cdn-images-1.medium.com/max/913/1*sDuK_y-YgfxZXh9FDh031Q.png" /><figcaption>Preview of List Created via Github Jobs API</figcaption></figure><h3>Testing</h3><p>From the <a href="https://enappd.com/blog/beginners-guide-to-ionic-angular-unit-testing-part-2-mocks-and-spies/155/">previous part</a> of this <a href="https://enappd.com/blog/beginners-guide-to-ionic-angular-unit-testing-part-1/151/">series</a>, we know that — we are using a <a href="https://enappd.com/blog/beginners-guide-to-ionic-angular-unit-testing-part-2-mocks-and-spies/155/">Mock/Stub Service for APIService </a>in out Test File — we will need to Stub the new Function as well — I will add a line for this in our Spec File.</p><pre>const ApiServiceStub = {</pre><pre>addJob: () =&gt; null,</pre><pre><strong>fetchJobs: () =&gt; from([[{title: &#39;job1&#39;}, {title: &#39;job2&#39;}]]),</strong></pre><pre>getJobs: () =&gt; []</pre><pre>};</pre><p>You can observe that there are 2 brackets <strong>[[ </strong>in above. We are using from <strong>rxjs</strong> operator which takes an Array as input &amp; it returns each element one by one.</p><p>We only need to return 1 value. We know that Jobs array is expected returned value for this function. So we create a single data — an array inside an array. This will mimic the Github API response — which also returns only 1 array.</p><p>We have just used Title in our application, so we have simplified the object also in testing.</p><p>If you are new to Testing and wondering why in God’s name this API function call is being stubbed — while we have original API available to test with. Please <a href="https://enappd.com/blog/beginners-guide-to-ionic-angular-unit-testing-part-1/151/">understand this is<strong> Unit Testing</strong></a> and component doesn’t want to be dependent on the Service or anything.</p><p>We just have the assumption that service will return this kind of output — and that is what component expects. If this expectation is not right, then we need to work on Service rather than changing our component’s logic.</p><p>Now let’s add a test to our tab1.page.spec.ts</p><pre>it(&#39;fetchJobs should return Observable which contains array of Jobs&#39;, () =&gt; {</pre><pre>fixture.detectChanges();</pre><pre><strong>component.githubJobs.subscribe</strong>((result) =&gt; {<br>  expect(result.length).toBeDefined();<br>  expect(result[0].title).toBeDefined();<br>  <br>  });</pre><pre>});</pre><p>You can see that we have subscribed to the Observable to get its value. Before that, we have called fixture.detectChanges() which will call the ngOnInit function. As it will immediately emit the array we have added to the stub. This test will work fine.</p><p>Let run ng test</p><figure><img alt="karma server output" src="https://cdn-images-1.medium.com/max/664/1*drO2qZOr58A4x9TmiJIwtQ.png" /><figcaption>All tests passing with the Last one Showing the Observable Test</figcaption></figure><p><strong>All passing!</strong></p><h3>Using Promises</h3><p>We just went through an easy part of testing with Observable. Let’s move to a more complex part of working with <strong>Promises</strong>.</p><p>We will adjust our Github API function to return a Promise rather than observable. In fact, we will make a copy of the function just to have both an <strong>Observable</strong> and <strong>Promise</strong> style working together.</p><pre>fetchJobsByPromise(){</pre><pre>return this.http<br>.get(&#39;https://github-jobs-proxy.appspot.com/positions?description=javascript&amp;location=san+francisco&#39;)<br><strong>.toPromise();</strong></pre><pre>}</pre><p>We added fecthJobsByPromise function to our service file. It uses toPromise function to convert the <strong>Observable</strong> output to <strong>Promise</strong> based Output.</p><p>Next in Component/Page, we will add a call to this service function.</p><pre>ngOnInit(){</pre><pre>this.jobs = this.apiService.getJobs();<br>   this.githubJobs = this.apiService.fetchJobs();</pre><pre><strong>this.apiService.fetchJobsByPromise().then((jobs) =&gt; {<br>       this.githubJobsByPromise = jobs;<br>   });</strong></pre><pre>}</pre><p>As you can see above, we have created githubJobsByPromise — a view variable to store the result of the resolved promise. Now we will change the template to have a very similar list of jobs from this githubJobsByPromise.</p><pre>&lt;ion-item&gt;</pre><pre>&lt;ion-label color=&quot;secondary&quot;&gt;Github Jobs By Promise&lt;/ion-label&gt;</pre><pre>&lt;/ion-item&gt;</pre><pre>&lt;ion-list&gt;</pre><pre>&lt;ion-item *ngFor=&quot;<strong>let job of githubJobsByPromise</strong>&quot;&gt;</pre><pre>&lt;ion-label&gt;{{<strong>job.title</strong>}}&lt;/ion-label&gt;</pre><pre>&lt;/ion-item&gt;</pre><pre>&lt;/ion-list&gt;</pre><p>All set. Let’s run the whole thing.</p><figure><img alt="Ionic Tab Page: with List of Jobs" src="https://cdn-images-1.medium.com/max/882/1*0Dt_4N_-ek8-TmP-oEJx1A.png" /><figcaption>Same List twice (Promise and Observable)</figcaption></figure><p>Back to testing.</p><p>We are adding a very small test which will check the value of githubJobsFromPromise</p><pre>it(&#39;fetchJobByPromise should be array of Jobs&#39;, () =&gt; {</pre><pre>fixture.detectChanges();</pre><pre>expect(component.githubJobsByPromise.length).toBeDefined();<br>  expect(component.githubJobsByPromise[0].title).toBeDefined();</pre><pre>});</pre><p>If your test server is still running you can check the browser window of Karma Server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*LQ-zE4gF1XhgevpdKcZOUQ.png" /><figcaption>Karma Server: Failed Test Cases</figcaption></figure><p>So, we have missed adding the Promise implementation on our <strong>Service Stub</strong> — So you can face a similar error.</p><pre>const ApiServiceStub = {</pre><pre>addJob: () =&gt; null,<br> fetchJobs: () =&gt; from([[{title: &#39;job1&#39;}, {title: &#39;job2&#39;}, {title: &#39;job3&#39;}]]),</pre><pre><strong>fetchJobsByPromise: () =&gt; Promise.resolve([{title: &#39;job1&#39;}, {title: &#39;job2&#39;}, {title: &#39;job3&#39;}]),</strong></pre><pre>getJobs: () =&gt; []</pre><pre>};</pre><p>Added it — a simple Promise which will resolve in a job object array.</p><p>Let&#39;s check again.</p><figure><img alt="Karma Server : Test failed" src="https://cdn-images-1.medium.com/max/877/1*kudz0cDEwYrGuS2CR6iNRw.png" /><figcaption>Test failed: Array is Undefined</figcaption></figure><p>So, what happened here. This is due to the asynchronous nature of promise and the way Javascript executes. expect calls are executed even before the promise has resolved.</p><p>You can put some kind of setTimeout hack for expect and maybe it works sometimes but that’s not a proper way.</p><h3>Async</h3><p>Don’t get it wrong !!</p><p>This async is not the same as in async/await. This a special function we can use in Angular jasmine testing.</p><p>We will import it at top :</p><pre>import { async, ComponentFixture, TestBed} from &#39;@angular/core/testing&#39;;</pre><p><strong>Async</strong> wraps the test functions — which we think will have promises and we want to wait till they are resolved</p><pre>it(&#39;fetchJobByPromise should be array of Jobs&#39;, <strong>async(</strong>() =&gt; {</pre><pre>fixture.detectChanges();</pre><pre><strong>fixture.whenStable().then(() =&gt; {  </strong>   <br>   expect(component.githubJobsByPromise.length).toBeDefined();<br>   expect(component.githubJobsByPromise[0].title).toBeDefined();<br> <strong> });</strong></pre><pre>})<strong>)</strong>;</pre><p>Also, you can see a special function fixture.whenStable() which is called to wrap the expected part. This part will run once all the Promises will be resolved from the Angular component.</p><p>Let’s check again</p><figure><img alt="Karma Server: Test Passing" src="https://cdn-images-1.medium.com/max/595/1*sO5t4XindMfwMZut44o3BQ.png" /><figcaption>Karma Server: Test Passing</figcaption></figure><h3>FakeAsync and Tick</h3><p>There is one more way is to do asynchronous testing — using FakeAsync and Tick functions. Let us move to testing of asynchronous code with FakeAsync in Angular.</p><p>Import these here :</p><pre>import { async, ComponentFixture, TestBed, fakeAsync, tick } from &#39;@angular/core/testing&#39;;</pre><p>Now you can wrap the function in <strong>fakeAsync </strong>and then call the <strong>tick()</strong> just before the lines — it will act as a way to stop executing till JS resolves the Promises.</p><pre>it(&#39;fetchJobByPromise should be array of Jobs (Using Fake Async)&#39;, <strong>fakeAsync</strong>(() =&gt; {</pre><pre>fixture.detectChanges();</pre><pre><strong>tick();</strong><br>  expect(component.githubJobsByPromise.length).toBeDefined();<br>  expect(component.githubJobsByPromise[0].title).toBeDefined();</pre><pre>}));</pre><p>Let’s check this test result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*qPHe9MZaQv4aJoTnOEBf-w.png" /><figcaption>Karma Server: Tests Passed</figcaption></figure><p>The main difference between <strong>fakeAysnc</strong> and <strong>async</strong>, in angular testing, is the style of calling — while whenStable().then() calls can create an ugly nested structure when we have many async calls to test inside one function. However, there are some actual differences also — like for example XHR calls are mostly tested with async calls only.</p><p>Let’s try something new here, I will add some timeout in our Stub function to have a delay (4000ms) in Promise resolution.</p><pre>fetchJobsByPromise: () =&gt; {</pre><pre>return new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    resolve([{title: &#39;job1&#39;}, {title: &#39;job2&#39;}, {title: &#39;job3&#39;}]);<br>   }, 4000);<br>  });</pre><pre>}</pre><p>Now if we run tests again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*XJwiFlxMZ8XBLaFXaZuYDg.png" /><figcaption>Karma Server: Fake Async Test fails</figcaption></figure><p>So async has survived this timeout but fakeAsync didn’t. How can it be done with tick now — use tick(4000) . Yes, tick has a method pass delay also. Now it will work like charm.</p><h3>Done CallBack</h3><p>There is one more style of Jasmine testing which is — in-built in Jasmine wheredone an argument is passed as 1st argument in test function. It acts as a callback — which holds the test until the time done is not executed.</p><p>For the test where there is an unexpected delay in the execution, we can use this as a final resort.</p><pre>it(&#39;fetchJobByPromise should be array of Jobs (done callback)&#39;, (<strong>done</strong>) =&gt; {</pre><pre>fixture.detectChanges();</pre><pre>setTimeout(() =&gt; {</pre><pre>expect(component.githubJobsByPromise.length).toBeDefined();<br>   expect(component.githubJobsByPromise[0].title).toBeDefined();<br>   <strong>done();<br></strong>}, 5000); // delay is more than time for Promise resolve</pre><pre>});</pre><p>In the above example, you can check how done( ) callback is used. This example is not the best one as we have created some delay deliberately to test. But we can understand how it holds the test for that duration — which otherwise will fail or say that no expectation was found.</p><p>Let’s check the test results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*dU1aSQijf7L_4WkxdD6TRQ.png" /><figcaption>Karma Server: Test Timeout</figcaption></figure><p>You might <strong>not</strong> have seen this error before, we have a test timeout limit reached. As tests can’t run forever there is a Timeout decided by Karma. Here the default is <strong>5000ms</strong> which exactly matching our delay. Hence it failed.</p><p>So, we can decrease the timeout, but…….</p><p>…… If in future we need to run a longer test case what you will do? That’s why we will not change our code but will increase the timeout threshold.</p><pre>jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;</pre><p>Add this line to beforeEach section — this will change the timeout. Let’s check out now.</p><figure><img alt="Karma Server: All test passing after increasing DEFAULT_TIMEOUT_INTERVAL" src="https://cdn-images-1.medium.com/max/616/1*OPsfke1wkYM7BYw_YXfugw.png" /><figcaption>Karma Server: All test passing after increasing DEFAULT_TIMEOUT_INTERVAL</figcaption></figure><p>Finally ✌️</p><p>Here is our final Test file looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaec358f91ed7d41e92a5804248af82f/href">https://medium.com/media/aaec358f91ed7d41e92a5804248af82f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31190a540f3b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enappd/beginners-guide-to-ionic-angular-unit-testing-part-3-async-testing-31190a540f3b">Beginner’s Guide to Ionic Angular Unit Testing (Part 3) — Async Testing</a> was originally published in <a href="https://medium.com/enappd">Enappd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s Guide to Ionic Angular Unit Testing (Part 2) — Mocks and Spies]]></title>
            <link>https://medium.com/enappd/beginners-guide-to-ionic-angular-unit-testing-part-2-mocks-and-spies-95a9e775133e?source=rss-20cfddb2e89c------2</link>
            <guid isPermaLink="false">https://medium.com/p/95a9e775133e</guid>
            <category><![CDATA[automated-testing]]></category>
            <category><![CDATA[testing-services]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ionic]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Abhishek Rathore]]></dc:creator>
            <pubDate>Mon, 24 Aug 2020 16:11:38 GMT</pubDate>
            <atom:updated>2020-08-24T16:11:38.193Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beginner’s Guide to Ionic Angular Unit Testing (Part 2) — Mocks and Spies</h3><figure><img alt="Beginner’s Guide to Ionic Angular Unit Testing (Part 2) — Mocks and Spies" src="https://cdn-images-1.medium.com/max/1024/1*B_nItaPiRYD0aJDZqF8sqg.png" /></figure><p>In our first part of this series, we saw how to set up the basic testing environment and got familiar with some of the terminologies for Unit Testing in the Angular world. Now you should be able to know — Karma, Jasmine tests, TestBed, Unit Testing: Mocks &amp; Stubs etc.</p><p>In this part, we will move further and add some more functionality to our app with the help of Angular Services(Testing services). As service dependencies will be injected into the components they will increase the complexity of our tests. Let’s jump ahead to the coding part.</p><p>We have added some code in a new Service called ApiService — this service will be used by our page to add jobs and store existing jobs. As you know in any complex application, services should have the business logic and components should do only view update related stuff. So we prefer to use Services as basic building blocks for business logic</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9acdf9a984106526b2d38a1687d14e7/href">https://medium.com/media/b9acdf9a984106526b2d38a1687d14e7/href</a></iframe><p>The above code also has an AlertComponent, which we will use to show that job has been added to the Job List successfully.</p><p>Now let’ see how our component/page code looks like :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df2641142cca49f3328264b51c5b2bc9/href">https://medium.com/media/df2641142cca49f3328264b51c5b2bc9/href</a></iframe><p>Very simple code. this.jobs still will have the job array — through the binding to service variable — But now data is stored in the service. addJob function has the same structure except for the logic — which has been moved to the service.</p><p>At this moment if you will run your tests they will pass! Surprisingly 😮</p><p>As we only tested jobs in our previous tests - which is still the same and function calls also remain the same.</p><p>However, now I want to add a more deep test which will check if addJob function of apiService is called or not. This function is now doing the main job of storing the data in jobs array. Now let us move forward in Angular testing using Spies by looking at testing with mocks &amp; spies.</p><h3>SPIES in Testing🕵</h3><p>For checking whether a function is called we create something called SPY. This spy is actually a fake implementation and it runs in place of the actual function. Test spy is an object that records its interaction with other objects all round the code base.</p><p>So we need something like this in our test code</p><pre>spyOn(apiService, &#39;addJob&#39;);</pre><p>The above statement means the object apiService is the parent object which has addjob target function. Only this target functions will be spied upon.</p><p>But wait !! how we got this apiService in the Test file? We don’t have discussed any concept of service injection in Test files yet.</p><p>Here’s how we can inject the apiService in our TestBed (for testing services with the TestBed) — very similar to as we do in the module. Under the providers</p><pre>TestBed.configureTestingModule({<br>  declarations: [Tab1Page],<br>  imports: [IonicModule.forRoot(), ExploreContainerComponentModule],<br>  providers: [ ApiService ]<br>}).compileComponents();</pre><p>However, I will not like to add the real Service here — WHY ?? 🤔</p><p>The reason is that your app may get too complicated and we might not want to understand what service is doing. We just want to test our component’s code independently.</p><p>So we MOCK our service also.</p><p>After having a closer look at test spies let us move to mocking with fake classes.</p><h3>MOCKS in Testing 🐵</h3><p>Mocks or Stubs as they are rightly called — represent a fake object or class which contains similar signature (objects and methods) to that of the original class. These functions may not do anything but their fake implementation is helpful in testing the unknown part of code.</p><p>Most people actually refer to Test Doubles while talking about Mocks. A Test Double is simply another object that can be passed in its place, which is similar to the interface of the required Collaborator.</p><p>Let us see mocking in testing. For example, in our component testing, we don’t need to know what getJobs is doing and how. We just know that it returns an array so we can stub that method in our Mock.</p><p>Here is an example of ApiServiceStub :</p><pre>const ApiServiceStub = {<br>   addJob: () =&gt; null,<br>   getJobs: () =&gt; []<br>};</pre><p>Yes, it does nothing but returns something similar to what actual function returns. Now let’s use this Stub/Mock to create a fake ApiService in our test file. We will use providers again to inject this. However this time we will use</p><pre>providers: [{ provide: ApiService, useValue: ApiServiceStub },]</pre><p>Above Syntax can read as ApiService created from an Object value ApiServiceStub. In Place of useValue you can use another syntax useClass sometimes — when you have a Class for the Mock/Stub.</p><p>So now we have a Service ApiService also available in our Test file. But as we do it in components, we will instantiate a new object from Service. In components we use constructor this — here we will use TestBed’s inject method. We will add a line :</p><pre>apiService = TestBed.inject(ApiService)</pre><p>Now let’s see our completed tests file. Look at how we added Service file, how we instantiated it, and how we changed the Last Test :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/024b78d789ea24306ff5395bfddab186/href">https://medium.com/media/024b78d789ea24306ff5395bfddab186/href</a></iframe><p>If you check the last test we added a SPY and also we expected that those functions will be called. We are using toHaveBeenCalled and toHaveBeenCalledWith to check if the Spied function was called. The two functions toHaveBeenCalled and toHaveBeenCalledWith only differ slightly. The later one also checks whether the argument passes also matches. We have just used both to showcase the difference. In the above scenario, You can only have to use the second one toHaveBeenCalledWith — as it tells whether functions are being called and also the arguments.</p><p>If you run the test now — it will have a failure. And failure is in the Test which was passing earlier. WHY ?? Any guesses?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1stBbh2zFdr_Ms2k23JYsA.png" /></figure><p>As you have stubbed the service with fake implementation — your component is always using the fake implementation and you are always getting an empty array in return from getJobs . Above test expected more than 1 element.</p><p>Now you know testing is hard if you don’t think of side-effects.</p><p>So, I will not inject this Mock Service globally and inject it in a specific case only where it is needed. I am using Testbed.OverrideProvider in this case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5298812c8cc969cdba36c7a0b50278a5/href">https://medium.com/media/5298812c8cc969cdba36c7a0b50278a5/href</a></iframe><p>But in real-life testing, you will want to have the only stub and not real service at all. So above ugly workaround is not something to be proud of.</p><p>Let’s rethink our code how we can make all tests work with Stubbed Service. Can there be a way that our fake getJobs return something meaningful? The answer is YES</p><h3>SPY methods</h3><p>Till now we just used SpyOn, to test the component logic, to create a SPY for a function. But that spy was not doing anything expect capturing the call to function. However, we have a lot of methods available on <strong>SpyOn</strong> output object — which can provide some life to our spied on methods. These are :</p><ul><li><strong>returnValue</strong> — this returns a value you mention from the spied method</li><li><strong>callFake</strong> — this provides a way to implement some fake function to be called when it is spied. You can even replace it will the code of the original method. But mostly a bad idea as testing should be simpler.</li><li><strong>callThrough</strong> — this is also a way in which you still want to use the SPY but leave the functionality un-touched and the original method can be called. In the case of our Test file — this original method is still not the one in service method — it is the one in the Stub Object - getJobs . So we can’t use it here.</li></ul><p>Let’s use the easiest one returnValue</p><pre>it(&#39;addJob should add the job string to jobs array&#39;, () =&gt; {</pre><pre>const job = &#39;Dummy Job&#39;;<br> spyOn(apiService, &#39;addJob&#39;);<br> spyOn(apiService, &#39;getJobs&#39;).and.returnValue([job]);</pre><pre>component.addJob(job);<br> expect(component.jobs.length).toBeGreaterThan(0);<br> expect(component.jobs).toContain(job);</pre><pre>});</pre><p>So we have spied on both functions addJob and getJobs . However, getJobs now is returning the value of an array [job] . Yes, we have hardcoded the value here — but that’s ok for testing components, as we already believe services are working fine, they will be tested separately.</p><p>Now we have to change the file again — stub providers only at the top &amp; no ugly overrides. However, there will be still a problem as getJobs will run even before the spies work. Because it is written in the constructor.</p><p>We can use ngOnInit which is more flexible and its call can be controlled in the Testing environment by</p><pre>fixture.detectChanges();</pre><p>This line controls the angular component loading activity and also calls ngOnInit . So we will remove this line from the common section of beforeEach and call only in the function we need to have ngOnInit called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50266afa7c6f9aef4b73bbd3df65498d/href">https://medium.com/media/50266afa7c6f9aef4b73bbd3df65498d/href</a></iframe><p>Carefully see the line where we added fixture.detectChanges() — Just after putting the spies. Be careful about placing the things in the test. If you put spies after the action — they will not act properly.</p><p>Now again let’s run tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*ganLlWoLemyJUaxIRba3ag.png" /></figure><p>All passing !!</p><p>But, we did cheating here. We have just passed something in getJobs which was not called sent by addJob — this means it’s not checking the actions of addJob.</p><p>So can we do better? Let’s change the code a little bit.</p><pre>const jobs = [];</pre><pre>spyOn(apiService, &#39;addJob&#39;).and.callFake((jb)=&gt;{<br>    jobs.push(jb);<br>});</pre><pre>spyOn(apiService, &#39;getJobs&#39;).and.returnValue(jobs);</pre><p>Now you can see — jobs is the common array accessed by both getJobs and addJob . Also, we have used callFake which give us more power to change the functionality of addJob functions.</p><p>Test Again.</p><p>All Passing !! 😇</p><p><strong>Stay tuned for Part 3 of this series !</strong></p><h3>Next Steps</h3><p>If you liked this blog, you will also find the following blogs interesting and helpful. Feel free to ask any questions in the comment section</p><ul><li>Ionic Payment Gateways — <a href="https://enappd.com/blog/ionic-4-stripe-payment-integration-with-firebase-for-apps-and-pwa/17">Stripe</a> | <a href="https://enappd.com/blog/ionic-4-paypal-payment-integration-for-apps-and-pwa/16">PayPal</a> | <a href="https://enappd.com/blog/how-to-integrate-apple-pay-in-ionic-4-apps/21">Apple Pay</a> | <a href="https://enappd.com/blog/how-to-integrate-razorpay-in-ionic-4-apps-and-pwa/20">RazorPay</a></li><li>Ionic Charts with — <a href="https://enappd.com/blog/ionic-4-charts-using-google-charts/66">Google Charts </a>| <a href="https://enappd.com/blog/adding-charts-in-ionic-4-apps-and-pwa-part-3/60">HighCharts</a> | <a href="https://enappd.com/blog/adding-charts-in-ionic-4-apps-and-pwa-part-2/54">d3.js</a> | <a href="https://enappd.com/blog/charts-in-ionic-4-apps-and-pwa-part-1/52">Chart.js</a></li><li>Ionic Social Logins — <a href="https://enappd.com/blog/facebook-login-in-ionic-4-apps-using-firebase/25">Facebook</a> | <a href="https://enappd.com/blog/google-login-in-ionic-4-apps-using-firebase/39">Google</a> | <a href="https://enappd.com/blog/twitter-login-in-ionic-4-apps-using-firebase/24">Twitter</a></li><li>Ionic Authentications — <a href="https://enappd.com/blog/email-authentication-with-firebase-in-ionic-4/38">Via Email</a> | <a href="https://enappd.com/blog/firebase-anonymous-login-in-ionic-4/37">Anonymous</a></li><li>Ionic Features — <a href="https://enappd.com/blog/using-geolocation-geocoding-and-reverse-geocoding-in-ionic-4/45">Geolocation</a> | <a href="https://enappd.com/blog/qr-code-scanning-and-optical-character-recognition-ocr-in-ionic-4/9">QR Code reader </a>| <a href="https://enappd.com/blog/best-fitness-plugins-for-ionic-4-how-to-use-pedometer/15">Pedometer</a>| <a href="https://enappd.com/blog/implement-signature-pad-in-ionic-apps/145/">Signature Pad</a></li><li>Media in Ionic — <a href="https://enappd.com/blog/spotify-like-music-in-ionic-4-apps/48">Audio</a> | <a href="https://enappd.com/blog/adding-video-player-in-ionic-4-app/64">Video</a> | <a href="https://enappd.com/blog/image-picker-in-ionic-4-app/67">Image Picker</a> | <a href="https://enappd.com/blog/how-to-add-image-cropper-in-ionic-4-app/68">Image Cropper</a></li><li>Ionic Essentials — <a href="https://enappd.com/blog/ionic-4-save-and-retrieve-data-locally-on-device/59">Native Storage</a> | <a href="https://enappd.com/blog/how-to-translate-in-ionic-4-globalization-internationalization-and-localization/11">Translations</a> | <a href="https://enappd.com/blog/rtl-right-to-left-use-in-ionic-4/50">RTL</a></li><li>Ionic messaging — <a href="https://enappd.com/blog/implement-ionic-4-firebase-push/34">Firebase Push</a> | <a href="https://enappd.com/blog/automatically-read-sms-in-ionic-4-apps/42">Reading SMS</a></li><li>Ionic with Firebase — <a href="https://enappd.com/blog/how-to-integrate-firebase-in-ionic-4-apps/23">Basics</a> | <a href="https://enappd.com/blog/firebase-with-ionic-4-hosting-auth-and-db-connection/58">Hosting and DB</a> | <a href="https://enappd.com/blog/firebase-cloud-functions-in-ionic-4-complete-guide/32">Cloud functions</a></li></ul><h3>Ionic React Full App with Capacitor</h3><p>If you need a base to start your next Ionic 5 React Capacitor app, you can make your next awesome app using <a href="https://store.enappd.com/product/ionic-react-full-app-capacitor/">Ionic 5 React Full App in Capacitor</a></p><figure><img alt="Ionic 5 React Full App in Capacitor from Enappd" src="https://cdn-images-1.medium.com/max/760/1*G3yOFVX4oABx9MhUy-3kng.png" /><figcaption>Ionic 5 React Full App in Capacitor from Enappd</figcaption></figure><h3>Ionic Capacitor Full App (Angular)</h3><p>If you need a base to start your next Angular <strong>Capacitor app</strong>, you can make your next awesome app using <a href="https://store.enappd.com/product/capacitor-full-app-with-ionic-angular/">Capacitor Full App</a></p><figure><img alt="Capacitor Full App with huge number of layouts and features" src="https://cdn-images-1.medium.com/max/736/0*UwSHcofTMStMnzAX.png" /><figcaption>Capacitor Full App with huge number of layouts and features</figcaption></figure><h3>Ionic Full App (Angular and Cordova)</h3><p>If you need a base to start your next Ionic 5 app, you can make your next awesome app using <a href="https://store.enappd.com/product/ionic-full-app">Ionic 5 Full App</a></p><figure><img alt="Ionic Full App with huge number of layouts and features" src="https://cdn-images-1.medium.com/max/700/0*1ArpKyhiDHZnevwB.jpeg" /><figcaption>Ionic Full App in Cordova, with huge number of layouts and features</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95a9e775133e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enappd/beginners-guide-to-ionic-angular-unit-testing-part-2-mocks-and-spies-95a9e775133e">Beginner’s Guide to Ionic Angular Unit Testing (Part 2) — Mocks and Spies</a> was originally published in <a href="https://medium.com/enappd">Enappd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s Guide to Ionic Angular Unit Testing (Part 1)]]></title>
            <link>https://medium.com/enappd/beginners-guide-to-ionic-angular-unit-testing-part-1-c081bb539915?source=rss-20cfddb2e89c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c081bb539915</guid>
            <category><![CDATA[ionic]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[automated-testing]]></category>
            <category><![CDATA[testbed]]></category>
            <dc:creator><![CDATA[Abhishek Rathore]]></dc:creator>
            <pubDate>Tue, 18 Aug 2020 11:01:11 GMT</pubDate>
            <atom:updated>2020-08-18T11:01:11.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_nItaPiRYD0aJDZqF8sqg.png" /></figure><p><strong>Angular</strong> is one of our favorite frameworks to work with — it might be complex to learn at first, but — it is a complete framework for front-end web development. As the framework is maturing by each version — it has become a reliable choice of any Long Term maintenance project. <br> <br> However, one can’t rely on software unless there is an assurance of code running properly every time you use it (or change it). That is why there is <strong>Testing</strong> — which automates the work of checking each aspect of code after every change. There are various ways of testing the code in Angular also -</p><ul><li><strong>Unit Testing</strong></li><li><strong>Integration Testing</strong></li><li><strong>End-to-End testing</strong></li></ul><p>In this series — we will cover techniques for <strong>unit testing Angular applications</strong> using the Ionic 5 Framework — which a popular mobile development framework for hybrid apps. You can use the same concepts in other Angular based apps also — not necessarily be <strong>Ionic</strong>. Testing your Angular application helps you check that your app is working as you expect.<br> <br>Let’s see the testing principles and understand the difference between various testing approaches. Before writing tests for your app, you should have a basic understanding of the following concepts:</p><p><strong>Unit Testing</strong> — It deals which checking only the JavaScript( or Typescript) part of the code. It is called Unit as we check only one unit of code specification at a time it can be a single condition or some functions output. However, this testing doesn’t tell us about whether the whole system works fine or not. Even it can’t tell you anything outside the scope of the unit — which is under test.<br> <br> <strong>Integration Testing</strong> — This is not always a common term in testing but in the case of Angular, it means working with the <em>HTML templates along with TypeScrip</em>t. So, if we want to check what rendered on the template — we will need Integration testing. As the Unit test can only tell you what is stored in the variables — it can’t tell you what happened in the browser and what was rendered. We will also be covering this topic in this series.<br> <br><strong> End-to-End testing</strong> — This is a complete flow testing of a feature. Suppose you have a feature — add the item to the Todo list. It will check the whole flow — right from adding to the object to it being added to the database and displayed back in the list. It is more complex to write such tests and they break easily once anything in the whole process changes. They are good for some sanity checks of the system — but writing e2e tests for everything in your system can’t be justified. The effort in testing might be more than developing the feature. We are not covering this kind of testing in our series.</p><h4>Understanding the concept of Unit Testing 💡</h4><p><strong>Unit testing</strong> as we described tests only a single point in the code e.g. a value of a variable. It may also check the return value of a function. But the main concept is — it only tests 1 major expectation after some activity happens.<br> <br> Now, for a developer like me who has never been into testing. It was hard to understand how testing works for unit testing in ionic applications. Whether the real code runs, does it runs completely like a full app, or just function we call is executed. We will clarify many such doubts in this series. In reality — it is a mix — where some part is real code and some part is fake code (fake data or functions). Unit tests and automated tests, in general, can help to verify that your codebase is behaving correctly.<br> <br> Our main focus in the UNIT test remains that only — the <em>system under test should have the real code</em> running. Whatever outside scope of this function may be real or fake — it doesn’t matter. For example. If you are testing a Boolean variable’s value it doesn’t matter whether that value resulted in some action (like a popup or something else). Only what matters it that is the value of the Boolean variable. However, in some other test cases, you might be more interested in whether Popup was called or not — Hence your expectations are everything in Unit testing. 🎅</p><p>Let us see how to unit test an Ionic/Angular Application.</p><h4>Setting up the Environment for Ionic Angular Testing</h4><p>The good part in Angular or Ionic Angular — we are getting everything we need for testing your Ionic App already set up. That is a Server to run the tests (Karma), a language to write our specifications (Jasmine), and other TestBed configuration which are seemingly complicated — at first.</p><p><strong>Ionic Unit Testing Example</strong></p><p><strong>Step 1 :</strong></p><p>I have chosen to use the tabbed version of the Ionic template to start with, if you want to go along, you can use the following command to install the tabs version of Ionic Angular Template :</p><pre>ionic start ionic-testing tabs --type=angular --capacitor</pre><p><strong>Step 2 :</strong></p><p>After running the whole setup you can check out if everything is working — by running the following command in your project directory.</p><pre>ionic serve</pre><p>You must get a screen like the following — (I am in dark mode — so don’t worry if yours is a little different) working fine ✌️</p><figure><img alt="Ionic Angular Tabs Template — Dark Mode" src="https://cdn-images-1.medium.com/max/1024/1*77Q8dkdn3ExB-Gqu9tyDaA.png" /><figcaption>Ionic Angular Tabs Template — Dark Mode</figcaption></figure><p><strong>Step 3: </strong>Set up testing</p><p>After checking the setup, we can check whether the test environment is working fine or not. We can use the command:</p><pre>npm test</pre><p>This will run the <strong>ng test</strong> CLI command as written in your <em>package.json</em>.</p><p>The log will show that Karma ran three tests that all passed.It will be shown in the last line of the log. A Chrome browser opens and displays the test output in the “Jasmine HTML Reporter” like this.</p><figure><img alt="Karma Server" src="https://cdn-images-1.medium.com/max/1024/1*WocH0MzbCUHWWtkHPkjljw.png" /><figcaption>Karma Server</figcaption></figure><p>Most people find the browser output(shown above) easier to read than the console log. You can click on a test row to re-run just that test or click on a description to re-run the tests in the selected test group (“test suite”). Meanwhile, the <strong>ng test </strong>command is watching for changes.</p><p>However, they are not very meaningful but they tell that our TestBed is working properly. If you run this command on an existing code this may not run properly because you might have many dependencies in existing code which are not available to testBed (more on this later).<br> <br> Now before writing our first test case, let’s jump into some basics about the setup and configuration of Angular Testing.</p><p>We will be using <strong>Karma </strong>and <strong>Jasmine</strong> to run the unit tests in our application.</p><h4>Karma Server</h4><p>As defined on the Karma runner official site. (<a href="http://karma-runner.github.io/5.0/intro/how-it-works.html">http://karma-runner.github.io/5.0/intro/how-it-works.html</a>)</p><blockquote><em>Karma is essentially a tool which spawns a web server that executes source code against test code for each of the browsers connected. The results of each test against each browser are examined and displayed via the command line to the developer such that they can see which browsers and tests passed or failed.</em></blockquote><p>A very complicated explanation — for us it simply means Karma starts a web server that runs our source code and also <strong>test code</strong> — and checks the results. It can work with multiple browsers in parallel — but in our case, we will stick only to 1 browser instance.<br> <br> In our case, it will open a new Chrome instance — why chrome? It is set as default in the <em>karma.conf.js </em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e2ff74d4c0e9f5bf2aa7e8fec90f119/href">https://medium.com/media/0e2ff74d4c0e9f5bf2aa7e8fec90f119/href</a></iframe><p>This may be different for you. Right now we don’t want to change anything in this file — but you can always come back to this file in future to take more control on your Karma 😎</p><h4>Jasmine</h4><p>As given on official Jasmine website :</p><p>“<em>Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.</em>”<br> <br> Forget about BDD — if you are not knowing what it is. Other parts of the definition must be very clear to you.</p><p>The CLI takes care of Jasmine and Karma configuration for you but you can search the web for more details about Jasmine and Karma configuration. We will discuss some of the jasmine basics &amp; Angular Testbed — after we run our first test.</p><h3>Understanding Spec file</h3><p>The tests are always written in SPEC files (.spec.ts). These will be automatically created if you use CLI commands to generate Angular components.</p><p>I am using <strong><em>tab1.page.spec.ts</em></strong> which is the spec file for Tab1 Ionic Page. Here is how it looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e3441ad7c6bb922597ecfa23d0ffa80/href">https://medium.com/media/6e3441ad7c6bb922597ecfa23d0ffa80/href</a></iframe><p>If you check the spec file there is only one test case</p><pre>it(‘should create’, () =&gt; {<br>   expect(component).toBeTruthy();<br>});</pre><p>It just checks whether the Angular component is created and hence it passes if it is truthy. Placing your spec file next to the file it tests and placing your spec files in a test folder are the two conventions to be adopted in your own projects for <em>every kind</em> of test file.</p><p>Let’s quickly jump off some of the special names used in the spec file to understand it more. We have 2 sets of jargon: Angular based and Jasmine based.</p><h4>Angular things :</h4><pre>TestBed.configureTestingModule({<br>   declarations: [Tab1Page],<br>   imports: [IonicModule.forRoot(), ExploreContainerComponentModule]<br>}).compileComponents();</pre><pre>fixture = TestBed.createComponent(Tab1Page);<br>component = fixture.componentInstance;<br>fixture.detectChanges();</pre><p><strong>TestBed</strong>: It is something like an Angular module which contains all dependencies required for testing the particular component. You can already see its similarity to <strong>ngModule</strong> with declarations and imports there. You can also learn more about Testing Ionic Applications with TestBed if you are using Angular to build your Ionic applications.</p><p><strong>Fixture</strong>: it is a wrapper that can access the HTML and TS components also.</p><p>We use a fixture to create <strong>components</strong> and <strong>services</strong> for instance.</p><p>In this example, we just create a component for Tab1Page. Pages are Angular components.</p><p><strong><em>fixture.detectChanges()</em></strong> is a line which start angular change detection Lifecycle. It can also initiate ngOnInit call as that runs on the loading of DOM.</p><h4>Jasmine things :</h4><pre>describe(&#39;Tab1Page&#39;, () =&gt; { // Test Suite</pre><pre>beforeEach(async(() =&gt; { // Setup<br>    //Angular TestBed Part</pre><pre>}));</pre><pre>it(&#39;should create&#39;, () =&gt; { // Test Case<br>   expect(component).toBeTruthy();<br>  });</pre><pre>});</pre><p><strong>describe</strong> — This is the top-level wrapper and creates something called a test suite — a test suite can have multiple tests in it. Other describe calls are nested within it which define major areas of functionality. The spec files have multiple describe calls nested inside a single describe call for hierarchical breakdown of functionality.</p><p><strong>it</strong> — the it in the file is called 1 spec — i.e. one test in the suite. It has a complete description in English about the test we are running and its expectations part in the function. It defines individual test cases.</p><p><strong>expect</strong> — this keyword is used for Jasmine expectation matching. Similar to the logical operator is programming it checks of matching things and returns true or false. ( test failed or passed)</p><p><strong>beforeEach</strong> — this part of code is to avoid code duplication and put all lines which are common for each test in a single block. So this section runs before every spec (it) part. There can multiple beforeEach defined in a TestSuite( describe)<br> <br> <strong>afterEach</strong> — this the part which runs after each test. (Not used in current code)<br> <br> beforeEach and afterEach are popularly knowns as <strong>setup</strong> and <strong>teardown</strong> code part of testing.</p><p>So now finally we can create and run unit test. Let us write our actual tests 😅</p><p>Before writing the test, for unit testing Ionic applications, I will add some functionality of our component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8a7982eaa1b28350226674491b76049/href">https://medium.com/media/d8a7982eaa1b28350226674491b76049/href</a></iframe><p>I added a simple function called addJob to the component which adds a job string to an array jobs .</p><p>We can test 2 things here :</p><p>1.jobs should be an array, we can check that by checking if length property is defined. You should not use the truthy check as it will take 0 length as a falsy value.</p><pre>it(&#39;jobs should be an array&#39;, () =&gt; {<br>    expect(component.jobs.length).toBeDefined();<br>});</pre><p>2. addJob should add the string to the jobs array. We can confirm this by checking if length of the array is greater than 0 (not a perfect test). Also by checking whether the element added now exists in thejobs array.</p><pre>it(&#39;addJob should add the job string to jobs array&#39;, () =&gt; {<br>    const job = &#39;Dummy Job&#39;;</pre><pre>component.addJob(job); // action part</pre><pre>expect(component.jobs.length).toBeGreaterThan(0);<br>    expect(component.jobs).toContain(job);</pre><pre>});</pre><p>In the above test, we have an <strong><em>action</em></strong> part, where we call actual <strong>addJob.</strong> All setup parts or variable declarations should be before <strong><em>action</em></strong> part and all <strong>expect</strong> should be after this part. Otherwise, you will not get the desired result.</p><figure><img alt="karma server" src="https://cdn-images-1.medium.com/max/1024/1*rplbJ274eOheDNMAqNhqWg.png" /></figure><p>Here is our result — all Tests passing. Look at the 3 tests in Tab1Page.</p><h4>Using the F word 🤐 : Only run specific Test cases</h4><p>To run only one or some of the specific specs you can put f in front of them so it will become fit and describe will become fdescribe. So depending on what you did on these tests OR test suites will run. Other things will be ignored. It is very useful if you have a lot of tests and you don’t want to run everything — especially during creating new tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VpDiqwHtc-nxqDu5-9HZQg.png" /><figcaption>Karma Server with only 1 test case selected using <strong>fit</strong></figcaption></figure><h4>Using the X: Ignore tests or make them Pending</h4><p>To disable some test cases you can use x in front of them this will make them xit — and they will be ignored/pending. Other specs will run as before. This is useful if you want to ignore some test cases for some reason.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRnf_lpHDyqIx12nw2x6uA.png" /><figcaption>Disable 1 Test Case using <strong>xit</strong></figcaption></figure><p>So this is just the beginning of our testing journey. In the next part of this series, we explore more useful testing techniques called <strong>Mocks</strong> and <strong>Spies </strong>🕵️</p><h3>Next Steps</h3><p>If you liked this blog, you will also find the following Ionic blogs interesting and helpful. Feel free to ask any questions in the comment section</p><ul><li>Ionic Payment Gateways — <a href="https://enappd.com/blog/ionic-4-stripe-payment-integration-with-firebase-for-apps-and-pwa/17">Stripe</a> | <a href="https://enappd.com/blog/ionic-4-paypal-payment-integration-for-apps-and-pwa/16">PayPal</a> | <a href="https://enappd.com/blog/how-to-integrate-apple-pay-in-ionic-4-apps/21">Apple Pay</a> | <a href="https://enappd.com/blog/how-to-integrate-razorpay-in-ionic-4-apps-and-pwa/20">RazorPay</a></li><li>Ionic Charts with — <a href="https://enappd.com/blog/ionic-4-charts-using-google-charts/66">Google Charts </a>| <a href="https://enappd.com/blog/adding-charts-in-ionic-4-apps-and-pwa-part-3/60">HighCharts</a> | <a href="https://enappd.com/blog/adding-charts-in-ionic-4-apps-and-pwa-part-2/54">d3.js</a> | <a href="https://enappd.com/blog/charts-in-ionic-4-apps-and-pwa-part-1/52">Chart.js</a></li><li>Ionic Social Logins — <a href="https://enappd.com/blog/facebook-login-in-ionic-4-apps-using-firebase/25">Facebook</a> | <a href="https://enappd.com/blog/google-login-in-ionic-4-apps-using-firebase/39">Google</a> | <a href="https://enappd.com/blog/twitter-login-in-ionic-4-apps-using-firebase/24">Twitter</a></li><li>Ionic Authentications — <a href="https://enappd.com/blog/email-authentication-with-firebase-in-ionic-4/38">Via Email</a> | <a href="https://enappd.com/blog/firebase-anonymous-login-in-ionic-4/37">Anonymous</a></li><li>Ionic Features — <a href="https://enappd.com/blog/using-geolocation-geocoding-and-reverse-geocoding-in-ionic-4/45">Geolocation</a> | <a href="https://enappd.com/blog/qr-code-scanning-and-optical-character-recognition-ocr-in-ionic-4/9">QR Code reader </a>| <a href="https://enappd.com/blog/best-fitness-plugins-for-ionic-4-how-to-use-pedometer/15">Pedometer</a></li><li>Media in Ionic — <a href="https://enappd.com/blog/spotify-like-music-in-ionic-4-apps/48">Audio</a> | <a href="https://enappd.com/blog/adding-video-player-in-ionic-4-app/64">Video</a> | <a href="https://enappd.com/blog/image-picker-in-ionic-4-app/67">Image Picker</a> | <a href="https://enappd.com/blog/how-to-add-image-cropper-in-ionic-4-app/68">Image Cropper</a></li><li>Ionic Essentials — <a href="https://enappd.com/blog/ionic-4-save-and-retrieve-data-locally-on-device/59">Native Storage</a> | <a href="https://enappd.com/blog/how-to-translate-in-ionic-4-globalization-internationalization-and-localization/11">Translations</a> | <a href="https://enappd.com/blog/rtl-right-to-left-use-in-ionic-4/50">RTL</a></li><li>Ionic messaging — <a href="https://enappd.com/blog/implement-ionic-4-firebase-push/34">Firebase Push</a> | <a href="https://enappd.com/blog/automatically-read-sms-in-ionic-4-apps/42">Reading SMS</a></li><li>Ionic with Firebase — <a href="https://enappd.com/blog/how-to-integrate-firebase-in-ionic-4-apps/23">Basics</a> | <a href="https://enappd.com/blog/firebase-with-ionic-4-hosting-auth-and-db-connection/58">Hosting and DB</a> | <a href="https://enappd.com/blog/firebase-cloud-functions-in-ionic-4-complete-guide/32">Cloud functions</a></li></ul><h3>Ionic React Full App with Capacitor</h3><p>If you need a base to start your next Ionic 5 React Capacitor app, you can make your next awesome app using <a href="https://store.enappd.com/product/ionic-react-full-app-capacitor/">Ionic 5 React Full App in Capacitor</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*FaAdkc0-tNS6PFh6.png" /><figcaption>Ionic 5 React Full App in Capacitor from Enappd</figcaption></figure><h3>Ionic Capacitor Full App (Angular)</h3><p>If you need a base to start your next Angular <strong>Capacitor app</strong>, you can make your next awesome app using <a href="https://store.enappd.com/product/capacitor-full-app-with-ionic-angular/">Capacitor Full App</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*SsniFXgIiFapt2oG.png" /><figcaption>Capacitor Full App with huge number of layouts and features</figcaption></figure><h3>Ionic Full App (Angular and Cordova)</h3><p>If you need a base to start your next Ionic 5 app, you can make your next awesome app using <a href="https://store.enappd.com/product/ionic-full-app">Ionic 5 Full App</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*E43NcOCjkgjChfOu.jpeg" /><figcaption>Ionic Full App in Cordova, with huge number of layouts and features</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c081bb539915" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enappd/beginners-guide-to-ionic-angular-unit-testing-part-1-c081bb539915">Beginner’s Guide to Ionic Angular Unit Testing (Part 1)</a> was originally published in <a href="https://medium.com/enappd">Enappd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Github Actions: Deploying Ionic Angular App to Firebase Hosting]]></title>
            <link>https://medium.com/enappd/github-actions-deploying-ionic-angular-app-to-firebase-hosting-790df7e9f305?source=rss-20cfddb2e89c------2</link>
            <guid isPermaLink="false">https://medium.com/p/790df7e9f305</guid>
            <category><![CDATA[firebase-hosting-example]]></category>
            <category><![CDATA[ionic-app-development]]></category>
            <category><![CDATA[ionic]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ionic-app]]></category>
            <dc:creator><![CDATA[Abhishek Rathore]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 06:29:19 GMT</pubDate>
            <atom:updated>2020-08-10T09:30:09.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhDWWjWXTXJrg3LN3BpFAg.png" /></figure><h3><strong>Github Actions</strong> is Github’s way of CI/CD</h3><p>GitHub Actions now supports CI/CD, free for public repositories.</p><p><strong>CI</strong> or <strong><em>Continuous Integration</em></strong> is a mechanism to automate the process of merging new code into an existing code base, — and to test things before doing this merge. This means as a developer you don’t have to worry about — are things still working? Use Continuous Integration to automatically build and test your code as you push it to GitHub, preventing bugs from being deployed to production. That&#39;s all about continuous integration here.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLmNwrBhejkK9EFP504%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLmNwrBhejkK9EFP504%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcGZ5Z3lrbjNuMzlodnA3ODdrb25wenp2OWNrZjlrYXpibXhua2hpYyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FLmNwrBhejkK9EFP504%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/91c2efa4198c043f3f400f216214650e/href">https://medium.com/media/91c2efa4198c043f3f400f216214650e/href</a></iframe><h3>What is Continuous Deployment?</h3><p><strong>CD</strong> <em>or</em><strong><em> Continous Deployment </em></strong>is the process of deploying automatically this code after CI is over — e.g. deploying a website on the server automatically after the relevant code changes are done. Explaining CI/CD or discussing Continuous integration vs. continuous delivery vs. continuous deployment is not the point of this article — so we will move forward with these basic sets of simple definitions. After discussing Github Actions, let us see How to deploy Angular App to Firebase Hosting?</p><h3>Building with GitHub Actions — Automate software workflows</h3><p>In this article, we will see — How to use <strong>Github Actions</strong> for automatically deploying your Angular Web app (Ionic in this case) to Firebase Hosting.</p><p>After Github Actions, let us now move on to how to deploy Angular App to Firebase Hosting.</p><p>We also assume that you are testing your application via the automated unit tests — So we have added some part related to setting up those tests in the Github environment. However you are free to skip that step — it not at all required.</p><h3>Preparation 🧑‍🍳</h3><p>So let’s start with first knowing the application which we are going to deploy. I have a simple <a href="https://store.enappd.com/product/ionic-grocery-app-and-admin-dashboard/">Grocery Dashboard made in the Ionic 5 framework</a>. This <a href="https://store.enappd.com/product/ionic-grocery-app-and-admin-dashboard/">app</a> is available on <a href="https://enappd.com/">Enappd.com</a></p><figure><img alt="Grocery Dashboard in Ionic 5 ( Enappd.com)" src="https://cdn-images-1.medium.com/max/1024/1*KQJ0LBnF3GocSVfWNeOaoA.png" /><figcaption>Grocery Dashboard in Ionic 5(Enappd.com)</figcaption></figure><p>Note: We have already set up a firebase hosting environment. To get this setup done you can learn more about <a href="https://enappd.com/blog/firebase-with-ionic-4-hosting-auth-and-db-connection/58/">How to set up firebase hosting and environment to deploy</a></p><h3>Setup Github Actions — Configuring a workflow :</h3><p>The following are the steps to add a workflow file.</p><h4>Step 1: Create Directory Structure</h4><p>Create a directory .github in your root folder and put another directory workflows inside this. In workflows directory, we will make some YAML files. the extension to make a YAML file is .yml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*eRlWiRV_Fq-gUpDNP-Kv4w.png" /><figcaption>Add .github/workflows directory and create a YAML file</figcaption></figure><h4>Step 2: Write the Basic Config in Workflow file</h4><p>Create a YAML file of any name — main.yml (In our case “main.yml” here). This YAML file will often be called the workflow file. As one file contains one workflow. You can create more files in this directory for more workflows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d578994bcfaafd3405f2ebe5c68ac4fd/href">https://medium.com/media/d578994bcfaafd3405f2ebe5c68ac4fd/href</a></iframe><p>Let’s understand each part one by one.</p><p>There are two main sections of a workflow file ( main.yml )</p><ol><li><strong>Trigger</strong>: Trigger tells about the action (git related actions — push, merge, etc.) on which GitHub automated workflow will start. For example, it is push in the above example but it can be any other git related action like merge. Also, we have mentioned that this workflow will only be triggered with a push on the branch refactor. This way you can restrict the workflows to only certain branches that are related to deployment branches and not on every push done during the development phase.</li><li><strong>Jobs</strong>: This part contains a list of jobs that will be triggered. In our case, we have given it a name Build and Deploy . name as you can notice appears everywhere in the workflow file— they will be shown while your CI system will run. Every job has some steps — which are like commands to be executed sequentially. Here in the above file, we have many steps and each step is marked with some name and some command inrun. As jobs will need a working environment (Operating System) we have put a runs-on part in at the start of the job with a value for the Ubuntu environment — you can change the environment according to your requirements. For most generic requirements Ubuntu seems to be an easy pick.</li></ol><h4>Step 3: Configuring the steps</h4><figure><img alt="Github Marketplace for Actions" src="https://cdn-images-1.medium.com/max/1024/1*gBwDW5x3cF-NZOGybSQINg.png" /><figcaption>Github Marketplace for Actions</figcaption></figure><ol><li><strong>Checkout Repo — </strong>this is a step to checkout (git checkout) your latest code from the branch you mentioned in the above settings. You can see that there is a uses key which essentially means we are using pre-built<strong> GitHub Actions </strong>(Scripts). These workflow actions are written by the community and are very helpful to do complex actions. If you don’t know much about shell scripts and automation scripts — these are life saviors for you. You can check the <a href="https://github.com/marketplace?type=actions">whole list of such actions</a></li><li><strong>Install Dependencies </strong>— This step is quite simple — Doing an npm install, as we are using an <strong>npm</strong> based project.</li><li><strong>Build </strong>— In this step we are running npm run build which is used to create a build for our web applications.</li><li><strong>Run Tests — </strong>In this step, we are using the command to test our code. Interesting to note, it will not run tests properly as well as on our local desktop. As in this CI environment, we don’t have the Chrome browser UI to be launched — however, we will make some adjustments to run the code. We will see that part later.</li><li><strong>Deploy to Firebase — </strong>Again we use an external Github Action here named firebase actions . This action will do a lot of complex stuff to make the Firebase CLI available in our CI environment — and we don’t have to install the firebase environment manually on the CI system. If you are confused about what is @ doing after these actions — it is just the version or branch of that action. In the args we will pass the command we use for hosting i.e.firebase deploy --only hosting In this case firebase is not required to be put in this action and you can use the remaining part of the command deploy --only hosting . Finally, to connect your firebase with your account you will need to login to firebase — but you can’t log in simply as this is an automated environment. So how to authenticate?</li></ol><h4>Step 4: Get Token from Firebase 🔥</h4><p>You can go to your system and type the command.</p><p>firebase login:ci</p><figure><img alt="firebase login:ci command to create firebase login token" src="https://cdn-images-1.medium.com/max/750/1*TevouW9IM3fW9j9xcu8b4w.png" /><figcaption>firebase login: ci command to create firebase login token</figcaption></figure><p>Then you can choose the google account from which you are using the firebase account to deploy. In the end, you will be presented with a long token string that you can use for the value of FIREBASE_TOKEN key in the last step. BEWARE: it is not a good practice to put a token available directly and can be a security concern. However, we will use this token right now to test. Later we can use Github Secret Store to hide this secret token from code view.</p><h3>Let’s Go Live now 🤞</h3><p>Now we are ready with all the script work. We can push the latest changes on the Github and it should work — at least we hope so</p><figure><img alt="Github Actions Tab" src="https://cdn-images-1.medium.com/max/1023/1*SPPsSvn1RiUWYjYeK_i0yg.png" /><figcaption>Github Actions Tab: Failed Build</figcaption></figure><p><strong><em>uh oh! </em></strong>😞</p><p>Let us see what might have happened if you see ❌ <strong>Build</strong> .</p><p>We have not tested our code on the localhost — so we are facing some issues here. You should run all these steps beforehand on the local system. Because there is no way CI will magically deploy the code — unless everything is working fine.</p><p>After some fixes in our code, we are ready to go again.</p><p>This time build works but our tests ( <em>Run Tests </em>) are stuck for a long time.🐌 🐌</p><figure><img alt="Run Tests Step is Stuck" src="https://cdn-images-1.medium.com/max/991/1*xrrgDghF4DhLKR4IwsMFIw.png" /><figcaption>Run Tests Step is Stuck</figcaption></figure><p><strong>REASON</strong>: We are not having Chrome on this CI Server and we can’t run a UI based browser here, so we need to make a small adjustment to our code</p><pre>&quot;scripts&quot;: {<br>   &quot;ng&quot;: &quot;ng&quot;,<br>   &quot;start&quot;: &quot;ng serve&quot;,<br>   &quot;build&quot;: &quot;ng build&quot;,<br>   &quot;test&quot;: &quot;ng test --watch false --browsers ChromeHeadless&quot;,<br>   &quot;lint&quot;: &quot;ng lint&quot;,<br>   &quot;e2e&quot;: &quot;ng e2e&quot;<br>}</pre><p>We have changed test script to work with <strong>ChromeHeadless </strong>which is already installed with karma launcher. Also, we made watch false — so that test end after a single run. Otherwise, your tests will be running forever — Caution: Beware of such a mistake on CI as you may lose some free hours of <strong>Github</strong> <strong>Actions</strong>.</p><p>Now finally let’s run it again by pushing these changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTom11m4hG0U3ES2D3gM8g.png" /><figcaption>Github Action: shows all success</figcaption></figure><p><strong>YES !!</strong> My code works now. 🕺 💃.</p><p>Finally, you can refresh your firebase web app and you will find the new changes.</p><h4>Github Secret Store 🤫</h4><p>If you have come this far you can now move your secrets to Github Secret Store, which is under the <strong>SETTINGS</strong> tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWsVedZbMkg0u1bMCvx_3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cb0w86fxCLPIXv431J9Png.png" /></figure><p>Now you can update your YML file and put Token as</p><pre>FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}</pre><p>And everything runs fine !! 🏃‍♀️</p><p>Here is the final workflow file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d974a8c625423e5d82479fa38c2c3e7/href">https://medium.com/media/9d974a8c625423e5d82479fa38c2c3e7/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=790df7e9f305" width="1" height="1" alt=""><hr><p><a href="https://medium.com/enappd/github-actions-deploying-ionic-angular-app-to-firebase-hosting-790df7e9f305">Github Actions: Deploying Ionic Angular App to Firebase Hosting</a> was originally published in <a href="https://medium.com/enappd">Enappd</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slack Bot for Cricket Scores with Node.js]]></title>
            <link>https://medium.com/@rathore/slack-bot-for-cricket-scores-with-node-js-2c1759d462e?source=rss-20cfddb2e89c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c1759d462e</guid>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[slackbot]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abhishek Rathore]]></dc:creator>
            <pubDate>Sun, 10 Nov 2019 05:19:26 GMT</pubDate>
            <atom:updated>2019-11-10T05:42:40.306Z</atom:updated>
            <content:encoded><![CDATA[<h3>Slack Bot for Cricket Scores with Node.js/Express and Heroku</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEYJ6N8dR4x5QvbNEJGymg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/mohamed_hassan-5229782/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=4071274">Mohamed Hassan</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=4071274">Pixabay</a></figcaption></figure><p><em>Slack is a popular communication platform for every workplace today. Its simple and intuitive interface and loads of functionalities have made it popular and productive for day to day users.<br></em><a href="https://api.slack.com/"><em>Slack Platform</em></a><em> has made it possible to make lots of custom integrations with Slack. Many chatbots, app integrations (Github, Trello, Jira, Asana, etc.) are already available on the </em><a href="https://slack.com/apps"><em>Slack App marketplace</em></a><em>.</em></p><p>In this blog, we will use Slack Platform APIs to make a simple chatbot that tells us about the score of ongoing or recent cricket matches. This chatbot will use a cricket API that is publicly available for limited use.</p><p>Let’s start with the steps to create your first chatbot:</p><ol><li><strong>Get Started with Slack Workspace.</strong></li></ol><p>Skip this step if you are already logged in to your workspace.</p><p>First, sign in to Slack and <a href="https://slack.com/create">create a workspace</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*ehHalIV7zj5cUe-1vab55A.png" /><figcaption>Create a New Workspace using your email ID.</figcaption></figure><p><strong>2. Create a Slack App</strong></p><p><a href="https://api.slack.com/apps">Create an App</a> in your Slack developer console and Add it to your workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*z7bUWbKFWU2CRiYBrURQVQ.png" /></figure><p><strong>3. Create a Bot user</strong></p><p>Go to the <strong>Bot Users</strong> menu option and click on <strong>Add a Bot User </strong>on the next screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*3asVsBq1mGou3XsmltZ0zw.png" /><figcaption>Adding a new Bot User</figcaption></figure><p>It will have the default name of your Slack App, however, you can change the display name before saving it. This name will be displayed in your slack workspace. Also, enable “<strong>Always show my bot online</strong>” option to see your bot always online. You can also customize the bot pictures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*Vl2hp5-R8uvj2E_AnTRqpA.png" /><figcaption>Changing the Display name of Bot User</figcaption></figure><p><strong>4. Authorizations and Installation of Bot</strong></p><p>For getting Access token you need to install the app in your workspace. You can go and install bot in your workspace. Go to Setting &gt; Install App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*cu1h3YKyhcc-KY1nBCSycQ.png" /><figcaption>Install App to your Workplace</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*WDkx2NDhRGBQXoiWOmTLng.png" /><figcaption>Allow the app to access your workplace</figcaption></figure><p>Once you install the App you will also find Bot User OAuth Access Token. This token will be required when your server will make a Request to the Slack server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*tLAOGafQLHIEz5hn6UWe2A.png" /><figcaption><strong>Bot User OAuth Access Token </strong>will be used later</figcaption></figure><p><strong>5. Check for completed actions</strong></p><p>Got to Basic Information menu — You will find under <strong>Add features and functionality </strong>you can find some features which are not enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*6SxS_UIwMOYh3YKLunDcyQ.png" /><figcaption>Bots and Permissions already enabled</figcaption></figure><p>Next, we need to work on Event Subscriptions which provides basic event triggers which bot can receive. Also, you will need an API endpoint that can request Slack Server and receive the responses.</p><p><strong>6. Event Subscriptions and Building the API endpoint</strong></p><p>In the Event Subscription menu page, first, you need to enable events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*z9tC9FYLqb5PfRnwiSdHIA.png" /></figure><p>After the above step, you will see a <strong>Request URL </strong>field. Here you need to put an <strong>API endpoint</strong> to your server. I have used Node with Express for this purpose, but you can use anything). You have to deploy the server on some publicly available cloud(in this example we chose <strong>Heroku Cloud</strong>)</p><p>In the below screen we have put the URL but it doesn’t return the challenge in response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*6EAaWXxFoFzwD2WtcwwBsw.png" /><figcaption>Un-verified request URL</figcaption></figure><p>API endpoint should have the following specifications :</p><ol><li>It should accept <strong>POST</strong> request on the provided path and get the data in the <strong>request</strong> body (like <strong>req.body</strong> in ExpressJS).</li></ol><p>You will receive similar data in the request body when the URL is un-verified :</p><pre>{<br>    &quot;token&quot;: &quot;Jhj5dZrVaK7ZwHHjRyZWjbDl&quot;,<br>    &quot;challenge&quot;: &quot;3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P&quot;,<br>    &quot;type&quot;: &quot;url_verification&quot;<br>}</pre><p>2. For the step of verification, your <strong>API endpoint </strong>should respond with the challenge token back to the Slack server. The following format of response will be needed :</p><pre>{<br>     &quot;challenge&quot;: &quot;3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*ozmumglNRfeoBH1FX_vpxw.png" /><figcaption>Verified Request URL</figcaption></figure><p>3. After verification of the request URL, you can change your API endpoint functionality according to your needs. As we will respond to some bot events and messages to a bot we will enable bot events in the next section.</p><p><strong>7. Enabling Bot Events</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*7Hguab-OQRzFDDwReJ59Ng.png" /><figcaption>Enable direct message trigger to bot</figcaption></figure><p>In the <strong>Event Subscription</strong> page, you can go to <strong>Subscribe to bot events </strong>section. Here you can enable some events which bot will listen to: like the direct message or @ mentions. Save the change before moving away from the page.</p><p>8. <strong>Creating API endpoints</strong></p><p>After the verification step you need to modify your endpoint to perform certain tasks :</p><ol><li>Get the event object from bot events and parse the necessary information :</li></ol><pre>{<br>   &quot;token&quot;: &quot;8XcnrlP6KUm4eJsVsPjesESO&quot;,<br>   &quot;team_id&quot;: &quot;T0MGWJM1A&quot;,<br>   &quot;api_app_id&quot;: &quot;AKZKU7Q21&quot;,<br>   &quot;event&quot;: {<br>      &quot;client_msg_id&quot;: &quot;ddcc9994-c5a9-47f6-a8bf-edea0369b529&quot;,<br>      &quot;type&quot;: &quot;message&quot;,<br>      &quot;text&quot;: &quot;hi man&quot;,<br>      &quot;user&quot;: &quot;U0MH2F7AN&quot;,<br>      &quot;ts&quot;: &quot;1561743178.000900&quot;,<br>      &quot;team&quot;: &quot;T0MGWJM1A&quot;,<br>      &quot;channel&quot;: &quot;DKZNBQKUM&quot;,<br>      &quot;event_ts&quot;: &quot;1561743178.000900&quot;,<br>      &quot;channel_type&quot;: &quot;im&quot;<br>   },<br>   &quot;type&quot;: &quot;event_callback&quot;,<br>   &quot;event_id&quot;: &quot;EvKNASE71R&quot;,<br>   &quot;event_time&quot;: 1561743178,<br>   &quot;authed_users&quot;: [<br>      &quot;UKZ851QLU&quot;<br>   ]<br>}</pre><p>The above object is received by the <strong>Request URL</strong> when you send a direct message to the bot. You can extract some information from this :</p><p>a) <strong>Text Message</strong>: ‘hi man’. You can match this text with your logic and respond accordingly. In our code, I am looking for a ‘<strong>score</strong>’ keyword to provide a list of matches to the Slack channel.</p><p>b) <strong>Channel: ‘</strong>DKZNBQKUM’. This is channel Id which is useful for reply target.</p><p>You will send a response of 200 (OK) to the above request. You don’ have to send any response data in this request call.</p><p>2. Now once you get the relevant data from bot event, you should call the Cricket API Endpoint and get relevant data. I have used <strong>cricapi.com/api </strong>for my code. You can signup and explore the API. If you want to make a simple chatbot, skip this step and just reply with some dummy messages in the next step.</p><p>3. After getting all data, you can call Slack Endpoint <a href="https://slack.com/api/chat.postMessage">https://slack.com/api/chat.postMessage</a></p><pre>POST https://slack.com/api/chat.postMessage<br>Content-type: application/json<br>Authorization: Bearer SLACK_BOT_TOKEN<br>{<br>    &quot;text&quot;: &quot;Hello! Knock, knock.&quot;,<br>    &quot;channel&quot;: &quot;CBR2V3XEX&quot;<br>}</pre><p>You must have the Authorization token, which is your <strong>Bot User OAuth Access Token . </strong>Also, send the <strong>text data</strong> and <strong>channel ID </strong>which you extracted above. This text will appear on the user chat screen.</p><p>9. <strong>Checking you bot</strong></p><p>First, we will try to Direct message the bot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*SJw-syC1PId_9fCQNTtWUQ.png" /></figure><p>Here I am messaging some sentences in which ‘<strong>score</strong>’ word comes up. As my code matches any occurrence of this word, it will trigger the API endpoint to get a list of all cricket matches going on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*NZI39gatbvKAd74uqG6swA.png" /><figcaption>Score keyword is checked</figcaption></figure><p>If the bot is not responding, you should recheck your server for code errors, also check whether you have provided the latest <strong>Bot User OAuth Access Token</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*gTnKcSVT6q3lVUuhM14RBw.png" /><figcaption>List of Matches</figcaption></figure><p>After getting the list of matches, one has to pass the ‘Match &lt;number&gt;’ kind of sequence to get the score of a particular match. The bot will reply with the score of the match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*pydp2ryxdsNwdvheMhO5Fg.png" /><figcaption>Chatbot replying to our messages</figcaption></figure><p><strong>Useful resources :</strong></p><ol><li>Code Repository for this bot: <a href="https://github.com/abhishekrathore/SlackBot">https://github.com/abhishekrathore/SlackBot</a></li><li>Heroku deployment for NodeJS: <a href="https://devcenter.heroku.com/articles/getting-started-with-nodejs">https://devcenter.heroku.com/articles/getting-started-with-nodejs</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c1759d462e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Object methods every developer should know]]></title>
            <link>https://medium.com/stemoto/javascript-object-methods-every-developer-should-know-c68c132a658?source=rss-20cfddb2e89c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c68c132a658</guid>
            <category><![CDATA[constructor]]></category>
            <category><![CDATA[shallow-copy]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[deep-copy]]></category>
            <dc:creator><![CDATA[Abhishek Rathore]]></dc:creator>
            <pubDate>Thu, 26 Jul 2018 05:09:31 GMT</pubDate>
            <atom:updated>2018-07-26T05:09:31.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMtGnYGs_1rEPHeOzUiZJw.jpeg" /></figure><p>Javascript Object is quite special and it doesn’t follow the classical object-oriented concepts used by other languages like Java. JS objects have the prototypical inheritance which is quite different from normal class-based inheritance. We will not explain inheritance as part of this article and will focus on some common methods which are available in JavaScript’s global <strong>Object </strong>constructor. Even though there are many other methods available in <strong>Object constructor, </strong>we will restrict our discussion to very frequently used ones.<br> <br> Here is the list of topics we will discuss in this article :</p><ul><li><strong>Shallow copy — Object.assign()</strong></li><li><strong>Deep copy — JSON.parse() &amp; JSON.stringify()</strong></li><li><strong>Object.create()</strong></li><li><strong>Object.entries()</strong></li><li><strong>Object.keys()</strong></li><li><strong>Object.values()</strong></li><li><strong>Object.freeze()</strong></li></ul><p>Before we start, lets check out a typical object initialization in JS. We have some more ways to initialize a JS object - but this is the most common way developers use :</p><pre>let obj = {};<br>obj.name = “messi”;<br>obj.year= 2018;<br>obj.speak = function(){<br> return “My Name is “+this.name+” and this is year “+this.year;<br>}</pre><p>Here you can see the <strong><em>name</em></strong>, <strong><em>year</em></strong> and <strong><em>speak</em></strong> properties. In JS methods are also properties with type function.</p><p>In the next section, we will discuss copying an object properly in JS.</p><h3>Copying an Object</h3><p>You can’t use the typical assignment operation to copy an object in JS as that will only lead to creating a reference to the same object.</p><pre>let newObj = obj;<br>obj.year = 2019;<br>console.log(newObj.year) </pre><pre>// 2019</pre><pre>console.log(newObj.speak()) </pre><pre>// My Name is messi and this is year 2019</pre><p>Above example shows that <strong><em>newObj</em></strong> is just a reference to <strong><em>obj</em></strong> and whenever any property changes in either of them — both objects are affected.</p><h4>Shallow Copy</h4><p>You can create a shallow copy i.e. a top level properties copy, using <strong>Objects.assign()</strong> method</p><pre>let copyObject = Object.assign({},newObj);<br>copyObject.name = &quot;ronaldo&quot;;<br>console.log(copyObject.speak());</pre><pre>// My Name is ronaldo and this is year 2019</pre><pre>console.log(newObj.speak());</pre><pre>// My Name is messi and this is year 2019</pre><p>This example is copying <strong><em>newObj</em></strong> and all its properties to <strong><em>copyObject</em></strong>. You can check out that speak method will only print the new name on <strong><em>copyObject</em></strong><br>However, this methods fails when we have nested objects in property values. Those objects are still not copied and work as shared reference in both objects.<br>Look at this example</p><pre>let sourceObject = {name:&quot;neymar&quot;,country:{name:&quot;brazil&quot;}}<br>let shallowCopyObj = Object.assign({},sourceObject);<br>shallowCopyObj.country.name = &quot;India&quot;;<br>console.log(sourceObject); </pre><pre>//{ name: &#39;neymar&#39;, country: { name: &#39;India&#39; } }</pre><p>You can check that <strong><em>sourceObject</em></strong> has <strong><em>country</em></strong> property as value object with <strong><em>name</em></strong> property that remains shared between the new <strong><em>shallowCopyObj</em></strong> and <strong><em>sourceObj</em></strong>. So how can we create a deep copy - the answer is not that simple if you are looking for true deep copy. We will give a small workaround in next section but that is only applicable for certain conditions(just search on google as we can have a complete article describing on how to have a deep copy)</p><h4>Deep Copy</h4><p>If you just need to copy only properties which are not functions — there is an efficient method. We are moving away from <strong>Object</strong> constructor here and using another global Object in JS — <strong>JSON</strong></p><pre>let deepCopyObj = JSON.parse(JSON.stringify(obj));<br>console.log(deepCopyObj);</pre><pre>//{ name: &#39;messi&#39;, year: 2019 }</pre><p>You can check in output that we have lost our function property while copying — but this will be true deep copy. Let’s end our discussion on copying values and move to some more useful functions in <strong>Object </strong>constructor.</p><h3>Object.create()</h3><p>You can also create object with <strong>Object.create(</strong>) function this has additional flexibility that you can choose what will be prototype of your new object.</p><pre>let createObj = Object.create(obj);<br>console.log(createObj);  //{}<br>createObj.name = “Pk”;<br>console.log(createObj.speak());</pre><pre>// My Name is Pk and this is year 2019</pre><p>In this example <strong><em>obj</em></strong> is the prototype from which <strong><em>createdObj</em></strong> is created. Which means it can use properties of prototype due to inheritance. That’s why we can use <strong><em>speak()</em></strong> method without declaring that in <strong><em>createdObj</em></strong>.</p><h3>Object.entries()</h3><p>This is a simple function which converts JS objects to an array of arrays. With inner array is pair of key and value of the object. Let’s checkout a self-explanatory example</p><pre>let person = {name:”Roger”,age:30}<br>let entries = Object.entries(person);<br>console.log(entries);</pre><pre>//[ [ &#39;name&#39;, &#39;Roger&#39; ], [ &#39;age&#39;, 30 ] ]</pre><h3>Object.keys()</h3><p>This function picks only keys (or property labels) of objects and returns an array</p><pre>let keys = Object.keys(person);<br>console.log(keys);</pre><pre>// [ &#39;name&#39;, &#39;age&#39; ]</pre><h3>Object.values()</h3><p>This function picks only values of objects and returns an array</p><pre>let values = Object.values(person);<br>console.log(values);</pre><pre>// [ &#39;Roger&#39;, 30 ]</pre><h3><strong>Object.freeze()</strong></h3><p>This function freezes the object for any further changes (key or values). It may not throw any error (unless you are in <strong><em>strict mode</em></strong>) but there will be no effect of value change on your object.</p><pre>let frozenObject = Object.freeze(person);<br>frozenObject.name = “Nadal”;<br>console.log(frozenObject);</pre><pre>//{ name: &#39;Roger&#39;, age: 30 }</pre><p>That’s it for this small article — these are quite simple but important part of a beginner’s journey to Javascript. Properly using copying and creation methods can avoid many potential bugs in Javascript applications.</p><p>If you want to deep dive into all methods available in JS <strong>Object constructor </strong>check out <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">MDN Docs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c68c132a658" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stemoto/javascript-object-methods-every-developer-should-know-c68c132a658">Javascript Object methods every developer should know</a> was originally published in <a href="https://medium.com/stemoto">Stemoto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Node.js Backend without any server — Just Code using Webtask.io]]></title>
            <link>https://medium.com/stemoto/a-node-js-backend-without-any-server-just-code-using-webtask-io-555c7919b51f?source=rss-20cfddb2e89c------2</link>
            <guid isPermaLink="false">https://medium.com/p/555c7919b51f</guid>
            <category><![CDATA[webtask]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Abhishek Rathore]]></dc:creator>
            <pubDate>Sun, 22 Jul 2018 06:35:57 GMT</pubDate>
            <atom:updated>2018-07-22T06:35:57.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXhg6hsyx38c5LEN8Was8w.png" /><figcaption>webtask.io is a simple platform for low scale backend service</figcaption></figure><blockquote>Whenever, we talk about backend it is scary dark world — with no colors and things are terminal.</blockquote><p>However, with platforms like firebase, it has become easier to make a backend. But, every backend comes with their SDK and style of coding/querying/APIs — which means there is a learning curve involved. It would be great if we can have an online IDE where we can run any of our NodeJS files and immediately get the backend working through APIs. We are trying the same thing on <a href="http://webtask.io/">Webtask.io</a> — it is an online IDE cum platform which will instantly deploy your code and give REST API over their domains. If you have a quick task of Node based backend and don’t want to dig into Linux cloud deployments — continue reading.</p><h3>Initial Setup</h3><p>After initial signup to <a href="http://webtask.io/">WebTask.io</a> you will get into their IDE — you can start via creating a new Web Task from a template. I chose ‘express with mongodb’. Check out the screens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*ul1P4tBZtHXRs3azSy5A0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*huWKBOb6CLA63E5GiLwuyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4JXVG6kyHZX_OWey8ZyiQ.png" /></figure><p>You will also have to find an online hosted MongoDB service — MLab is a perfect source for that. Sign up on MLab and get you hosted MongoDB URL.</p><p>If you don’t know about MLab, it is an online MongoDB which you can access via mongoldb URL like</p><pre>mongodb://&lt;dbuser&gt;:&lt;dbpassword&gt;@ds147451.mlab.com:47451/youstart</pre><p>Database user and password given in above URL will be made after making a new database on MLab. You can checkout MLab documentation for all this. You must choose sandbox free tier for having a free account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67-3p23e4nGSPnaMamN7xg.png" /><figcaption>A MLab Deployed Database</figcaption></figure><h4><strong>Word of Caution</strong></h4><p>Now comes the funny part — templates are outdated. Yes, I was using MongoDB 3 native driver (which you can check out in their NPM module section) but default connection code was given for MongoDB 2. This led to many errors while I was connecting to <a href="https://mlab.com/">MLab</a> Cloud MongoDB Database. This problem is solved in the next section.</p><h3>Updating Environment Variables/ Secrets</h3><p>You might be familiar with how node use environment variables (process.env) to keep secrets. However, WebTask has a section to keep secrets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFpyFH-hv-RMlzxjrjIONQ.png" /><figcaption>Secrets option is under the Wrench Icon Toolbar</figcaption></figure><p>You have to update in secrets — MONGO_URL. There can be many things which can go wrong with this URL config — Be Careful !! You will have to create a database and then a user for that database in MLab before jumping to this stage.<br> <br> As of MongoDB native driver 3+ you can’t have MONGO_URL as :</p><pre>mongodb://&lt;dbuser&gt;:&lt;dbpassword&gt;@ds147451.mlab.com:47451/youstart</pre><p>Instead use the one given below ( checkout that we removed database name ‘youstart’ and added a section after ? )</p><pre>mongodb://&lt;dbuser&gt;:&lt;dbpassword&gt;@ds147451.mlab.com:47451/?authSource=yourDB&amp;w=1</pre><p>`yourDB` should be replaced by your database name in MLab — else authentication will fail.<br> <br> Also if you look at later URL you will see database name is removed — database name is now given in javascript code.</p><pre>var db = client.db(‘youstart’); // Here youstart is the name of my database in MLab</pre><p>I have edited the code of template to make it work, you can use the following code here — only one change needed is name of your database.</p><h3>Complete Code (edited version of template)</h3><pre>‘use latest’;<br>import bodyParser from ‘body-parser’;<br>import express from ‘express’;<br>import Webtask from ‘webtask-tools’;<br>import { MongoClient } from ‘mongodb’;<br>import { ObjectID } from ‘mongodb’;</pre><pre>const collection = ‘my-collection’;<br>const server = express();</pre><pre>server.use(bodyParser.json());<br>server.get(‘/:_id’, (req, res, next) =&gt; {<br> const { MONGO_URL } = req.webtaskContext.secrets;<br> MongoClient.connect(MONGO_URL, (err, client) =&gt; {<br> const { _id } = req.params ;<br> if (err) return next(err);<br> var db = client.db(‘youstart’); //CHANGE THIS</pre><pre>db.collection(collection).findOne({ _id: new ObjectID(_id) }, (err, result) =&gt; {<br> if (err) return next(err);<br> res.status(200).send(result);<br> });<br> });<br>});<br>server.post(‘/’, (req, res, next) =&gt; {<br> const { MONGO_URL } = req.webtaskContext.secrets;<br> // Do data sanitation here.<br> const model = req.body;<br> console.log(MONGO_URL);<br> MongoClient.connect(MONGO_URL, (err, client) =&gt; {<br> if (err) return next(err);<br> var db = client.db(‘youstart’);  //CHANGE THIS</pre><pre>db.collection(collection).insertOne(model, (err, result) =&gt; {<br> if (err) return next(err);<br> res.status(201).send(result);<br> });<br> });<br>});<br>module.exports = Webtask.fromExpress(server);</pre><h3>Use Runner to Test API</h3><p>Click on the run button which will open an API test panel.</p><p>There are already 1 POST and 1 GET API endpoints implemented in the above code. You can first test the POST API to create some data on MLab database</p><pre>POST /                  (with the body containing JSON data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*7xoggwgUwEyseTMki7IiZg.png" /></figure><p>Check out result in MLab — you can check that some document will be created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2X2hXp0MRutnwBP4cYAew.png" /><figcaption>Document created by POST API</figcaption></figure><p>Now you can test GET API</p><pre>GET /:id  (where you can replace :id which Mongod Document ID) </pre><pre>GET /5b532801161da900067f68a1</pre><p>You will get the expected result in the Runner section.</p><p>Now we will check out our deployed backend server. Server URL is at bottom of IDE and you can start using it instantly.</p><pre> <a href="https://wt-06fb0e1f9b5c229c733b079d74404815-0.sandbox.auth0-extend.com/express-with-mongo-db/5b532801161da900067f68a1">https://wt-06fb0e1f9b5c229c733b079d74404815-0.sandbox.auth0-extend.com/express-with-mongo-db/5b532801161da900067f68a1</a><br> </pre><p>Tada !! Server-less Backend is ready !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=555c7919b51f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stemoto/a-node-js-backend-without-any-server-just-code-using-webtask-io-555c7919b51f">A Node.js Backend without any server — Just Code using Webtask.io</a> was originally published in <a href="https://medium.com/stemoto">Stemoto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Interactive session with Harsh Bhardwaj at Youstart : How to land great Jobs.]]></title>
            <link>https://medium.com/stemoto/https-medium-com-rathore-session-by-harsh-bhardwaj-youstart-summer-internship-jaipur-fullstack-1f7ae4ef9c48?source=rss-20cfddb2e89c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f7ae4ef9c48</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Abhishek Rathore]]></dc:creator>
            <pubDate>Sun, 17 Jun 2018 10:25:41 GMT</pubDate>
            <atom:updated>2018-06-17T10:25:41.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4hNvwg2I2IQ7nM_N0x8Nw.jpeg" /><figcaption>Harsh Bhardwaj, Interacting with Students at Youstart — Fullstack Summer Bootcamp 2018</figcaption></figure><p>As a part of on-going tradition of interactions with past Alumni and Industry mentors, we organized a session with Harsh Bhardwaj on 5th June 2018, as part of Summer Training and Internship Program. Harsh works at PTC, which is known for its Internet of things (IoT) and augmented reality (AR) platform for partners and developers. <a href="https://www.ptc.com/">PTC</a> has six core product families: Creo, Windchill, Mathcad, Integrity, Servigistics, and ThingWorx.</p><p>Harsh has taken out some time from his busy schedule during his visit to Jaipur. Harsh has been a part of the Youstart family and always helped young coders to learn and work on new technologies by being an active volunteer at college club. He is continuing the same role via these activities — even after joining the Industry. Most of the session was Q &amp; A, which went over an hour to discuss various topics related to students life and career. Here are the key elements :</p><p><strong>How was your interview experience at PTC and other companies?</strong></p><p>Most of the interviewers asked about some problem to check your problem-solving attitude and not syntax and semantics. If they have given a problem then you have to provide an efficient approach to solve it — and keep optimizing it over the discussion. They want to see how you think about a problem in a real-life situation. They want to analyze your thought process, as you will be working with them on day-to-day work. I am talking about interviews of good companies; a mass recruiter might not be interested in providing so much time to each candidate.<br>Most of my interviews went for more than 1 or 2 hours in which we discussed a single problem at hand. Most good companies allow you to think on pen &amp; paper or a whiteboard. They don’t want your code — as the code is an obvious thing which anyone can write.</p><p><strong>How was life after college?</strong></p><p>Life in college was a bit of struggle for me — it was enjoyable but hard. You have to go through many courses and exams. In between, you want to work on good internships too. But, it is hard to get a good internship, especially in a non-IT city like Jaipur.<br>I remember a boy with an injured leg and traveling almost 20KM to complete internship works. It was me!<br>But I wanted to do that, it was not a burden for me. I worked on many internships in which I was not paid any stipend — but all was the experience.<br>Life after joining PTC has been fun. I work on real-life problems with like-minded people. I get some extra money to spend than in my college days. I can work on exciting new things.</p><blockquote>I remember a boy with an injured leg and traveling almost 20KM to complete internship works. It was me!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SySG-We_LcfZ1NQtIP_Enw.jpeg" /></figure><p><strong>What is the role of training/internship in engineering?</strong></p><p>You need not do any training if you can learn these things on your own — the internet is a big resource for learning new things. If you need guidance approach a good mentor — who has industry skills and has worked in the relevant industry. There are a lot of coachings but most of them are focused on certificates, not on learning real industry practices. I think training or internship should be done where you are actually working in an industry environment under the guidance of people who know how the industry works.<br>I didn’t have many certificates when I was sitting for placements. Even though I had completed many training and internships but I was not interested in collecting those certificates. I was rather interested in working and get some new skills.<br>I remember a guy sitting beside me during placement time having a lot of certificates but did not have any knowledge of current technologies. I was selected after that interview, based on my knowledge and skills — he wasn’t.</p><blockquote>Certificates with no knowledge are of no value.</blockquote><p><strong>How did you start with coding and other things?</strong></p><p>I worked on many internships — as I said many of them did not pay anything. I was not working for certificates or stipend but for the experience.<br>I think all of it was used somewhere in my journey — you can’t say exactly where it will be useful but somewhere it will be.<br>I attended node.js Summer Bootcamp at <a href="https://youstartlabs.in/">Youstart</a> and that came to use in one of the rounds in PTC interview. Also, my current profile and work of full stack developer started recently — there we had to learn these frameworks quickly and I am finding it familiar as I have already learned Nodejs here. So you never know when it will be useful — but real knowledge never goes away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlakFP4UarnQIJW909Qw5Q.jpeg" /></figure><p><strong>Is it worth going to software development field, nowadays?</strong></p><p>Yes, it is a quite exciting field. You can create new products. You can work on new ideas. You can create things which people use. You get to work with people who are helpful, friendly and have similar visions as you. Finding such an environment is difficult in any practical sector. The software industry is still the top choice of making a career. Also, it is flexible — you can work from anywhere — you get work from home. you don’t need big machinery. Everything you need is your system and will to work on given problem.</p><p><strong>One should do master’s or go to software development company? Which is better?</strong></p><p>It completely depends on your interest If you are interested in academics or research then go for further studies i.e. Master’s degree.<br>If you want a big job master’s degree may be helpful for that too but it is not worth to spend 2 years to join master’s degree and then work in software development after that. <br>Now you can apply to any country across the globe if you have the required skill set. It is better to have 2 years of working experience in the software field.<br>But if you are focused on government jobs, teaching jobs or some similar options, master’s degree can be helpful. But in software development, it is not so.<br>You can always go to a better company in 2 years or less than that by improving your skills and good coding practices.</p><p><strong>Is it worth learning MEAN Stack?</strong></p><p>MEAN Stack is a framework in which you can create applications. There are many such frameworks.<br>Initially, companies are not worried about the platform you use to solve a particular problem.<br>If you can solve a problem, no one worries about the platform. However, MEAN stack is a good platform. Many companies are adopting it. It is quite popular in the current industry. I am also working as a Full Stack Developer. But you have to always think that technologies will come and go — you have to be an engineer first who can solve any problem given to you. Technology and frameworks will change but you have to prove yourself in any given task. That’s why I have learned in my college days — whatever task is given to you, complete it with full dedication.</p><p><strong>How to prepare for placements?</strong></p><p>If you are thinking about campus placements — you don’t have to prepare a lot just read some traditional books to prepare aptitude and tech questions. If you are thinking of a good company — prepare data structures well, read about object-oriented programming concepts — not syntax. Know about SOLID principle and practice programming question on some online forum.</p><blockquote>You should have a good profile on GitHub, and other code platforms.</blockquote><p><strong>How important is percentage or marks for placements?</strong></p><p>I had a backlog — I was not able to sit in many companies during my campus placements. Ultimately I had got a better job than others. Do I need to say any more about marks and percentage? If you want to go to masters and higher studies — might be useful to have higher grades but otherwise — no one will ask.</p><p><strong>How you faced tech interviews with basic knowledge of JAVA and other things?</strong></p><p>Companies are not checking in-depth knowledge of Java or any framework. You can survive with basic knowledge if you have the problem-solving attitude with you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stEWKnTBKJpzd_M4KvQ0MQ.jpeg" /></figure><p><strong>What do you think about future of mobile application software development?</strong></p><p>Future is bright for mobile and all smart devices which will come. You can already see that people are using mobile as complete computing systems. There are lots of work going on in this field.</p><p><strong>What is a product company and how it is different from a service company?<br></strong> <br>Product company has there own product -like windows by Microsoft — they work on the product, maintain it and improve it. Service companies — generally work on products of other companies and make them possible using their developers — Like Infosys. They create products for other companies who are their clients. Generally, people want to work in product company as they can have a ownership of some product — but at times you can be bored on working on the same project. But you can switch if your company provide flexibility to switch teams and products.</p><p><em>These were excerpts from talk of Harsh, if you want to be a part of growing community of coders and hackers at Youstart, you can join our facebook group </em><a href="https://www.facebook.com/groups/youstartlabs">https://www.facebook.com/groups/youstartlabs</a> .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f7ae4ef9c48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stemoto/https-medium-com-rathore-session-by-harsh-bhardwaj-youstart-summer-internship-jaipur-fullstack-1f7ae4ef9c48">An Interactive session with Harsh Bhardwaj at Youstart : How to land great Jobs.</a> was originally published in <a href="https://medium.com/stemoto">Stemoto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Angular 6 using Game of Flags]]></title>
            <link>https://medium.com/stemoto/intro-to-angular-6-using-game-of-flags-8f83cba1be08?source=rss-20cfddb2e89c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f83cba1be08</guid>
            <category><![CDATA[angular-6]]></category>
            <category><![CDATA[youstart]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[jaipur]]></category>
            <dc:creator><![CDATA[Abhishek Rathore]]></dc:creator>
            <pubDate>Sun, 03 Jun 2018 10:59:43 GMT</pubDate>
            <atom:updated>2018-06-03T10:59:43.404Z</atom:updated>
            <content:encoded><![CDATA[<p>Starting Angular 6 can be a daunting task specially if you are unaware of component style web architectures and new to ES6/typescript world. Rather than jumping to Heroes Tour on official Angular Site we can make some interesting application to learn the basics of Angular components and service objects.</p><p>TLDR ;</p><p><strong>In this article we will create a small game — Game of Flags (not Thrones :P ). All code is hosted on GitHub </strong><a href="https://github.com/Youstart-Labs/GameOfFlags"><strong>here</strong></a><strong> and all steps are shown in a screencast hosted on this Youtube </strong><a href="https://youtu.be/zCrRtjX8UQE"><strong>link</strong></a><strong>. If you are a pro — Go there.</strong></p><p>Ingredients Required :</p><ul><li>Code Editor (I prefer VSCode)</li><li>Node and NPM installation</li><li>Angular 6 CLI installed on your system [ check if `ng` command works]</li></ul><p><strong>Steps :</strong></p><ol><li>Create a new project using ng new command. This will create the Angular 6 scaffold for a new app. I have chose name gof</li></ol><pre>ng new gof</pre><p>2. Move to newly create folder gof using cd command</p><pre>cd gof</pre><p>At this point you can check using ng serve command that your angular application is working perfectly on <a href="http://localhost:4200.">http://localhost:4200</a></p><p>3. Create a new component using ng generate component command</p><pre>ng generate component flag</pre><p>This will generate a flag component which is by default called via app-flag tag in your root component . We will come back to this point in later part of article.</p><p>4. Open flag.component.html in flag component folder. Here you can create a basic text input box and button using simple HTML code. We will use this button to generate random flags and input for guessing name of nation.</p><p>5. You will need a list of all countries to generate random countries data — as we will later use a CSS library called flag-icon-css which depends on ISO Codes of countries — like IN for India. I will download the use all.json data given on Github repo <a href="https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes/blob/master/all/all.json">https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes/blob/master/all/all.json</a></p><p>6. To store all this data — it is a good idea to create a Service in Angular. We will used ng generate service command to generate a data service.</p><pre>ng generate service countries</pre><p>This will create file countries.service.ts in root folder. Here we can paste our countries data in one function called getCountries</p><p>Here how it will look like :</p><pre>export class CountriesService {</pre><pre>constructor() { }</pre><pre>getCountries(){</pre><pre>return [{“name”:”Afghanistan”,”alpha-2&quot;:”AF”,.....] //all data</pre><pre>}</pre><p>7. Now we can import CountriesService inside our flag.component.ts</p><p>Use import statements like this</p><pre>import { CountriesService } from &#39;../countries.service&#39;;</pre><p>Also we will need to add the Service variable to our constructor to use it properly. I called it cService</p><pre>constructor(private cService: CountriesService) { }</pre><p>8. Now let’s implement a function called next() which will be called on click of our button in Flag component. We will implement logic to generate random number to a range of countries array indexes. So we can pick a random country and its name, ISO code properties.</p><p>Here is what it will look like</p><pre>next(){</pre><pre>let countries = this.cService.getCountries();</pre><pre>let random = Math.floor(Math.random()*countries.length);</pre><pre>this.randomNationName = countries[random].name;</pre><pre>this.randomNationISOCode = countries[random][&#39;alpha-2&#39;]</pre><pre>console.log(this.randomNationISOCode,this.randomNationName)</pre><pre>}</pre><p>Don’t forget to declare randomNationName and randomNationISOCode at top of class.</p><p>9. Finally to check the function we need to attach this to our button using click event binding</p><pre>&lt;button (click)=&quot;next()&quot;&gt;Fire&lt;/button&gt;</pre><p>Now you can check in your browser that you are getting random names and ISO code of countries.</p><p>10. We have not yet implemented flag logic. We will use github project called flag-icon-css to perform this. You can install this library via npm using</p><pre>npm install flag-icon-css</pre><p>This will install it in node_modules . We can use this CSS in our component using @Component decorators</p><pre>@Component({</pre><pre>selector: &#39;app-flag&#39;,</pre><pre>templateUrl: &#39;./flag.component.html&#39;,</pre><pre>styleUrls: [&#39;./flag.component.css&#39;,<br>&#39;../../../node_modules/flag-icon-css/css/flag-icon.css&#39;]</pre><pre>})</pre><p>Finally you can check whether CSS is working or not by attaching the style on your flag.component.html</p><pre>&lt;span class=&quot;flag-icon flag-icon-gr&quot;&gt;&lt;/span&gt;</pre><p>Here gr represents ISO code of Greece in lowercase. Check if this works for you — or you have made some mistake in attaching CSS files. However, the flag size will be small by default. You can change it by changing the inline-style to this.</p><pre>&lt;span style=&quot;width:10em; line-height: 10em&quot; class=&quot;flag-icon flag-icon-gr&quot;&gt;&lt;/span&gt;</pre><p>11. Let add some logic so that we can get random flag on clicking of Fire button. Logic is simple just replace flag-icon-gr with flag-icon-{{randomNationISOCode}} . However ISO codes are by default in uppercase we can use Angular Pipes to make them in lower case.</p><pre>&lt;span style=&quot;width:10em; line-height: 10em&quot; class=&quot;flag-icon flag-icon-{{randomNationISOCode | lowercase}}&quot;&gt;&lt;/span&gt;</pre><p>Now you can check that you are getting a random flag on click of Fire button. You can also show the randomNationName with flags — just to verify.</p><p>11. Final part of game requires us to</p><ul><li>remove the nation name from HTML</li><li>create a variable myGuess and attach it to input box using ngModel directive</li><li>And finally add a conditional alert shown using *ngIf to check whether myGuess is equal to randomNationName or not.</li></ul><p>All this can be done via this code snippet ( flag.component.html )</p><pre>&lt;div&gt;</pre><pre>&lt;div&gt;</pre><pre>&lt;span style=&quot;width:10em;line-height: 10em&quot; class=&quot;flag-icon flag-icon-{{randomNationISOCode | lowercase}}&quot;&gt;&lt;/span&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;input type=&quot;text&quot; [(ngModel)]=&quot;myGuess&quot; placeholder=&quot;enter name of nation&quot;&gt;</pre><pre>&lt;button (click)=&quot;next()&quot;&gt;Fire&lt;/button&gt;</pre><pre>&lt;h1 *ngIf=&quot;myGuess &amp;&amp; myGuess==randomNationName&quot;&gt;Correct Guess !!!&lt;/h1&gt;</pre><pre>&lt;/div&gt;</pre><p>Please note that you will need to import FormsModule in app.module.ts for using ngModel directive.</p><pre>import { FormsModule } from &#39;@angular/forms&#39;;</pre><pre>/// at top of file</pre><pre>imports: [</pre><pre>BrowserModule,</pre><pre>FormsModule   //add this part</pre><pre>],</pre><p>12. Tada !! you game is ready and you can play it via click on Fire button and putting on your guesses.</p><p><strong>There are lot of improvement you can do in this game — making UI changes, making guess via multiple choices rather than typing and making friendly alerts etc.</strong></p><p>Here is one screenshot of my Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*4uLP3NDDHA15e25AxHCVsw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f83cba1be08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stemoto/intro-to-angular-6-using-game-of-flags-8f83cba1be08">Intro to Angular 6 using Game of Flags</a> was originally published in <a href="https://medium.com/stemoto">Stemoto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Techie Thursdays]]></title>
            <link>https://medium.com/stemoto/techie-thursdays-bf8b2c0aa9d6?source=rss-20cfddb2e89c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8b2c0aa9d6</guid>
            <category><![CDATA[jaipur]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[coders]]></category>
            <category><![CDATA[talks]]></category>
            <dc:creator><![CDATA[Abhishek Rathore]]></dc:creator>
            <pubDate>Thu, 24 May 2018 17:58:07 GMT</pubDate>
            <atom:updated>2018-05-24T17:58:07.988Z</atom:updated>
            <content:encoded><![CDATA[<p>There has been an immense need for techies to share their knowledge with their peers and we are following up our routine via Techie Thursdays at Youstart Labs. A topics can vary from a simple discussion on new technologies, to ways of redefining career. Interns and students are participating enthusiastically to the initiative and coming up with lots of exciting ideas — many of them from their daily lives and environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8b2c0aa9d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stemoto/techie-thursdays-bf8b2c0aa9d6">Techie Thursdays</a> was originally published in <a href="https://medium.com/stemoto">Stemoto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>