<?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 Boris on Medium]]></title>
        <description><![CDATA[Stories by Boris on Medium]]></description>
        <link>https://medium.com/@just-boris?source=rss-5e76c96bfe75------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wcAoqwrhx_NBcL04L9MGUQ.jpeg</url>
            <title>Stories by Boris on Medium</title>
            <link>https://medium.com/@just-boris?source=rss-5e76c96bfe75------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 07:05:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@just-boris/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[Peeking under the hood of redesigned Gmail]]></title>
            <link>https://just-boris.medium.com/peeking-under-the-hood-of-redesigned-gmail-dd84b532e0f5?source=rss-5e76c96bfe75------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd84b532e0f5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[gmail]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Boris]]></dc:creator>
            <pubDate>Thu, 15 Nov 2018 12:26:58 GMT</pubDate>
            <atom:updated>2018-12-01T10:31:08.631Z</atom:updated>
            <content:encoded><![CDATA[<p>Half a year ago Google <a href="https://www.theverge.com/2018/4/25/17277360/gmail-redesign-live-features-google-update">announced</a> an updated version of Gmail interface. Despite <a href="https://news.ycombinator.com/item?id=18095579">multiple complaints</a> from people, this is the default interface now.</p><p>Among the other issues, people noted performance problems with the new interface, especially on low-end machines. Let’s see how could this happen and what can be that heavy in the web-interface of the e-mail client. We will use Google Chrome’s DevTools, so this article will also be a good reminder about features that they have.</p><h3>Initial setup</h3><p>First of all, let’s look at Gmail’s performance. Chrome Devtools have a built-in tool, <a href="https://developers.google.com/web/tools/lighthouse/">Lighthouse</a>, that shows a nice and clear report about different aspects of your website, including performance. Gmail performance score is 2 out of 100:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5U2josqYUjsCRj8H-EIQg.png" /></figure><p>To be honest, this is not the result you might expect from a Google product. Nevertheless, let’s look deeper at this situation. After disabling cache and reloading the page, on the Network tab of dev tools will be displayed all requests have been done to load this page. For me, it was 6.9 Mb in total. This is a lot, especially considering that Webpack, for example, by default warns you when your assets size is more than 244 Kb. Here we have 27 times more.</p><blockquote>It is worth mentioning here that modern web services (including Gmail) are using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">Service Workers</a> for advanced assets caching. So, in order to get adequate numbers for the cold start payload you should not only <a href="https://stackoverflow.com/a/7000899/1297743">disable the cache</a> but also <a href="https://github.com/GoogleChromeLabs/sw-precache/issues/340#issuecomment-349947842">reset Service Workers</a>, which also holds some resources cached. After that, your numbers will show the full size of assets.</blockquote><p>Now let’s look at the page load in slow motion. There is an explanation in <a href="https://developers.google.com/web/tools/chrome-devtools/network-performance/">the documentation for Google Chrome</a> as how to do that. We will get a number of screenshots, showing page at different loading stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOafYzEK8qEsztMsQ9XmJQ.png" /></figure><p>It shows that the page becomes more or less usable after 9 seconds.</p><p>Loading page again with the cache and Service Workers enabled shows a better picture. There are only 250 Kb of requests, but it doesn’t actually make the page faster, we still have to see a loading screen for 9 seconds. There is something else makes the page load slower, not the network trade-offs.</p><h3>Blocking some resources</h3><p>If we will look at the list of resources, there will be a lot of them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTiol1DviA5MbCSdsvfcpQ.png" /></figure><p>Maybe some of them are not really needed for the page work? Let’s try blocking resources and see how will this affect the page. It is easy to do with the <a href="https://developers.google.com/web/updates/2017/04/devtools-release-notes#block-requests">built-in dev tools feature</a>.</p><p>It turned out, that requests to `https://mail.google.com/_/scs/*` are crucial for the Gmail interface, but some others can be blocked:</p><ul><li>www.gstatic.com/og/* — <a href="https://developers.google.com/api-client-library/">Google API Сlient Library</a>, to make requests to API of different Google services</li><li>ssl.gstatic.com/inputtools/* — <a href="https://www.google.com/inputtools/">Google Input Tools </a>— screen keyboard widget</li><li>hangouts.google.com — embedded Hangouts widget</li></ul><p>After blocking these scripts the page loads in 4 seconds, but the essential functions such as reading and writing emails are still working. If you also experience performance issues in Gmail interface, blocking these URLs might be a solution for you.</p><h3>Profiling</h3><p>At this point, we have cut off some resources, but the page still loads slow. We should look, what is happening during these 4 seconds. Chrome has <a href="https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/reference">a built-in Javascript profiler</a>, that will show us the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpldiVs67ZoTeog9K0VxTg.png" /></figure><p>Apparently, the browser was busy executing Javascript throughout this time. It is interesting to observe what sort of code this is. Javascript is usually shipped to clients in a minified form without formatting and with mangled function and variable names.</p><h3>De-minifying the source code</h3><p>Let’s try to understand the minified code. We will download resources and pass them through <a href="https://prettier.io/">Prettier</a>, a code formatting tool. Alternatively, you could use a <a href="https://developers.google.com/web/tools/chrome-devtools/javascript/reference#format">built-in feature</a> of Chrome DevTools.</p><p>Code becomes more readable, but it is still very hard to understand without original names, what these functions do. Fortunately, strings are preserved and we can use these clues to restore the source code. There are some strings like closure_uid_ or type_error:TrustedResourceUrl. We can search for them on the internet in hope of finding some open-source framework they are coming from.</p><p>The search would lead us to <a href="https://github.com/google/closure-library">Google Closure Library</a>. It seems like we have seen some minified pieces of this framework. Further compare reveals some matches between minified code and sources of Closure Library:</p><p>Two if statements, one short and one long, then assignment and finally a function call. This must be the same code.</p><p>Going further we also meet strings like GwtExecutor, ListenableFuture, DaggerComponentFactory, that look like parts of Java-stack, possibly compiled to Javascript. A related Google Inbox project is featured on “<a href="http://www.gwtproject.org/examples.html">projects using GWT</a>&quot; page and it is possible that it shared some code with the main Gmail interface.</p><p>This technology stack is very unexpected. In the light of the fact that Google <a href="https://www.youtube.com/watch?v=7CUO7PyD5zA">actively promotes</a> web components and their framework on top of that (Polymer) it is very surprising to see in 2018 a redesign of a Google project that doesn’t use them.</p><p>Instead, we have a very old technology stack with a lot of artifacts from past days where all browsers did not follow standards and you had to write a special treatment for each browser. The leftovers of it are still there, in 2018 edition of Gmail code:</p><ul><li><a href="https://github.com/google/closure-library/blob/master/closure/goog/net/xmlhttp.js#L216">AJAX via ActiveXObject</a>, a hack for IE6, because it did not have XMLHttpRequest support</li><li><a href="https://github.com/google/closure-library/blob/master/closure/goog/events/events.js#L270">Event listeners via attachEvent</a>, were needed for IE8 and below, they did not have standard `addEventListener` method.</li></ul><p>This code is included in the bundle for no practical reason, because Gmail <a href="https://support.google.com/mail/answer/6557?co=GENIE.Platform%3DDesktop&amp;hl=en">officially supports only</a> IE10+, there are no consumers for these hacks.</p><p>In addition to legacy overhead, this stack has outdated components paradigm. It is based on <a href="https://google.github.io/closure-library/source/closure/goog/demos/">class hierarchy</a> — an approach with a big number of heavy abstractions, which are getting created for every component that significantly slows down the rendering when you have hundreds of components on a page. Modern UI-frameworks don’t do long inheritance chains, their classes are light and the rendering work is being performed by the framework core. This reduces an overhead of components, so you can have more components without performance penalty.</p><p>It is definitely contributing to slow page initialization: there are thousands of classes are being instantiated during page load that slows down page rendering.</p><p>Thus, despite the updated visual look, the code of Gmail carries the legacy of old technologies, the weight cannot be hidden by the new visual shell.</p><h3>Checking code coverage</h3><p>Another useful feature of DevTools is <a href="https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage">Code coverage</a>. It helps to understand which parts of the code were not executed by the browser and possibly can be loaded on demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GnN4IZqHNeDmAqOw8q4pFQ.png" /></figure><p>About half of the code was not used. There are can be legit pieces, like event listeners and other async operations. But it is worth checking unused parts anyway, we can find some code that might be thrown away.</p><p>In addition to already mentioned hacks for older versions of Internet Explorer, we have found a couple more interesting pieces:</p><p><strong>Leftovers of Google Picasa</strong></p><p>The service has been shut down, but the memory still lives in GMail code.</p><p><strong>Screen keyboard</strong></p><p>There is a bunch of classes responsible for the feature, that you probably don’t use every day, but they are loaded with every Gmail page visit.</p><p><strong>Integration with Google Calendar</strong></p><p>Same as above: you might not use Google Calendar, but the nice meeting representation will be loaded.</p><h3>Conclusion</h3><p>This review may clarify some reasons why Gmail interface is slow. Unfortunately, it is out of our hands, to make Google improve the performance of their interface. But we can learn some lessons for our own web applications:</p><ul><li>Google Closure Compiler is very powerful. That was a real puzzle to restore the source code, it currently gives the best compression rate comparing to any other JS minifier.</li><li>Check your project for unused code, for example, hacks for older browsers. Review your code and get rid of things, which are not actual anymore. If you use Babel, consider providing <a href="https://babeljs.io/docs/en/babel-preset-env#browserslist-integration">browserlist config</a> to include only transformations that make sense for your target audience.</li><li>Abstractions are not free. If you would like to solve a task using an elegant programming pattern, first think about the cost of it. There may be a simpler solution available.</li><li>Do not include secondary page elements in the initial payload, use <a href="https://developers.google.com/web/fundamentals/performance/optimizing-javascript/code-splitting/">code-splitting</a>. In the case of Gmail, the Hangouts widget is being loaded immediately, slowing down main resources. It might be loaded later, after the crucial functionality of the page — the list of emails.</li><li>Do not neglect modern technologies. They might contain fundamentally different solutions for your issues, more performant and convenient.</li><li>Finally, do not forget to pay attention to the performance of your app. <a href="https://developers.google.com/web/fundamentals/performance/audit/tools">Audit it</a> from time to time, or set up a CI integration for it.</li></ul><blockquote>Thanks to <a href="https://medium.com/u/ca5e8845364b">Oli Steadman</a> for proofreading the article</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd84b532e0f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The hidden power of Jest matchers]]></title>
            <link>https://just-boris.medium.com/the-hidden-power-of-jest-matchers-f3d86d8101b0?source=rss-5e76c96bfe75------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3d86d8101b0</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Boris]]></dc:creator>
            <pubDate>Mon, 09 Jan 2017 23:42:20 GMT</pubDate>
            <atom:updated>2021-04-02T08:32:45.330Z</atom:updated>
            <content:encoded><![CDATA[<p>Not very many people know, that Jasmine provides you an ability to customize the result of equality check, which is internally used in toEqual, toHaveBeenCalledWith, and other matchers.</p><p>Basically, it means that if the right-side object has an asymmetricMatch method, the result if its call will be used instead of an actual deep-equality check.</p><pre>const fooOrBar = {<br>  asymmetricMatch: actual =&gt; actual === &#39;foo&#39; || actual === &#39;bar&#39;<br>};</pre><pre>expect(&#39;foo&#39;).toEqual(fooOrBar); // passes<br>expect(&#39;bar&#39;).toEqual(fooOrBar); // passes<br>expect(&#39;baz&#39;).toEqual(fooOrBar); // fails, not either &#39;foo&#39; or &#39;bar&#39;<br>expect(fooOrBar).toEqual(&#39;foo&#39;); // fails, works only at right side</pre><p>This feature is available in Jasmine and described pretty well in <a href="https://jasmine.github.io/edge/introduction#section-Custom_asymmetric_equality_tester">the official documentation</a>. Also Jest, which uses Jasmine underneath also officially supports it as <a href="http://facebook.github.io/jest/docs/api.html#asymmetric-jest-matchers">it is described in the documentation</a>.</p><p>Today I will try to highlight some examples, where asymmetric matches will be surprisingly powerful and allow you to write much simpler code than before. All code examples bellow will be based on Jest, however, the difference with Jasmine will not be very big, the general approach will be the same.</p><h3>1. Match calls with function in arguments</h3><p>Imagine, that you need to test that some API method was called properly. When all method parameters are plain objects or primitives, it is easy:</p><pre>fakeApi.method({options: true});</pre><pre>expect(fakeApi.method).toHaveBeenCalledWith({options:true});</pre><p>But if method accepts also a callback, it will be not quite simple</p><pre>fakeApi.asyncOperation(result =&gt; {<br>  console.log(result)<br>});</pre><pre>expect(fakeApi.method).toHaveBeenCalledWith(result =&gt; {<br>  console.log(result));<br>});</pre><p>This will not work because functions are not equal to each other. To make this work, you need to store a reference to the callback and use it later in assertion</p><pre>const callback = (result) =&gt; console.log(result);<br>fakeApi.asyncOperation(callback);</pre><pre>expect(fakeApi.method).toHaveBeenCalledWith(callback);</pre><p>But this is not always possible. In some cases, this callback will be provided by somebody else and you will not get the direct access to it. Therefore, will not be able to use toHaveBeenCalledWith, for this kind of tests.</p><p>This is the case, where asymmetric matches may come and help you. We can write an assertion, that method was called with some function, but doesn’t matter what exactly. Jest (actually, Jasmine) gives us a set of predefined asymmetric matches, for example, expect.any(&lt;type&gt;) that returns true for any value with specified type</p><pre>fakeApi.doAsync((result) =&gt; console.log(result));</pre><pre>expect(fakeApi.doAsync).toHaveBeenCalledWith(expect.any(Function));</pre><p>Great! Now we are may do assertions, but skip some values, that not possible to check strictly. In addition to this we may use expect.anything to tell that here any value is allowed, except undefined or null. This may be useful, when only some method arguments make sense for you</p><pre>circle.show({x: 10, y: 15}, {color: &#39;blue&#39;});</pre><pre>expect(circle.show).toHaveBeenCalledWith({x: 10, y: 15}, expect.anything());</pre><p>Also we can use those matches at any level, not only on top, so we can check types of provided arguments, without mentioning values</p><pre>circle.show({x: 10, y: 15}, {color: &#39;blue&#39;});</pre><pre>expect(circle.show).toHaveBeenCalledWith({<br>  x: expect.any(Number),<br>  y: expect.any(Number)<br>}, {<br>  color: expect.any(String)<br>});</pre><p>Using asymmetric matches as a placeholder for some spy arguments helps you to focus on the most important stuff in your tests.</p><h3>2. Ignoring values, relative to current time</h3><p>We can use the same technique to suppress checks for some values that are based on your testing environment, for example, data that is produced from the current date.</p><p>Every time, when you writing an assertion on the object, that contains generated timestamp, you need to find a way to mock system time. You can use any time-mocking library to stub value of Date.now() and new Date(), but also you can use asymmetric matchers magic. For example, we have a function, that generates an object representing comment entity, that will be saved. It has a field createdAt, which is taken from the current time. When we are writing a test on it, we can put an asymmetric placeholder instead of timestamp:</p><pre>const comment = createComment(&#39;test content&#39;, &#39;author@me.com&#39;);</pre><pre>expect(comment).toEqual({<br>  createdAt: expect.any(Date),<br>  content: &#39;test content&#39;,<br>  author: &#39;author@me.com&#39;<br>});</pre><p>So, now we have got everything tested, but didn’t look very much into minor details. Basically, the pattern is the following: if you have some value, that should exist in tested data, but you don’t what exactly it is, replace it with expect.any or expect.anything.</p><h3>3. Partial match for complex objects</h3><p>Here is a lot of use-cases when you are receiving a big object, but only few fields make sense for you. When you are testing this code, you also would like to mention only important fields, but not others, that may be changed, without any effect for your code. Asymmetric matchers like expect.objectContaining and expect.arrayContaining may help you there:</p><pre>const user = prepareUserInfo(&#39;test-user&#39;); </pre><pre>// user object is something like ... <br>// {<br>//   id: 123,<br>//   name: &#39;test-user&#39;,<br>//   profile: {...},<br>//   passwordHash: &#39;*****&#39;,<br>//   whatever: {...}<br>// }</pre><pre>// ... but for the test we are interested only in name and id<br>expect(user).toEqual(expect.objectContaining({<br>  id: 123,<br>  name: &#39;test-user&#39;<br>}));</pre><p>You can make your test code cleaner, when you explicitly mention the only limited set of values, that it important for the test. Remember the crucial test pattern: one test — one feature.</p><p>Same for arrays. If you are getting the array of TODOs, but you need to find only recently added, use expect.arrayContaining</p><pre>const newTodo = {text: &#39;increase test coverage&#39;};</pre><pre>addTodo(newTodo);</pre><pre>expect(todos).toEqual(expect.arrayContaining([newTodo]));</pre><p>Here you don’t need to care about items order. The goal of the test was to check, that recently added todo appears in the list, and we did it just fine.</p><h3>Putting everything together</h3><p>Here I tried to highlight some use cases, where asymmetric matches may be useful. But this is not the full list. Just remember, that every time you may replace any complex value with a simple placeholder to make your test code shorter and more expressive. So, I’d like to finish the post with this little code snippet, where you can see all asymmetric matches together.</p><pre>expect(store.getState()).toEqual({<br>  todosById: expect.any(Object),<br>  filters: expect.arrayContaining([&#39;completed&#39;]),<br>  user: expect.objectContaining({<br>    name: &#39;test-user&#39;,<br>    profile: expect.objectContaining({<br>      email: &#39;test-user@example.com&#39;<br>    })<br>  })<br>});</pre><p>Let’s assume, that store.getState() produces you a very big object. Usually, you have to write several assertions to check such data. But with asymmetric matchers you can do this with a simple check. Mark everything, that is important for you and ignore the rest. I hope you also have found this feature useful will give it a try in your projects as well as me. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3d86d8101b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Page object for testing React.js components]]></title>
            <link>https://just-boris.medium.com/page-object-for-testing-react-js-components-49cddb59adb7?source=rss-5e76c96bfe75------2</link>
            <guid isPermaLink="false">https://medium.com/p/49cddb59adb7</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Boris]]></dc:creator>
            <pubDate>Mon, 24 Oct 2016 07:11:02 GMT</pubDate>
            <atom:updated>2016-10-24T08:30:25.771Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I will tell you a little trick how to make your test code a bit fancier and easier to maintain. <a href="http://www.seleniumhq.org/docs/06_test_design_considerations.jsp#page-object-design-pattern">The PageObject pattern</a> is quite common in Selenium testing world, but it can be also useful when you are writing unit tests on every single UI-Component.</p><blockquote>Disclaimer: there will be no any new library that you need to install before get started. This article is about code pattern. You can adopt it with any technology stack, React is used here only for example, but it is not necessary.<br>But there is a <a href="https://github.com/just-boris/page-object">Github repo</a> with examples from this article, that you can bookmark for future reference.</blockquote><p>For example, we have a <strong><em>LoginForm </em></strong>component, that provides a simple interface for authorization. For sake of simplicity let’s put state handling logic aside, here will be stateless component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12ae8a7d7e0ede3fa0cdf10a6abe2852/href">https://medium.com/media/12ae8a7d7e0ede3fa0cdf10a6abe2852/href</a></iframe><p>Let’s try to test out logic. Let’s check that we can pre-fill our inputs with values. Also, we will follow actual best testing practices and will use <a href="https://github.com/airbnb/enzyme">enzyme</a> library to render our component to testing. So far, test would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b70a58b7aba364c93a0167e7ce565277/href">https://medium.com/media/b70a58b7aba364c93a0167e7ce565277/href</a></iframe><p>Then we need to test one more use case. Let’s add one more test and refactor it, by moving duplicated code into helper function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dbea31dfd2382272825d1a69a2557b0/href">https://medium.com/media/3dbea31dfd2382272825d1a69a2557b0/href</a></iframe><p>But we still couldn’t get rid of code that finds us form fields. We have a lot of similar component.find(...)calls that should be also replaced with a helper. Off the top of my head comes the idea to move selector strings into constant to make them reusable. But component.find(EMAIL_FIELD)doesn’t look much better than code before. Here can be a better way how to organize all elements selectors, you can create a PageObject.</p><p>Basically, PageObject is just a usual object, that gives you access to all important part of the page. We don’t test the whole web page, only one component, but we can think that our component is actually a little page, that we are going to interact with. In Javascript you can describe your page like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f120700a56c3a86bfb28c5ad7dbacf57/href">https://medium.com/media/f120700a56c3a86bfb28c5ad7dbacf57/href</a></iframe><p>Now we have a single place to describe our component and all interactive elements inside. Every time, when the component inner structure will change, we need update only those accessors, all other code that uses them can be unchanged. Probably, other developers, who are going to support your tests later, will thank you for this helper.</p><blockquote>Note, that we have created formField getter, that accepts a parameter. You may find this not acceptable for you, as an alternative you can create special methods for each element, like emailField()and passwordField(), it is also okay and up to you.</blockquote><p>Let’s put all things together and update our test suite:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a502e20b773a04e48611540f147dbefd/href">https://medium.com/media/a502e20b773a04e48611540f147dbefd/href</a></iframe><p>Currently, our test code encourages to do everything through Page object. This can be considered as a good practice, because every time when you are going to do something new, you need to define an accessor, that may be reused later. On the other hand, you can always check what component can do, by looking Page object definition.</p><p>Finally, let’s add one more test on handling submit. We can not only use page object to read data but also to simulate user behavior on the component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bb2678ae76f031df39fc93886578a01/href">https://medium.com/media/6bb2678ae76f031df39fc93886578a01/href</a></iframe><p>That’s it. Page object wrapper gives you nice API to interact with your component, so test code will be more expressive and neat. And this doesn’t require so many efforts from you, just follow this simple pattern.</p><p>However, we used React here, it is not required. You can adopt this pattern with almost every framework that has a conception of UI-Component. The actual implementation of component.find() method would be different, but the general approach with Page object will be the same.</p><p>Here is a <a href="https://github.com/just-boris/page-object">Github repository</a>, that contains code from this article and more other examples. I am going to maintain it and add more examples for more complex cases. Feel free to ask any questions and send pull requests!</p><p>I hope, this pattern will help you to test your components. Of course, here some more other things that also could help you — custom matchers, data-builders — but that will be another story. Happy coding and stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49cddb59adb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up Selenium tests with Webdriver.io]]></title>
            <link>https://just-boris.medium.com/setting-up-selenium-tests-with-webdriver-io-cc7fc3c86629?source=rss-5e76c96bfe75------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc7fc3c86629</guid>
            <category><![CDATA[allure]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Boris]]></dc:creator>
            <pubDate>Tue, 15 Mar 2016 16:48:55 GMT</pubDate>
            <atom:updated>2017-11-30T16:21:21.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes you need to check that your web application is working well. How can we test it? Unit testing is fine, it doesn&#39;t test your entire code as-is, every module is tested isolated from others. Sometimes you need some tool, that runs a real browser, simulates some actions like a real user does. Selenium can be this tool. It works with almost all browsers, even with mobile. But so often people underestimate Selenium because they treat it as a very difficult tool to use and looking for workarounds. But it doesn&#39;t if you know what to do, it seems very easy to use, and in this article, I am going to tell you how to setup tests against real browsers in your project.</p><h3>Meet Selenium</h3><p>Selenium is a very old tool. The project started in 2004 and went a long way and now it is the open platform, with well-documented public API and bindings for a lot of browsers. The core of Selenium is written in Java. But don&#39;t worry, you can use it with any language as a simple standalone program that runs a web server with some HTTP-methods.<br><br>You can install it from the official website, also, there is a neat wrapper to get this from npm. So for you node.js project, you can just run</p><pre>npm install selenium-standalone — save-dev</pre><p>Package ships an executable for you, that runs Selenium. But package itself contains the only downloader code, you need to fetch actual Selenium distro.</p><pre>./node_modules/.bin/selenium-standalone install</pre><blockquote><strong>ProTip:</strong> add this command as “prebublish” in your package.json, to download selenium automatically after npm install</blockquote><p>Then we can run Selenium server.</p><pre>./node_modules/.bin/selenium-standalone start</pre><p>We can work with Selenium like with any HTTP-server with some REST-API. This API named WebDriver and contains methods to interact with browsers. If you need to run some browser on different operation system (Internet Explorer, for example) you can run Selenium on remote computer, connect it from yours and run tests as well it was on your local machine. Because it is just a web-server, it can be scaled to a lot of copies in some cloud and make Selenium Grid, where you can run a lot of tests on different hosts in parallel. There some companies already provide you Selenium-as-service, if you don’t want setup and maintain your own cluster, you can use Sass solution.<br><br>But anyway it would be good to start from tests on your local machine and browsers because it significantly reduces overhead and allow you to step over some issues and get your setup much faster.</p><h3>Webdriver.io</h3><p>As I said, Selenium is a just server, that handles your HTTP-requests. But you don&#39;t need to call it directly. There are already a lot of libraries to do it in a nice way. Webdriver.io is one of the popular WebDriver clients in Javascript. Recently the 4th version was released, so now it is a good time to check this out.</p><pre>npm install webdriverio -- save-dev</pre><p>Webdirver.io can be used as any other library:</p><pre>var webdriverio = require(&#39;webdriverio&#39;);</pre><pre>var browser = webdriverio<br>  // setup your selenium server address. <br>  // If you are using default settings, leave it empty<br>  .remote({ host: &#39;localhost&#39;, port: 4444 })<br>  // run browser that we want to test<br>  .init({ browserName: &#39;chrome&#39;, version: &#39;45&#39; });</pre><p>Then we will get Chrome browser and can do something with it. We can open urls, do mouse clicks, look for elements on a page. Full list of available commands you can find in <a href="http://webdriver.io/api.html">documentation</a>.</p><p>But Webdriverio can do much more that that. It has special test runner that can do a lot of work for you to make your testing easier. You can find `wdio` command that is shipped with webdriverio package.<br><br>First of all, you need to run `wdio config` to went through configuration dialog and tell where you selenium server is, which browsers you want to run and other information. All possible options are listed in <a href="http://webdriver.io/guide/testrunner/configurationfile.html">that section</a> of Webdriverio docs. The result will be saved in the `wdio.conf.js` file. It is plain javascript file, that should return a configuration object. If you worked with Karma or Webpack, you will find this configuration style very similar. Here we can setup any options regarding our tests, browsers and setup some lifecycle hooks, for example, do something before each test starts.<br><br>Then you can write test code. The thing is there you will already have available `browser` object that you can use to work with a browser.</p><pre>describe(&#39;webdriver.io tests&#39;, function() {<br>    it(&#39;is a test&#39;, function() {<br>        browser.click(&#39;.logo&#39;);<br>    });</pre><pre>    it(&#39;is a second test&#39;, function() {<br>        browser.click(&#39;.link&#39;);<br>    });<br>});</pre><p>Look, now we don’t need to setup Selenium and get browser, all that things is now hidden in the configuration file, our tests very simple and straightforward.<br>But our setup is not finished yet. We need to run our selenium server for our tests. Webdriver.io provides an integration to run local selenium instance. You just need to install <a href="https://github.com/webdriverio/wdio-selenium-standalone-service">wdio-selenium-standalone-service</a> module, then add this into services section of your wdio.conf.js file:</p><pre><strong>export</strong>.config = {<br>  <em>// ...<br>  </em>services: [&#39;selenium-standalone&#39;],<br>  <em>// ...<br></em>};</pre><p>Great! Now our server magically starts up and shuts down around our test run. We can write tests and not care about other stuff around. The only thing that still isn&#39;t solved is how to automatically start up your application to test, but it solely depends on your environment and I beleive that you can set this up.</p><h3>Going deeper</h3><p>You may write more and more tests and eventually encounter with errors in your tests. Not all of them can be easy explained. Sometimes you have to do a lot of debugging to find out the reason. In simple unit tests, we have a lot of helpers to debug. We can put a breakpoint and go through our application code and watch actual variable values there. But with Selenium, we can&#39;t afford this. Our code is run so far away and we can&#39;t attach a debugger there. We may only watch to the page like a simple user and look for some errors. What does Webdriverio have to help us? The most popular way to debug Selenium tests is screenshoting. When you can see to your test page as it looks for test code, you will probably see the reason for the error. Webdriverio has a handy method for it.</p><pre>browser.saveScreenshot(&#39;my-page.png&#39;);</pre><p>You can save screenshots during tests and figure out what went wrong with them. But finally you will end up with a folder full of pictures and you will not have any context about any screenshot. You can get some hints from the filename, but you can&#39;t add a lot of data there. We need to gather much more data from our test when we making a screenshot or other dumping information.</p><h3>Allure-framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hW63gL11ONQu8lz3fIFVg.png" /><figcaption>Allure gives you very rich html report</figcaption></figure><p><a href="http://github.com/allure-framework/allure-core">Allure</a> is a framework for better test reporting. It gathers a lot of information and dumps it on disk and after tests, you will get an HTML file where you can see a report. It looks much better than raw console reports. Allure compatible with a lot of testing frameworks, there also is plugin for Webdriverio, that you can install from npm:</p><pre>npm install wdio-allure-reporter</pre><p>Then you can add `allure` into `reporters` section in config to enable it:</p><pre>reporters: [&#39;dot&#39;, &#39;allure&#39;]</pre><p>It would be better to keep default `dot` reporter to see actual progress while tests are running. After tests have been run, you will get some files in `allure-results` directory (by default, but you can change it). It is raw results, if you want to look at it, you need to do some processing. Install `allure-commandline` that will do it for you. You can install it from Homebrew, PPA, or use it as TeamCity/Bamboo/Jenkins plugin, but in this guide we are working with Node.js, so you probably want to get it from NPM. And you can:</p><pre>npm install allure-commandline</pre><p>To generate the report run the following:</p><pre>./node_modules/.bin/allure generate allure-results</pre><p>`allure-results` is a directory where you test results are. The final report will be in `allure-report` directory. It is some html files, that you can open using `allure open` command.<br><br>Why do you have to do a lot of commands? Why not just write the report after tests? Allure uses two-step model to make the second step optional. Report generation can take some time, but sometimes you don&#39;t need to see the report, for example, if all your tests were passed. Then your bill will be finished faster.<br><br>Finally, let&#39;s look at the report. All information from your tests now is structured to help you find a reason of fail much faster. There are several ways to review your results:</p><ul><li>Defects — here you will get a list of different exception messages that were thrown in your tests. If some test had failed with the same error, it will be grouped. Also, a little deviation is possible, some similar messages will be merged into one. Sometimes similar error has the same reason and can be fixed in one place and this view intended to help you with it.</li><li>xUnit — it is the classical view where you can see your test in the `Suite -&gt; Case` model. Here you can look your tests closely to how it looks in the source code and easily match failed tests with their actual code.</li><li>Graph — some statistics about your tests. Everybody likes charts, here you can find some.</li></ul><p>Allure have some more different views that are not perfectly integrated with Webdriverio for now, but hopefully, it will be done in future. There are:</p><ul><li>Behaviors – group tests by user stories. There you can group tests for different criteria rather than xUnit. If some user story is covered by test cases from different test suites, here you can see them all on one list.</li><li>Timeline – if you can run your tests in parallel (Webdriverio launcher can&#39;t do it, at least for now), it is good to know how your tests were distributed by time. For example, if your test application had some blackout, you will see a group of failing tests here. This view is a good thing to detect this issues.</li></ul><p>Let&#39;s try this. Then you will never want to investigate test failures in the console.</p><h3>Conclusion</h3><p>Selenium is the most common tool to run tests on real browsers. If you want to add some integration tests to your web application, you probably should consider it. You can use javascript if it is your main programming language. There are a lot of tools that you help with it. Webdriverio is a javascript library that works perfectly with Selenium. After a little setup, you will have some integration tests that can be easily integrated with your current testing infrastructure. Also, all code from this article is available on <a href="http://github.com/just-boris/wdio-demo">Github</a>, where you can find a working project that you can clone and play around.<br><br>Good luck with testing! This thing will give more confidence that your code work as expected and you would automate that checks and will not do it manually</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc7fc3c86629" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Catching errors on Gulp.js]]></title>
            <link>https://just-boris.medium.com/catching-errors-on-gulp-js-4682eee2669f?source=rss-5e76c96bfe75------2</link>
            <guid isPermaLink="false">https://medium.com/p/4682eee2669f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[gulp]]></category>
            <dc:creator><![CDATA[Boris]]></dc:creator>
            <pubDate>Mon, 17 Aug 2015 13:13:26 GMT</pubDate>
            <atom:updated>2015-08-17T13:13:26.027Z</atom:updated>
            <content:encoded><![CDATA[<p>Watch mode is important thing of modern build systems, especially for front-end. Gulp also has this feature but with a few caveats, which makes work more difficult. This is a stream-based build system, so you have to deal with Steam API, where you must catch every error, otherwise uncaught exception will be thrown and will stop your build process.</p><p>This is especially important for watcher, because watch<em> </em>daemon lives for a long time, and that is not good when uncaught error kills it.</p><h3>What’s going on?</h3><p>First of all, we need to figure out, why it is happening, why watcher sometimes fails and dies. The recommended way to notify about occurred errors in gulp plugins is an emitting `error` event. But node.js streams, which are actually utilized in gulp, doesn’t allow to keep errors unnoticed. If there is no listeners on `error` event on some stream, in case of error an unhandled exception will be thrown. That needed to be sure that error message from stream reached its users. As the result, while working with gulp, developers often see following error in console:</p><pre>events.js:72 <br>    throw er; // Unhandled ‘error’ event</pre><p>While you are running build on Continuous-Integration sever, this behaviors can be useful, it helps to catch bugs. But this errors on local development with watcher which may be annoying, because watcher always need to be restarted.</p><h3>What to do?</h3><p>There is many discussions about that issue, for example on <a href="http://stackoverflow.com/questions/23971388/prevent-errors-from-breaking-crashing-gulp-watch">stackoverflow</a>. Also there is an<a href="https://github.com/gulpjs/gulp/issues/259"> issue on Github</a> in the gulp repo. There are proposed some solutions.</p><p>First, subscribe on error event and don’t allow to throw unhandled exception:</p><pre>gulp.task(&#39;less&#39;, function() { <br>  return gulp.src(&#39;less/*.less&#39;) <br>    .pipe(less().on(&#39;error&#39;, gutil.log))<br>    .pipe(gulp.dest(&#39;app/css&#39;));<br>});</pre><p>Then, you can use <a href="https://github.com/floatdrop/gulp-plumber">gulp-plumber</a> plugin, which suppresses default error handler for all further plugins in a <em>pipe()</em> chain</p><pre>gulp.task(&#39;less&#39;, function() {<br>  return gulp.src(&#39;less/*.less&#39;)<br>    .pipe(plumber())<br>    .pipe(less())<br>    .pipe(gulp.dest(&#39;app/css&#39;));<br>});</pre><h3>Why needed another solution?</h3><p>Despite of problem looks solved, it isn’t so. Now you will not receive any error message from build on CI-server. All errors now is being captured somewhere, so gulp thinks that all tasks has been passed right, even and some errors has occurred. Computers can’t read and understand console output, they use exit codes to tell the result of process and in that case exit code is zero which means “success”. And now we have a question how bring our error handlers back.</p><h3>Getting errors properly</h3><p>Actually, gulp can receive errors from pipeline. But only from the last one in chain, because streams designed to not propagate errors via pipes. Node.js repo has a <a href="https://github.com/nodejs/node/pull/1521">pull-request</a> with a related proposal, but it is not merged yet. So, now gulp can get only error from last stream, and usualy it is <em>gulp.dest() </em>call to write the result of task to file. But generally errors occur in other plugins between <em>gulp.src</em> and <em>dest</em>. Gulp cannot see them, but we can help him.</p><p>Gulp task function can accept not only streams as the result. We can define task in a classic node-style with callback in arguments. That function we can call manually and report erorrs from the middle pipes as well.</p><pre>gulp.task(&#39;less&#39;, function(done) {<br>  gulp.src(&#39;less/*.less&#39;)<br>    .pipe(less()).on(&#39;error&#39;, function(error) {<br>      // we have an error<br>      done(error); <br>    })<br>    .pipe(gulp.dest(‘app/css’))<br>    .on(‘end’, function() {<br>      // in case of success<br>      done();<br>    });<br>});</pre><p>That way to handle errors a bit more verbose, but correct. We can move common code in a little helper function like in <a href="https://gist.github.com/just-boris/89ee7c1829e87e2db04c">this gist</a> and then will get less code in task definition:</p><pre>gulp.task(‘less’, wrapPipe(function(success, error) {<br>  return gulp.src(‘less/*.less’)<br>    .pipe(less().on(‘error’, error))<br>    .pipe(gulp.dest(‘app/css’));<br>}));</pre><p>Now we can keep calm for our build on CI-server and enjoy local-development as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4682eee2669f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>