<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>effects | Kate Gable</title>
	<atom:link href="https://www.katesky.com/tag/effects/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.katesky.com</link>
	<description>sharing knowledge, encouraging to learn, promoting passion for coding, supporting mothers who code</description>
	<lastBuildDate>Tue, 20 Dec 2022 21:29:35 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
<site xmlns="com-wordpress:feed-additions:1">193364748</site>	<item>
		<title>Data polling with ngrx effect and how to unit test it</title>
		<link>https://www.katesky.com/2022/12/20/data-polling-with-ngrx-effect-and-how-to-unit-test-it/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=data-polling-with-ngrx-effect-and-how-to-unit-test-it</link>
		
		<dc:creator><![CDATA[Katerina Gable]]></dc:creator>
		<pubDate>Tue, 20 Dec 2022 18:30:11 +0000</pubDate>
				<category><![CDATA[angular]]></category>
		<category><![CDATA[effects]]></category>
		<category><![CDATA[kate sky]]></category>
		<category><![CDATA[ngrx]]></category>
		<category><![CDATA[state management]]></category>
		<category><![CDATA[TestScheduler]]></category>
		<category><![CDATA[unit tests]]></category>
		<guid isPermaLink="false">https://www.katesky.com/?p=260</guid>

					<description><![CDATA[<p>I just finished implementing data polling using ngrx effects. For those unfamiliar with ngrx, it is a popular library for implementing the Redux pattern in Angular applications. To implement data polling with ngrx effects, you can create an effect that listens for <br /><a href="https://www.katesky.com/2022/12/20/data-polling-with-ngrx-effect-and-how-to-unit-test-it/" class="more-link">Read More</a></p>
The post <a href="https://www.katesky.com/2022/12/20/data-polling-with-ngrx-effect-and-how-to-unit-test-it/">Data polling with ngrx effect and how to unit test it</a> first appeared on <a href="https://www.katesky.com">Kate Gable</a>.]]></description>
										<content:encoded><![CDATA[<body>
<p>I just finished implementing data polling using ngrx effects. For those unfamiliar with ngrx, it is a popular library for implementing the Redux pattern in Angular applications.</p>



<p>To implement data polling with ngrx effects, you can create an effect that listens for a specific action, such as a <code>POLL_DATA</code> action. When this action is dispatched, the effect can perform an HTTP request to retrieve the data from a remote server, and then dispatch a new action with the data.</p>



<p>You can use the <code>@Effect</code> decorator to create an effect that listens for specific actions. The <code>@Effect</code> decorator takes an options object as an argument, which allows you to specify the action that the effect should listen for and the effect’s behavior.</p>



<p>For example, you might create an effect that listens for the <code>POLL_DATA</code> action and performs an HTTP request to retrieve the data like this:</p>


<div class="wp-block-syntaxhighlighter-code code"><pre class="brush: jscript; highlight: [1]; title: ; notranslate">
@Injectable()
export class PollingEffects {
  pollData$: Observable&lt;Action&gt; = this.actions$.pipe(
    ofType(POLL_DATA),
    switchMap(() =&gt;
      this.http.get('/api/data').pipe(
        map((data) =&gt; ({ type: DATA_RECEIVED, payload: data })),
        catchError(() =&gt; of({ type: DATA_REQUEST_FAILED }))
      )
    )
  );
}


</pre></div>


<p>This effect listens for the <code>POLL_DATA</code> action and then performs an HTTP request using the <code>HttpClient</code> service. If the request is successful, it dispatches a <code>DATA_RECEIVED</code> action with the received data as the payload. If the request fails, it dispatches a <code>DATA_REQUEST_FAILED</code> action.</p>



<p>To ensure that the data is polled at regular intervals, you can use the <code>interval</code> operator from the RxJS library. You can modify the effect above to poll the data every 10 seconds like this:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
@Injectable()
export class PollingEffects {
  pollData$: Observable&lt;Action&gt; = this.actions$.pipe(
    ofType(POLL_DATA),
    switchMap(() =&gt; interval(10000)),
    switchMap(() =&gt;
      this.http.get('/api/data').pipe(
        map((data) =&gt; ({ type: DATA_RECEIVED, payload: data })),
        catchError(() =&gt; of({ type: DATA_REQUEST_FAILED }))
      )
    )
  );
}

</pre></div>


<p>In this modified version of the effect, the <code>interval</code> operator is used to emit a value every 10 seconds (10000 milliseconds). The effect then uses the <code>switchMap</code> operator to perform an HTTP request every time the interval emits a value.</p>



<p>To stop the data polling, you can simply dispatch a new action that the effect can listen for and respond to.</p>



<p>For example, you might create a <code>STOP_POLLING</code> action that the effect can listen for and use to stop polling the data. You can modify the effect above to stop polling when the <code>STOP_POLLING</code> action is dispatched like this:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
@Injectable()
export class PollingEffects {
  pollData$: Observable&lt;Action&gt; = this.actions$.pipe(
    ofType(POLL_DATA),
    switchMap(() =&gt;
      interval(10000).pipe(takeUntil(this.actions$.pipe(ofType(STOP_POLLING))))
    ),
    switchMap(() =&gt;
      this.http.get('/api/data').pipe(
        map((data) =&gt; ({ type: DATA_RECEIVED, payload: data })),
        catchError(() =&gt; of({ type: DATA_REQUEST_FAILED }))
      )
    )
  );
}
</pre></div>


<p>In this modified version of the effect, the <code>takeUntil</code> operator is used to stop the data polling when the <code>STOP_POLLING</code> action is dispatched. The <code>takeUntil</code> operator takes an observable as an argument and completes the source observable (in this case, the <code>interval</code> observable) when the argument observable emits a value.</p>



<p>To use this modified effect, you can dispatch the <code>POLL_DATA</code> action to start polling and the <code>STOP_POLLING</code> action to stop polling.</p>



<h4 class="wp-block-heading">To create a unit test for the data polling effect using the TestScheduler from the RxJS library, you can use the following steps: </h4>



<p>First you have to modify your effect to use asyncScheduler like this:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
@Injectable()
export class PollingEffects {
  pollData$: Observable&amp;lt;Action&gt; = this.actions$.pipe(
    ofType(POLL_DATA),
    switchMap(() =&gt;
      interval(10000, asyncScheduler).pipe(
        takeUntil(this.actions$.pipe(ofType(STOP_POLLING)))
      )
    ),
    switchMap(() =&gt;
      this.http.get('/api/data').pipe(
        map((data) =&gt; ({ type: DATA_RECEIVED, payload: data })),
        catchError(() =&gt; of({ type: DATA_REQUEST_FAILED }))
      )
    )
  );
}

</pre></div>


<p>In this modified version of the effect, the <code>interval</code> operator is called with the <code>asyncScheduler</code> as the second argument. This causes the interval to use the <code>asyncScheduler</code> to schedule its emissions.</p>



<p>The <code>asyncScheduler</code> is a scheduler that schedules work asynchronously, using the JavaScript <code>interval</code> function. This can be useful if you want to simulate a delay in the data polling effect, or if you want to ensure that the effect is run outside the Angular zone.</p>



<p>I hope this helps clarify how to use the <code>asyncScheduler</code> with the data polling effect. Next you will add your unit tests file and follow the steps:</p>



<ol class="has-small-font-size wp-block-list">
<li>Import the <code>TestScheduler</code> from the RxJS library. The <code>TestScheduler</code> is used to control the virtual time in the test;</li>



<li>Create an instance of the <code>TestScheduler</code> and set up the test actions and expected results. To do this, you will need to define the actions that the effect should listen for and the expected results of the effect. </li>



<li>Set up the dependencies for the effect under test. This will typically include any services or dependencies that the effect uses, such as the <code>HttpClient</code> service. You can use mock implementations of these dependencies to control their behavior in the test.</li>



<li>Create an instance of the effect under test and pass in the dependencies.</li>



<li>Pass <code>TestScheduler</code> instance into the effect that is under test. This will execute the effect with a virtual timer.</li>
</ol>



<p>Here is an example of a unit test for the data polling effect using the TestScheduler:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
@Injectable()
export class PollingEffects {

    pollData$ = createEffect(() =&gt; ({ scheduler = asyncScheduler} = {}) =&gt;
    this.actions$.pipe(
      ofType(POLL_DATA),
      switchMap(() =&gt; interval(10000, asyncScheduler).pipe(
        takeUntil(this.actions$.pipe(ofType(STOP_POLLING)))
      )),
      switchMap(() =&gt; this.http.get('/api/data').pipe(
        map(data =&gt; ({ type: DATA_RECEIVED, payload: data })),
        catchError(() =&gt; of({ type: DATA_REQUEST_FAILED }))
      ))
    )
  );

}

</pre></div>


<p>To use the <code>createEffect</code> function from the ngrx library with the data polling effect, you can modify the effect like this:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">

</pre></div>


<p>The <code>createEffect</code> function takes a function that returns an observable as an argument, and returns an observable of actions. The function that is passed to <code>createEffect</code> should contain the logic for the effect.</p>



<p>In this modified version of the effect, the <code>createEffect</code> function is used to wrap the logic for the effect in a way that is compatible with the ngrx store. The effect listens for the <code>POLL_DATA</code> action and performs an HTTP request to retrieve the data every 10 seconds (10000 milliseconds) using asyncScheduler.  If the request is successful, it dispatches a <code>DATA_RECEIVED</code> action with the received data as the payload. If the request fails, it dispatches a <code>DATA_REQUEST_FAILED</code> action.</p>



<p>I hope this helps clarify how to use the <code>createEffect</code> function with the data polling effect. </p>



<p></p>



<p>Using ngrx effects to implement data polling is a straightforward process. Essentially, you can create an effect that listens for a specific action, such as a <code>POLL_DATA</code> action, and performs an HTTP request to retrieve data from a remote server. The effect can then dispatch a new action, such as a <code>DATA_RECEIVED</code> action, with the received data as the payload.</p>



<p>To stop the data polling, you can simply dispatch a new action, such as a <code>STOP_POLLING</code> action, that the effect can listen for and use to stop the data polling process.</p>



<p>Unit testing this effect is a bit tricky but you got it!</p>



<p>Hope all the code examples help you!</p>



<p>Hope you enjoyed this article.</p>



<p></p>



<p></p>



<pre class="wp-block-preformatted"></pre>
</body>The post <a href="https://www.katesky.com/2022/12/20/data-polling-with-ngrx-effect-and-how-to-unit-test-it/">Data polling with ngrx effect and how to unit test it</a> first appeared on <a href="https://www.katesky.com">Kate Gable</a>.]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">260</post-id>	</item>
	</channel>
</rss>
