<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jay Vincent</title>
    <description>The latest articles on DEV Community by Jay Vincent (@_builtbyjay).</description>
    <link>https://dev.to/_builtbyjay</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F196883%2F6f5a21f0-e5b3-430c-b293-7008cc3586d6.jpg</url>
      <title>DEV Community: Jay Vincent</title>
      <link>https://dev.to/_builtbyjay</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/_builtbyjay"/>
    <language>en</language>
    <item>
      <title>Creating Observables from an array of sequentially completing Promises</title>
      <dc:creator>Jay Vincent</dc:creator>
      <pubDate>Thu, 02 Jan 2020 19:00:43 +0000</pubDate>
      <link>https://dev.to/_builtbyjay/creating-observables-from-an-array-of-sequentially-completing-promises-273k</link>
      <guid>https://dev.to/_builtbyjay/creating-observables-from-an-array-of-sequentially-completing-promises-273k</guid>
      <description>&lt;p&gt;A super-quick post from me today, as I wanted to share some newly acquired knowledge.&lt;/p&gt;

&lt;p&gt;Let's say you have an array of data, userIds in this example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class PageComponent {
  userIds = ['user_1', 'user_2', 'user_3'];
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;And you want to create an Observable stream of &lt;code&gt;User&lt;/code&gt; objects from an API request, where each API request is run in sequence - ie. the request for &lt;code&gt;user_2&lt;/code&gt; won't be made until &lt;code&gt;user_1&lt;/code&gt; has resolved. How would you do it?&lt;/p&gt;

&lt;p&gt;Let's assume we have a function which returns a promise of our &lt;code&gt;User&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;You may be tempted to map over the &lt;code&gt;userIds&lt;/code&gt; and use &lt;code&gt;Promise.all&lt;/code&gt; like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class PageComponent {
  userIds = ['user_1', 'user_2', 'user_3'];
  users: User[];

  async ngOnInit(): void {
    this.users = await Promise.all([
      ...this.userIds.map(userId =&amp;gt; this.userService.getUser(userId))
    ]);
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;However, this will make all asynchronous calls at the same time and won't set &lt;code&gt;this.users&lt;/code&gt; until all inner promises have resolved.&lt;/p&gt;

&lt;p&gt;Observables are a much better pattern for this kind of use-case.&lt;/p&gt;

&lt;p&gt;What we want to do is create an Observable from the &lt;code&gt;userIds&lt;/code&gt; array with the rxjs &lt;code&gt;from&lt;/code&gt; function, then use the &lt;code&gt;concatMap&lt;/code&gt; operator to map each &lt;code&gt;userId&lt;/code&gt; to an inner observable (or promise in this case), which won't be subscribed to until the previous one has completed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class PageComponent {
  userIds = ['user_1', 'user_2', 'user_3'];
  users$: Observable&amp;lt;User&amp;gt;;

  ngOnInit(): void {
    this.users$ = from(this.userIds).pipe(
      concatMap(userId =&amp;gt; this.userService.getUser(userId))
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;When subscribed to, this observable will request and emit each user in sequence, emitting 3 &lt;code&gt;User&lt;/code&gt; objects over time before completing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bonus points - use &lt;code&gt;scan&lt;/code&gt; to accumulate values over time
&lt;/h2&gt;

&lt;p&gt;Let's say you wanted the Observable to build up an array of &lt;code&gt;User&lt;/code&gt; objects over time and not just emit individual &lt;code&gt;User&lt;/code&gt; objects. Let's use the rxjs &lt;code&gt;scan&lt;/code&gt; operator!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class PageComponent {
  userIds = ['user_1', 'user_2', 'user_3'];
  users$: Observable&amp;lt;User[]&amp;gt;;

  ngOnInit(): void {
    this.users$ = from(this.userIds).pipe(
      concatMap(userId =&amp;gt; this.userService.getUser(userId)),
      scan((acc, curr) =&amp;gt; acc.push(curr), [])
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Et voila! Simply loop over &lt;code&gt;users$ | async&lt;/code&gt; in your template and watch your user list grow.&lt;/p&gt;

&lt;p&gt;The power and magic of rxjs and Observables everybody :)&lt;/p&gt;

</description>
      <category>angular</category>
      <category>typescript</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Testing the ScrollToTop component in React with Enzyme and Jest</title>
      <dc:creator>Jay Vincent</dc:creator>
      <pubDate>Wed, 17 Jul 2019 13:00:35 +0000</pubDate>
      <link>https://dev.to/_builtbyjay/testing-the-scrolltotop-component-in-react-with-enzyme-and-jest-3p95</link>
      <guid>https://dev.to/_builtbyjay/testing-the-scrolltotop-component-in-react-with-enzyme-and-jest-3p95</guid>
      <description>&lt;p&gt;If you’ve implemented React Router in an application with long pages, you will have no doubt noticed that the scroll position doesn’t get reset when the location changes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/scroll-restoration.md"&gt;React Training recommend a neat little component&lt;/a&gt; to wrap around your App component, which will reset the scroll position to 0 when it detects a change in location:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import { withRouter } from 'react-router';
class ScrollToTop extends React.Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0);
    }
  }

  render() {
    return this.props.children;
  }
}

export default withRouter(ScrollToTop);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;To ensure the component is doing what we expect, let’s write some unit tests for this component.&lt;/p&gt;

&lt;p&gt;We want to test that:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The component calls &lt;code&gt;window.scrollTo&lt;/code&gt; with the correct parameters when location changes.&lt;/li&gt;
&lt;li&gt;It renders nested components correctly.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s set up our test file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import { mount } from 'enzyme';
import { MemoryRouter } from 'react-router-dom';
import ScrollToTop from './ScrollToTop';
global.scrollTo = jest.fn();
describe('ScrollToTop', () =&amp;gt; {
  let wrapper;
  let history;
  beforeEach(() =&amp;gt; {
    wrapper = mount(
      &amp;lt;MemoryRouter initialEntries={['/']}&amp;gt;
        &amp;lt;ScrollToTop&amp;gt;
          &amp;lt;p&amp;gt;Hi&amp;lt;/p&amp;gt;
        &amp;lt;/ScrollToTop&amp;gt;
      &amp;lt;/MemoryRouter&amp;gt;
    );
    history = wrapper.instance().history;
  });
  afterEach(() =&amp;gt; {
    jest.clearAllMocks();
  });
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Firstly, we create a spy for the &lt;code&gt;window.scrollTo&lt;/code&gt; method. Jest uses &lt;code&gt;global&lt;/code&gt; as the &lt;code&gt;window&lt;/code&gt; object, so we do this by assigning the spy to &lt;code&gt;global.scrollTo&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We mount our &lt;code&gt;ScrollToTop&lt;/code&gt; component within &lt;code&gt;MemoryRouter&lt;/code&gt; and get a reference to the mounted components history.&lt;/p&gt;

&lt;p&gt;We then make sure to reset our spy method after each test.&lt;/p&gt;

&lt;p&gt;With the set-up done, we are ready to write some tests!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it('calls window.scrollTo when route changes', () =&amp;gt; {
  expect(global.scrollTo).not.toHaveBeenCalled();
  history.push('/new-url');
  expect(global.scrollTo).toHaveBeenCalledWith(0, 0);
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We call &lt;code&gt;history.push&lt;/code&gt; just as we would in our application. This will activate a route change within &lt;code&gt;MemoryRouter&lt;/code&gt; which will then pass through updated props to the &lt;code&gt;ScrollToTop&lt;/code&gt; component, triggering the &lt;code&gt;componentDidUpdate&lt;/code&gt; lifecycle method.&lt;/p&gt;

&lt;p&gt;We can then assert that our spy method has been called with the correct parameters.&lt;/p&gt;

&lt;p&gt;Lastly, we write a test to ensure &lt;code&gt;ScrollToTop&lt;/code&gt; is rendering it’s nested components as expected.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it('it renders children', () =&amp;gt; {
  const component = wrapper.find(ScrollToTop);
  expect(component.children().length).toEqual(1);
  expect(component.contains(&amp;lt;p&amp;gt;Hi&amp;lt;/p&amp;gt;)).toEqual(true);
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;And we are done! I hope this proves useful to someone wanting to test a component that reacts to router events.&lt;/p&gt;

</description>
      <category>react</category>
      <category>testing</category>
    </item>
  </channel>
</rss>
