<?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 Anton Kravchenko on Medium]]></title>
        <description><![CDATA[Stories by Anton Kravchenko on Medium]]></description>
        <link>https://medium.com/@antosha-kravchenko?source=rss-c438afd959db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zkKovJm5fieicTTY.</url>
            <title>Stories by Anton Kravchenko on Medium</title>
            <link>https://medium.com/@antosha-kravchenko?source=rss-c438afd959db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 03:03:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@antosha-kravchenko/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[How to Integrate AWS API Gateway and AWS S3 Using AWS CDK]]></title>
            <link>https://aws.plainenglish.io/integrating-aws-api-gateway-and-aws-s3-using-aws-cdk-41118c1b01c3?source=rss-c438afd959db------2</link>
            <guid isPermaLink="false">https://medium.com/p/41118c1b01c3</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Anton Kravchenko]]></dc:creator>
            <pubDate>Sun, 12 Dec 2021 14:45:42 GMT</pubDate>
            <atom:updated>2021-12-15T03:45:57.124Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article will showcase how to integrate <a href="https://aws.amazon.com/api-gateway/">AWS API gateway</a> and <a href="https://aws.amazon.com/s3/">AWS S3 </a>using <a href="https://aws.amazon.com/cdk/">AWS CDK</a>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aUE_HWi2A19cEu8B" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>AWS CDK is a framework that allows you to describe your infrastructure as code using a programming language of your choice. It is a powerful and convenient tool that provides a lot of advantages, such as the ability to deploy the whole project&#39;s infrastructure predictably and promptly, the ability to source control your infrastructure, ability to finally have identical environments (such as dev, test, etc.) and so on.</p><p>Having worked with AWS services and CDK in particular for a while, I can tell that even though AWS provides an extreme variety of services, it sometimes gets complicated to integrate them.</p><p>Have you ever tried building something that at least remotely resembles GitLab CI using AWS CodeBuild/CodeCommit/CodePipeline? If you have, you know how complicated the setup might get when you try to wire all the services together to make them work as a single piece. AWS CDK is not an exception to that rule, and as powerful CDK is as messy working with it might get.</p><p>In particular, such a simple task as integrating a gateway with a bucket is surprisingly tricky. Even though there is an <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-s3.html">official tutorial</a> that explains in detail how to do it manually, I’ve had hard times replicating this setup in CDK as I haven’t found any complete examples on how to do it.</p><p>To fill that gap, in this article, I will show how to implement tricky integration of AWS API Gateway and AWS S3 from scratch using AWS CDK.</p><p>At first, we need to create a CDK project by running:</p><pre>cdk init app --language typescript</pre><p>If you don’t have cdk please refer to <a href="https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html">the official documentation</a> to find installation instructions.</p><p>The next step is to describe the infrastructure, namely:</p><ol><li>An S3 bucket that will be storing static assets</li><li>An API Gateway that will be exposing an endpoint that will be proxying requests to the bucket</li><li>IAM role needed for API Gateway to be able to read from the bucket</li><li>Endpoint for serving static content</li><li>Integration of S3 and API Gateway</li></ol><p>Let&#39;s start tackling it one by one:</p><ol><li>S3 bucket</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9ed9d464cc167961ac9e557aa974602/href">https://medium.com/media/c9ed9d464cc167961ac9e557aa974602/href</a></iframe><p>This is a function that creates an S3 bucket called s3-integration-static-assets.</p><p>2. API Gateway</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29adcf1398adafa0f0579f183c7e8786/href">https://medium.com/media/29adcf1398adafa0f0579f183c7e8786/href</a></iframe><p>Here we&#39;re creating an API. Pay attention to the following fields:</p><ul><li><a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html">binaryMediaTypes</a> — field that enables API Gateway to handle binary media types. If the API needs to serve anything other than a text payload, this is required.</li><li><a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-openapi-minimum-compression-size.html">minimumCompressionSize</a> — a field that enables compression of your content and specifies the minimum size of payload that has to be compressed</li></ul><p>3. IAM role</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf8d56b48e76f366cbb2d1a30bd2ffb2/href">https://medium.com/media/bf8d56b48e76f366cbb2d1a30bd2ffb2/href</a></iframe><p>This function creates an IAM role for API Gateway to read from an S3 bucket.</p><p>4. The endpoint</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30e80098b577bd0ed9c1b78c2c739f2c/href">https://medium.com/media/30e80098b577bd0ed9c1b78c2c739f2c/href</a></iframe><p>This is the definition of an endpoint that has 2 path parameters (folder which represents the name of the folder inside the S3 bucket and key which is the name of the file inside a folder), accepts Content-Type request header and attaches Content-Type to the responses.</p><p>5. API Gateway and S3 integration</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9c636bb5756258a7a2cd3c42b09d266/href">https://medium.com/media/b9c636bb5756258a7a2cd3c42b09d266/href</a></iframe><p>What’s happening here is that we take folder and key parameters from the path and use them to proxy requests to the S3 bucket.</p><pre>path: `${assetsBucket.bucketName}/{folder}/{key}`</pre><p>Also, we configure the endpoint to set Content-Type header for response based on the Content-Type of the requested file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e988f06278d31ed2507da87d38c9c769/href">https://medium.com/media/e988f06278d31ed2507da87d38c9c769/href</a></iframe><p>Now, if we collect all the pieces together we will get the following stack definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a09cf43a886e0031542782aadc8a06be/href">https://medium.com/media/a09cf43a886e0031542782aadc8a06be/href</a></iframe><p>The next step would be to deploy the stack and test it.</p><p>To deploy the stack run:</p><pre>cdk deploy</pre><p>It will synthesize the stack and ask for confirmation before proceeding with the actual deployment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xT1-1K6r-I3SSgho5TeMQQ.png" /></figure><p>Once approved, CDK will start the deployment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hstrG7Aun1_T5pJHgzbv3Q.png" /></figure><p>Once completed, CDK will give you the link to API Gateway that&#39;s been deployed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bW1V2n6VA-YJUsy22lLSKA.png" /></figure><p>This it is — as simple as that. Now we have our infrastructure deployed, and it&#39;s time to test it.</p><p>Open your management console and navigate to S3 — there will be a bucket called s3-integration-static-assets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjecdamrWY3YpdXlfFgofw.png" /></figure><p>Create a folder called static and upload your assets to that folder (in my case, I&#39;ll upload JSON, PNG, and TXT files):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CHyneW-4A42RJypgM4RHw.png" /></figure><p>The next step is to call the endpoint and verify that it serves files correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHjU6_PDgs_FIzBUx_Vj1w.png" /></figure><p>The important thing here is that thanks to the configuration done in steps 4 and 5, the gateway recognizes the content type of files it serves and sets the Content-Type header in responses accordingly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1aYJ_xwFHQN9NHSniNwBJQ.png" /></figure><p>Finally, if you want to destroy the stack run:</p><pre>cdk destroy</pre><p>and it will destroy the stack and the resources (please note that the S3 bucket has to be removed manually):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWH23e6NJcePBO0-MfdeCA.png" /></figure><p>If you’re interested in the complete working example you can find it on GitHub <a href="https://github.com/anton-kravchenko/aws-api-gateway-s3-integration-with-cdk">https://github.com/anton-kravchenko/aws-api-gateway-s3-integration-with-cdk</a>.</p><p>Thank you for reading the article and happy coding!</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41118c1b01c3" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/integrating-aws-api-gateway-and-aws-s3-using-aws-cdk-41118c1b01c3">How to Integrate AWS API Gateway and AWS S3 Using AWS CDK</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using PageObject pattern with Cypress]]></title>
            <link>https://medium.com/geekculture/using-pageobject-pattern-with-cypress-6d9907850522?source=rss-c438afd959db------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d9907850522</guid>
            <category><![CDATA[cypress-testing]]></category>
            <category><![CDATA[page-object-model]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[page-object]]></category>
            <dc:creator><![CDATA[Anton Kravchenko]]></dc:creator>
            <pubDate>Sat, 20 Nov 2021 19:02:20 GMT</pubDate>
            <atom:updated>2021-11-22T07:24:05.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1lMSZFiLIJ4_nv0z" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The article showcases how to use the <a href="https://martinfowler.com/bliki/PageObject.html">PageObject</a> pattern with <a href="https://www.cypress.io/">Cypress</a> and <a href="https://anton-kravchenko.github.io/cypress-selectors/">cypress-selectors</a>.</p><p>Page Object Model (POM) is a design pattern that aims to represent a web page as a class describing elements of that page as class fields and behavior of that page as class methods. Such class suites as both repository of web elements on the page and interface for interactions with those elements. This approach helps create an abstraction over the application&#39;s layout and encapsulates the mechanics of querying and interacting with elements behind an application-specific API.</p><p>Page Object Model pattern has many advantages:</p><ul><li>it introduces convenient abstraction for interaction with UI</li><li>it encapsulates the details of the UI structure of a page and its behavior in a single class</li><li>it enables code re-use since any page object may be used in many test cases</li><li>it simplifies tests maintenance as it is easy to locate pages and elements that need to be updated</li><li>it makes tests cases more readable and easier to understand since POM hides the complexity of querying elements behind simple high-level API</li></ul><p>POM is a widely adopted pattern, and de-facto is a standard approach for E2E testing. Even though the Selenium web testing framework has coined the pattern&#39;s name, the POM pattern can be used with other testing frameworks. In particular, I found the POM pattern helpful in tests written in Cypress, so let&#39;s discover how to use these two in conjunction.</p><p>As an application under test, I&#39;m going to use one of the implementations of the <a href="https://github.com/gothinkster/realworld">real-world app</a> called <a href="https://cirosantilli-realworld-next.herokuapp.com/">conduit</a>. It is a clone of Medium.com, where you can create an account, post a new article, view the feed, and so on.</p><p>Here are the three flows we&#39;re going to cover with tests:</p><ol><li>Login flow — user logs in to the application</li><li>Post new article flow — user logs in to the application and publishes an article</li><li>List publications flow — user logs in to the application and opens the list of articles</li></ol><p>Let&#39;s start with defining our page objects. The test cases cover five different pages, so we need to declare five classes: LoginPage,HomePage, NewArticlePage, ArticlePage and ProfilePage.</p><p>Let&#39;s start with the LoginPage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69899d74be0a2b9d7ddc5ce981722699/href">https://medium.com/media/69899d74be0a2b9d7ddc5ce981722699/href</a></iframe><p>The first class declares selectors as static fields using decorators from the <a href="https://anton-kravchenko.github.io/cypress-selectors/">cypress-selectors</a> library. emailInput and passwordInput elements will be selected by the value of the attribute type. signInButton will be pointing to the second element on the page with the text &#39;Sign in.&#39;</p><p>The second class is the page object for the Login page. It implements the only thing that can be done on that page — logging in. The reason for such separation of selectors and page behavior is that it makes it easier to re-use selectors without creating instances of page objects when it is not necessary. Your application might have &quot;global&quot; elements which are always present on the screen and represent the application&#39;s state (for example, a header that renders your information if you are logged in or a login button otherwise). In such cases, it might be a good idea to describe controls of such elements just one time and use them everywhere instead of declaring the same selectors in many classes.</p><p>Take a closer look at how the selectors from LoginPageSelectors class are being used. It is worth pointing out that even though selectors have been declared statically and are being used by reference, the actual element look-up happens <strong>right before</strong> the next command. For instance, here LoginPageSelectors.emailInput.type(email) Cypress will search for emailInput element <strong>right before </strong>executing type method.</p><p>There is a bit of trickery happening under the hood every time a selector is being used, but the only thing to know is that selector doesn&#39;t hold a reference to any particular DOM element. Instead, it queries an element and returns you a reference to aCypress.Chainable(the same way as cy.getcommand would do) every time you call it. So that the following two lines of code are equivalent:</p><pre>LoginPageSelectors.emailInput.type(email);<br>cy.get(&#39;[type=&quot;email&quot;]&#39;).type(email);</pre><p>The next is HomePage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1366de3ffa214e285878036d835514d2/href">https://medium.com/media/1366de3ffa214e285878036d835514d2/href</a></iframe><p>The approach here is the same: one class with static declarative selectors and the second one representing all interactions that can be done with the page. In this example, HomePage suites as a &#39;router,&#39; so we have three methods that take you to different pages and return instances of page objects for those pages.</p><p>The next class is NewArticlePage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64ff87e72d65ff36bcda2f241a9dacc0/href">https://medium.com/media/64ff87e72d65ff36bcda2f241a9dacc0/href</a></iframe><p>This page allows creating a new article with a title, description, content, tags, and publishing it. Please note that most of the methods return this. It allows convenient chaining in the tests when you run a couple of subsequent actions on a single page.</p><p>Last but not least, we need to declare selectors for ArticlePage and ProfilePage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99add86c8743868062c8eebb60e849bb/href">https://medium.com/media/99add86c8743868062c8eebb60e849bb/href</a></iframe><p>Now we&#39;re all set up to start implementing the tests. Let&#39;s start with the login flow. The test will open the login page, enter credentials, attempt to sign in to the application, and verify that the login has succeeded.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a50c3a0cf422327e8d86c7e904d5abf/href">https://medium.com/media/9a50c3a0cf422327e8d86c7e904d5abf/href</a></iframe><p>That&#39;s it — nice and simple. A real-world test case would be way heavier, but the idea here is that POM helps hide a lot of implementation details behind a simple interface. So when you&#39;ve finished declaring selectors for the elements and describing the behavior of your page, you can use it to define concise and readable tests. Below is the same test implemented without page object and selectors:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b371c4e32a8459722abb7e9a0d16843/href">https://medium.com/media/7b371c4e32a8459722abb7e9a0d16843/href</a></iframe><p>The test is cluttered with UI details, and it is hard to tell what it actually does. It is easier to comprehend and work with a test when it utilizes high-level domain concepts (like in our case login flow) than when it doesn&#39;t use any abstraction and queries elements by hardcoded selectors.</p><p>The next flow we&#39;re going to test if publish article flow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b94294b5bf2a0cbe2504d74a4a07793b/href">https://medium.com/media/b94294b5bf2a0cbe2504d74a4a07793b/href</a></iframe><p>This test is a little beefier — we log in, obtain a reference to the new article page object, populate the new article form with the data, publish it and finally assert that the article has been successfully posted. Even though this test is more complicated than the previous one, it remains readable and easy to comprehend.</p><p>And finally, the last test covers the profile page:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04660ff93b4a7b2eb11fe031f3284273/href">https://medium.com/media/04660ff93b4a7b2eb11fe031f3284273/href</a></iframe><p>Here we log in to the application, open the profile page, and verify that the feed of articles contains the recently published article.</p><p>As you can see from examples, POM makes life easier in many ways. After investing some time in creating page objects, you get many benefits such as high readability and lower maintenance cost.</p><p>It is worth pointing out that the POM pattern is considered an anti-pattern in Cypress. According to <a href="https://www.cypress.io/blog/2019/01/03/stop-using-page-objects-and-start-using-app-actions/">the article</a>, page objects are hard to maintain and make tests slower because they force to build the desired app state through UI instead of taking shortcuts (like modifying the app&#39;s state using <a href="https://www.cypress.io/blog/2019/01/03/stop-using-page-objects-and-start-using-app-actions/#application-actions">actions</a>). These points are valid in some cases; however, I found the POM helpful, and the benefits of using it outweigh the cost of introducing it to the project.</p><p>The repository with the complete example is available on <a href="https://github.com/anton-kravchenko/cypress-page-object-example">Github</a>.</p><p>Thank you for reading the article, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d9907850522" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/using-pageobject-pattern-with-cypress-6d9907850522">Using PageObject pattern with Cypress</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a type-safe object builder in TypeScript]]></title>
            <link>https://medium.com/geekculture/implementing-a-type-safe-object-builder-in-typescript-e973f5ecfb9c?source=rss-c438afd959db------2</link>
            <guid isPermaLink="false">https://medium.com/p/e973f5ecfb9c</guid>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[type-systems]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Anton Kravchenko]]></dc:creator>
            <pubDate>Sun, 29 Aug 2021 13:01:39 GMT</pubDate>
            <atom:updated>2022-07-16T15:20:06.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmOHozA5zVPgM4x1H6MEeQ.png" /></figure><p>This article demonstrates how flexible TypeScript’s type system is by implementing a type-safe object builder.</p><p>At first, let&#39;s discover what the builder pattern is and what purpose it serves. Builder pattern essentially allows you to separate the construction of an object from its representation. In other words, it provides a way to conveniently create instances of a particular class initialized with the data you need.</p><p>Let’s take a look at an example written in Java that uses <a href="https://projectlombok.org/features/Builder">Lookbook</a>’s @Builder annotation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/260b15ad9639478e73940e45ca04c0d9/href">https://medium.com/media/260b15ad9639478e73940e45ca04c0d9/href</a></iframe><p>ResponseEntry is a class that has two private fields and which can be initialized and instantiated as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cee3390d98f3c582e3661291c65b1f3/href">https://medium.com/media/8cee3390d98f3c582e3661291c65b1f3/href</a></iframe><p>Lombok automatically defines methods that initialize each field of your class. This approach plays very well for creating testing data because you can define instances of a class in one line.</p><p>However, this approach has one flaw — it is not fully type-safe. Even though Java is a strongly and statically typed language, there is no way to <strong>“statically”</strong> ensure that an object built via its builder won&#39;t have any uninitialized fields. Let’s take a look at an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c8ca2f2b15ba447a56a7aca975d13b6/href">https://medium.com/media/5c8ca2f2b15ba447a56a7aca975d13b6/href</a></iframe><p>Object r1has two fields initialized while r2 initializes only status field and leaves payload equal to null. As a result, we get NullPointerException at line 5 as Java has no capabilities of spotting this sort of error statically.</p><p>Java and TypeScript have entirely different type systems: the first is <a href="https://en.wikipedia.org/wiki/Nominal_type_system">nominal</a> (which allows better type-safety), and the second is <a href="https://en.wikipedia.org/wiki/Structural_type_system">structural</a> (which enables more flexibility). However, TypeScript’s type system has many unique features that make it possible to implement a type-safe version of the builder pattern free of the issue shown above and capable of spotting uninitialized data statically during compile time.</p><p>We are going to implement a type-safe version of the builder pattern with the following API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebbcd782b85832a5b23e664337d5df72/href">https://medium.com/media/ebbcd782b85832a5b23e664337d5df72/href</a></iframe><p>Here is a small demo of the result we’re going to achieve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vu4UR4NiniDShf0h5gVr0Q.gif" /></figure><p>There are a couple of things worth mentioning:</p><ul><li>method with narrows the list of keys that you can pass as the first argument based on what keys you’ve already passed to it</li><li>method with infers the type of the second argument based on the key so that for the first key “foo” it expects the second argument to be of type string, for the second bar it expects number and for the third one boolean</li><li>method build is not available unless all fields from TestEntity are initialized</li><li>the type of entity is getting inferred as TestEntity (which is the type of object that was constructed in the example)</li></ul><p>The implementation looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b52d23560c23298df08b59bc1c1248bd/href">https://medium.com/media/b52d23560c23298df08b59bc1c1248bd/href</a></iframe><p>It looks tricky, and it really is. My brain was about to start melting when I finally made it work. Let’s break down the features of TypeScript that are used in this type-safe implementation of the Builder pattern:</p><ul><li><a href="https://www.typescriptlang.org/docs/handbook/2/classes.html">Class</a> — it is a “blueprint ” for creating objects. In essence, classes are a way to store data and methods that operate that data in one “container.” In our implementation, we will define a class with a static method new that would serve as an entry point to our Builder implementation.</li><li><a href="https://www.typescriptlang.org/docs/handbook/2/generics.html">Generics</a> — this is a core feature of any statically typed language that allows writing code capable of working with multiple data types. Generics can be used with classes, functions, methods, interfaces, and type aliases.</li><li><a href="https://www.typescriptlang.org/docs/handbook/interfaces.html">Interface</a> — describes a shape/structure of classes, objects, or even functions. The primary use of interfaces is defining contracts for entities without providing implementation details so that a single interface may be implemented by a dozen of classes, each of which has its own unique behavior but conforms to the same contract.</li><li><a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html?#type-assertions">Type assertion</a> — is a way to cast a particular type to its more or less specific version. This is helpful when dealing with concepts that TypeScript is not comprehensive enough to accommodate. In other words, it helps to tell how the TypeScript’s compiler should refine certain types.</li><li><a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases">Type alias </a>— allows assigning a new name to an existing type. Also might be used for referencing <a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types">union</a> or <a href="https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types">intersection types</a>. It comes in handy when being used with the <a href="https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#the-keyof-type-operator">keyof</a> operator.</li><li><a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types">Literal type</a> — allows JavaScript literals to be used as types. Helpful when being used as a union with other literal types. That way, you can define an exact and strict list of strings or numbers that are allowed to be assigned to a particular variable.</li><li><a href="https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#the-keyof-type-operator">keyof operator</a> — takes an object type (alias or interface) and returns a string literal union of its keys.</li><li><a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype">Partial</a> utility type — takes an object type T and returns T1 where all fields are optional</li><li><a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys">Omit</a> utility type — takes an object type T and key K and removes that key from the object type</li><li><a href="https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys">Pick</a> utility type — takes an object type T and a set of keys and returns a new type by “picking up” a set of keys from T</li><li><a href="https://www.typescriptlang.org/docs/handbook/2/conditional-types.html">Conditional type</a>— this is the most complicated and hard to explain concepts of TypeScript. It allows you to declare a type that points to one of 2 other types based on the result of the condition expressed as a type relationship test. It sounds weird (and looks truly confusing), but this is the core of the implementation we’re after. In essence, this feature allows you to describe a static type in “imperative” style (the expression looks precisely as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">conditional operator</a> in JavaScript). So that type T is either type Foo or type Bar based on some condition.</li></ul><p>Now that all of the concepts are outlined, let’s break down the implementation. It has four pieces:</p><ol><li>IBuild interface</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a1e398cd38208c7135b484598526874/href">https://medium.com/media/9a1e398cd38208c7135b484598526874/href</a></iframe><p>This is the interface that describes an entity that has a method called build which returns the type Target. Our Builder class will use it to implement a method that returns a fully initialized object (with all fields set).</p><p>2. IWith interface</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2af02f075e3a2c7aa9ae8d9fb4f6cae4/href">https://medium.com/media/2af02f075e3a2c7aa9ae8d9fb4f6cae4/href</a></iframe><p>This interface has 2 type arguments: Target (this is the type of object we want to create) and Supplied (this is the object that we created so far — it is getting populated with key-value pairs from the method with. This type updates with every call to with).</p><p>The interface describes a function called with that takes two arguments: key(line 3) and value(line 4).</p><p>The first argument key has a type K that has the constraint K extends keyof T. It means that key must be a string that matches one of the fields of type Target. So if we were to build an object of type type Foo = { bar: number } the function would accept only one value as the first argument, and it would be a string “bar.”</p><p>The second argument value has type T[K]. It means that value refers to the type of data for the field K in the object T. If we were to build an object of typeFoo from the previous example, the type of the second argument would be “number” since Foo[&#39;bar&#39;] is number.</p><p>Also, the function has 2 type parameters: T and K. Type T is a type that describes the difference between type Target and type Supplied. This is important since this type defines which keys function with is going to accept. While the type Target remains the same, Supplied changes after every call to with. Take a look at the example below that shows the contents of the types Supplied after every call to with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec8c1e6db8c903e396b51b45266f7a39/href">https://medium.com/media/ec8c1e6db8c903e396b51b45266f7a39/href</a></iframe><p>As you can see Supplied type changes after every call to with function, which is why whenever with is getting called, it narrows down the list of keys allowed to be passed to the function.</p><p>Now let’s break down the most complicated piece of implementation — the return type of with function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a747c5bc9d1faf5371e6d3e057fa669/href">https://medium.com/media/1a747c5bc9d1faf5371e6d3e057fa669/href</a></iframe><p>This code implements something similar to the ternary operator in JavaScript, but it works with <strong>types</strong>. This feature is called <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types">conditional types</a>, and it lets you define a type that is selected based on your condition.</p><p>The idea here is to return type IBuild if all of the fields that should be in the object have already been supplied via the method with. Otherwise, we should return IWith.</p><p>keyof Omit&lt;Omit&lt;Target, keyof Supplied&gt;, K&gt; extends never — in this line, we check if K was the last key that should have been supplied and if it is type-safe to allow building the object via build method.</p><p>Omit&lt;Target, keyof Supplied&gt; — drops all keys of Supplied type from Target type. So if type Target = { status: number, payload: string } and type Supplied = { status: number } the result of Omit&lt;Target, keyof Supplied&gt; is { payload: string}.</p><p>keyof T extends never in our case checks whether T is a type that describes an empty object. In type T = keyof {} extends never ? true : false — T has type true because keyof {} extends neverreturns true.</p><p>It sounds tricky, but this return type basically decides whether the object has been completely built and ready to be returned via function build or it is still missing some of the fields so that function with has to be called a few more times.</p><p>3. Class Builder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6d4ce77f2767eab7f771dc9676ddffd/href">https://medium.com/media/c6d4ce77f2767eab7f771dc9676ddffd/href</a></iframe><p>This is the class that implements both of the interfaces IBuild and IWith. The implementation of both methods is <strong>dead simple.</strong> build simply returns the private field target , which is the object under construction. with takes key and value arguments and puts them to the new target object. The only thing worth taking a closer look at is line 7:</p><pre>return new Builder&lt;Target, Supplied &amp; Pick&lt;T, K&gt;&gt;(target)</pre><p>We do not re-use the single instance of the builder, but instead, we create a new one after every call to with. This is to reinitialize Builder with proper type arguments. See the breakdown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df9ec5b9edb424feb36981db5f6f3bbf/href">https://medium.com/media/df9ec5b9edb424feb36981db5f6f3bbf/href</a></iframe><p>4. Class ObjectBuilder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79afe7d46e690fcd3ed341e7bf11c6fa/href">https://medium.com/media/79afe7d46e690fcd3ed341e7bf11c6fa/href</a></iframe><p>This class is an “entry point” that hides implementation details behind a simple interface so that consumer doesn’t have to worry about initializing IWith interface with proper types.</p><p>If we finally tie all these pieces together, we will get the following logic:</p><ul><li>If all of the fields of type Target have been added via with function — useIBuild as return type. It means that method build becomes available, and we can get the object we were building.</li><li>Otherwise, return IWith which means that the object hasn’t been fully initialized, and a few more with calls are required.</li></ul><p>I’m glad if you’ve made it to the end of the article and understood the concepts I was trying to explain. These concepts are pretty complicated, and implementing the type-safe object builder pattern turned out to be a bit mind-bending.</p><p>If you’re interested in the topic, consider checking out more advanced implementation (it takes into account optional fields and more) at <a href="https://github.com/anton-kravchenko/ObjectBuilder">github.com</a>. The implementation is also available as an npm package called <a href="https://www.npmjs.com/package/typescript-object-builder">typescript-object-builder</a>.</p><p>Thank you for reading the article, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e973f5ecfb9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/implementing-a-type-safe-object-builder-in-typescript-e973f5ecfb9c">Implementing a type-safe object builder in TypeScript</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why the Prettier Code Formatter is a Big Deal]]></title>
            <link>https://javascript.plainenglish.io/why-the-prettier-code-formatter-is-a-big-deal-6c038ad75ae8?source=rss-c438afd959db------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c038ad75ae8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[prettier]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Anton Kravchenko]]></dc:creator>
            <pubDate>Wed, 07 Jul 2021 01:17:18 GMT</pubDate>
            <atom:updated>2021-07-07T01:17:18.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zZU3cptbCWb-CnG7" /><figcaption>Photo by <a href="https://unsplash.com/@possessedphotography?utm_source=medium&amp;utm_medium=referral">Possessed Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Prettier is a <strong>big deal </strong>(as is any other robust code formatter for that matter). This article will showcase why it is so essential and how to introduce it to an existing codebase.</p><p>If you have never heard of automatic code formatters before — these are tools that parse your code, transform it into <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">AST</a>, and then “re-print” it in a nice way. The primary purpose of this process is to ensure that all code in your codebase follows the same styling <a href="https://standardjs.com/rules.html">rules</a>.</p><p>So, no matter how many quotes you use to define string or whether you put semicolons at the end of each line — the code formatter has its own opinion on how your code should look.</p><p>At first glance, it may seem to be a disadvantage — you, as the author of your code, know better where to put an extra newline to emphasize that certain pieces of code are related or when an arrow function should be defined in one line (even though it is 300 symbols long).</p><p>However, the problem is that everyone has an opinion on how code should look, and at times it may be tough to find a common denominator on code styling perspective.</p><p>Moreover, when you are sending a pull request for review and your teammate leaves one hundred nit-picky code-style comments which, to his best knowledge, must be addressed (because otherwise, the code would be unreadable and “ugly,” right?) — you spend time for nothing while adding semicolons, putting newlines between methods, and so on.</p><p>We are facing 2021, and I still see fellow C coders who are endlessly surfing through the giant proprietary “C code style document” trying to find/learn tons of styling rules. Of course, the major part of these rules has nothing to do with the concerns like the number of spaces in the tab. Still, I spend way more time on addressing tons of dummy “remove this new line,” “add one more space here” comments than I care to admit.</p><p>I used to be a C developer on a giant (10M LOC) set-top box project hosted in Clearcase. We had to follow huge and pretty well-defined coding standard. The main problem was that we didn’t have the tools to enforce rules automatically, so “surfing the document” was an integral part of our development and code review processes. We could have benefited a lot if we had a tool that would enforce all those rules automatically, but unfortunately, there was no such tool around back then.</p><p>Nowadays, the cool kids do not want to invest their time learning code-style documents (especially writing them), so now we have tools (like Prettier) that take code styling off our shoulders and let us focus on more meaningful things. So let&#39;s discover why automatic code formatting is a good thing and what exactly it buys you.</p><h4>1. Code-style consistency</h4><p>If I were to compile the list of things that drastically commit to the quality of a codebase, one of them would be <strong>consistency</strong>.</p><p>Have you ever worked on multiple projects simultaneously that incorporate different code styles? I bet you have, and you know how frustrating it is having to adapt to different rules and patterns every time you need to make a change. Consistency is what makes code easier to read and work with.</p><p>From my experience, I know that no matter how hard you try, you are unlikely to have a code-style consistent codebase without automation. I have seen such attempts many times, and the result is always the same — inconsistent changes inevitably sneak in and get spread across the whole codebase.</p><p>The only working way to truly gain code-style consistency is to have a robust code formatter re-style your code every time you make a change. Doing that ensures that every line of the codebase follows the same styling rules as all other lines.</p><h4><strong>2. Single source of truth</strong></h4><p>There was one time when I got into a very awkward situation with one of my colleagues. I was doing a code review of his pull request and came across two following lines of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b71cc46997d1353b77000e3ae1bc02e/href">https://medium.com/media/0b71cc46997d1353b77000e3ae1bc02e/href</a></iframe><p>The length of the first one is <strong>205 characters, </strong>and the second one is <strong>304</strong>. I could not believe those two lines had made their way to the code review — why would anyone write a line of code that occupies three full widths of a screen on a computer? It is very complicated to figure out what this code accomplishes. Moreover, the longer the line of code, the easier it is for bugs to sneak in, isn’t it? So my reaction was obvious — I suggested splitting the lines to make the code more readable. It turned out that the author of those two lines had a completely different opinion on that matter —we’ve had a pretty heated discussion on that topic, and he was arguing that he intentionally made those lines huge to hide the initialization logic. Well, it does sound somewhat reasonable, but there was another problem with those lines that became very obvious once we formatted them. Following is precisely the same code, but formatted via Prettier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/118f26b8c0b64a7260c8b88724908b6e/href">https://medium.com/media/118f26b8c0b64a7260c8b88724908b6e/href</a></iframe><p>The difference is drastic. When you read code formatted like this, it becomes crystal clear that it is cumbersome and not optimal. It reads start_time variable over and over again (while it could have been read once and stored to a variable), it needlessly creates new instances of moment and finally, it repeats itself. In this case, code formatting not only made the code more readable but also “highlighted” the flaws.</p><p>I must admit — having this discussion was not the most pleasant thing. We’re all professionals, and most of us love what we do. We get emotionally attached to the code we’re writing, and because of that, we become biased. Sometimes, people have so different visions/amounts of experience/background, that it is almost impossible to find common ground. In addition to that, code style is a matter of taste (at least to some extent), and it is not always feasible to justify the things like spaces vs. tabs, two vs. four spaces in a tab, one vs. two new lines between methods in a class and so on. Moreover, even if you did come up with a well-defined and thorough code style standard — how would you enforce it consistently?</p><p>This is where automatic code formatting shines — you always get consistently formatted codebase no matter what. And, of course, this puts an end to eternal debates on styling. Every code style decision is up to a heartless computer that does its job perfectly and, most important, consistently and deterministically.</p><h4>3. No syntax errors</h4><p>Code formatter reads your code (transforms it into <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">AST</a>) before executing its magic. If it encounters a syntax error at this step, the process fails, and you get notified about that. So, if your code formatting is getting triggered by pre-commit of pre-push git hook, you will not be able to push that code at all (which is nice because you definitely don’t want to be the one who broke the build of your app).</p><h3>Adoption strategies</h3><p>If you decide to incorporate automatic code formatting into your development process, there are a couple of ways to do it.</p><h4>1. “Big bang” approach</h4><p>The easiest way is to reformat the whole codebase at once. The steps would be the following:</p><ul><li>install Prettier ( npm install --save-dev --save-exact prettier)</li><li>configure Prettier (via .prerttierrc file or configuration in package.json file)</li><li>add format command into your package.json:&quot;format&quot;: &quot;prettier --write \&quot;src/**/**.ts\&quot; \&quot;test/**/*.ts\&quot; &quot;</li><li>run npm run format</li><li>install pre-commit as described <a href="https://prettier.io/docs/en/precommit.html">here</a> (so that all the staged files get formatted before commit)</li></ul><p>And voila — the whole codebase will have been reformatted at once.</p><p>The downsides of this approach are apparent:</p><ul><li>most of the lines of the codebase will be shown as authored by you (I suspect this may be an issue for enterprise-grade projects that are at the maintenance only stage)</li><li>your colleagues may face challenges while pulling the main branch after reformatting (although they can perform the same steps above to preserve their delta and avoid merge conflicts)</li><li>it may be hard to convince your managers that your pull request (with N hundreds of reformatted files) will not introduce any issues.</li></ul><p>In my career, I’ve executed this approach four times on different-size projects (from 10K to 100K LOC). All four times went relatively smoothly — I had to spend some time convincing my peers, but after incorporating Prettier, everybody was happy.</p><h4>2. File-by-file reformatting</h4><p>If you can’t go for the “all at once” approach, you can try to reformat your codebase on a file-by-file basis. The steps would be the same as for the previous approach except for executing format command. The workflow would be the following: make your changes, commit them and let pre-commit hook do the job of reformatting all the staged files.</p><p>Although this approach may lead to a very long migration process, it has some advantages:</p><ul><li>this approach helps to avoid having to review a huge PR that comes with approach #1</li><li>if you don’t fully trust Prettier, you will have a chance to review every single change it made during the code review process</li></ul><h4>3. Format only changed lines</h4><p>If the two approaches above do not fit your use case, if you can’t afford pollution of git history, or if you’re looking for the least disruptive way of migration, you can consider setting up a pre-commit hook that will be formatting only changed lines of code. It can be done by setting up <a href="https://github.com/nrwl/precise-commits">precise-commits</a> that uses Prettier’s <a href="https://prettier.io/docs/en/options.html#range">range</a> option.</p><p>The advantages of this approach are the following:</p><ul><li>it avoids pollution of git history (since only changed LOC are getting formatted)</li><li>it avoids huge initial PR that comes with “all at once” approach</li></ul><p>The disadvantages are obvious — long migration process and inconsistency between “new formatted” and “old” code. However, this approach is perfect if you’re working on an enterprise codebase (or monorepo), where git history matters.</p><p>Thank you for reading this article. Feel free to share your thoughts in the comments, and happy coding!</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c038ad75ae8" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/why-the-prettier-code-formatter-is-a-big-deal-6c038ad75ae8">Why the Prettier Code Formatter is a Big Deal</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deal with Selectors in Cypress]]></title>
            <link>https://javascript.plainenglish.io/dealing-with-selectors-in-cypress-8b9ac0dfe240?source=rss-c438afd959db------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b9ac0dfe240</guid>
            <category><![CDATA[page-object]]></category>
            <category><![CDATA[cypress-selectors]]></category>
            <category><![CDATA[cypress]]></category>
            <dc:creator><![CDATA[Anton Kravchenko]]></dc:creator>
            <pubDate>Thu, 14 Jan 2021 18:52:09 GMT</pubDate>
            <atom:updated>2021-07-06T14:16:23.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uSGH2rxIyCIWh652" /><figcaption>Photo by <a href="https://unsplash.com/@alanveob?utm_source=medium&amp;utm_medium=referral">Aleksey Boev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It’s been a while since I started using Cypress, and I haven’t found much information regarding working with selectors.</p><p>Cypress documentation doesn’t go beyond <a href="https://docs.cypress.io/guides/references/best-practices.html#Selecting-Elements">advising</a> usage of “stable” attribute selectors over brittle CSS selectors and doesn’t suggest ways of organizing and reusing selectors.</p><p>The purpose of this article is to fill that gap and to discover what options are available so far.</p><p><strong>0. Using hardcoded selectors</strong></p><p>The easiest way for working with selectors is to hardcode them all over the place.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b007ff3bdcce771ed0eb390ef38e657/href">https://medium.com/media/6b007ff3bdcce771ed0eb390ef38e657/href</a></iframe><p>It is needless to say that this is not the best way of handling selectors because:</p><ul><li>you can’t reuse selectors hardcoded in your test code</li><li>if a selector breaks, you need to update all of the occurrences of that selector in your test code</li><li>a selector may not represent which exactly element it locates (e.g. div &gt; .item doesn’t provide any clue about the purpose of an element it queries)</li></ul><p>Given all shortcomings of that approach, I would say this is the least preferable way of working with selectors.</p><p><strong>1. Storing selectors in constants</strong></p><p>The apparent improvement to approach <strong>#0</strong> would be to store your selectors in constants and then use them by reference— this is the easiest way to reuse selectors:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c8286a8da65d13e608ea9ea697d1f22/href">https://medium.com/media/7c8286a8da65d13e608ea9ea697d1f22/href</a></iframe><p>We could even add those selectors to some object (namespace?) to emphasize that those selectors are closely related, and then use them by accessing our “namespace” of selectors for a particular page/widget:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbef15c8188d1c1d5ace7138ec44ec7b/href">https://medium.com/media/dbef15c8188d1c1d5ace7138ec44ec7b/href</a></iframe><p><strong>Pros:</strong></p><ul><li>such selectors can be reused (just access any of your selectors by a reference)</li><li>if a selector is named correctly, it is easy to understand what is a function/purpose of an element it points to</li><li>if a selector breaks, you need to fix it only in one place</li></ul><p><strong>Cons:</strong></p><ul><li>while it is possible to define a “compound” selector that queries one element inside another one (e.g., children element inside the parent element), it is a bit cumbersome and inconvenient:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fa33d4bc41a703cd4ef1e67c3a7aa24/href">https://medium.com/media/2fa33d4bc41a703cd4ef1e67c3a7aa24/href</a></iframe><p><strong>2. Defining a custom function for selecting elements</strong></p><p>Suppose you are lucky enough to have access to a codebase of an application under test. In that case, you can add test attributes to elements you want to interact with and then define a custom command that would query those elements using a test id like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3cb6e9abfa07f0582a0abd0b4585cf9/href">https://medium.com/media/b3cb6e9abfa07f0582a0abd0b4585cf9/href</a></iframe><p>Also, you can let TypeScript know (if you use it) that Cypress API has been extended:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80891a9c5956e562dab7de4acd97b997/href">https://medium.com/media/80891a9c5956e562dab7de4acd97b997/href</a></iframe><p>Now by utilizing that custom command, we can reuse our selectors by extracting them to separate functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f04afddb0f3ad90034cc756d191482e/href">https://medium.com/media/4f04afddb0f3ad90034cc756d191482e/href</a></iframe><p>Our test then will look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/677f928c274540f6f1737f9bdc917243/href">https://medium.com/media/677f928c274540f6f1737f9bdc917243/href</a></iframe><p>Since the command that we’ve defined supports “relative” selectors, we can also search elements inside other elements:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1c7efe44fb523996a61793f8746d43f/href">https://medium.com/media/f1c7efe44fb523996a61793f8746d43f/href</a></iframe><p>It is worth noting that this approach may lead to flaky tests (in rare cases). The thing is, <a href="https://docs.cypress.io/guides/core-concepts/retry-ability.html#Only-the-last-command-is-retried"><strong>Cypress commands only retry the last command before the assertion</strong></a>. In practice, it means that if you have a bunch of nested find commands like in the example below</p><pre>cy.get(&lt;root&gt;).find(&lt;parent&gt;).find(&lt;children&gt;).shold(&lt;assertion&gt;)</pre><p>and your assertion is failing, Cypress will retry only the last command before the assertion (.find(&lt;children&gt;) from the example above). So if the first find command (.find(&lt;parent&gt;) ) got executed against the wrong parent element, your test would fail. See <a href="https://docs.cypress.io/guides/core-concepts/retry-ability.html#Only-the-last-command-is-retried">the official documentation </a>for a detailed explanation for this behavior.</p><p>It is also worth noting that I’ve seen that case happening only two times over the 200+ E2E test, and those two tests were failing only in a CI container (exactly as mentioned in the article).</p><p>The pros and cons of this approach are pretty much the same as for the previous one:</p><p><strong>Pros:</strong></p><ul><li>this approach lets you define your selectors once and then use them just by calling a function that queries your elements</li><li>if your “selector functions” are named correctly, it is easy to infer what elements they return</li><li>if a selector breaks, there is only one place that requires a fix</li></ul><p><strong>Cons:</strong></p><ul><li>this approach works 99% of the time, but still, you may encounter unpleasant flakiness in some cases</li></ul><p>I’ve been using that approach for a long time, but it didn’t seem to be the best solution because there is a chance of introducing a flaky test (even though it is shallow), and the test code that uses functions for selecting elements seems to be a bit cumbersome.</p><p><strong>3. Storing selectors in PageObjects</strong></p><p>Yeah, I know, the Cypress team considers <a href="https://martinfowler.com/bliki/PageObject.html">PageObject</a> to be an anti-pattern, and according to the <a href="https://www.cypress.io/blog/2019/01/03/stop-using-page-objects-and-start-using-app-actions/">article</a>, you should avoid using it. The reasoning is that PageObject pattern “introduces another layer of indirection” and prevents you from testing your features in “isolation”. While those are valid points, “testing in isolation” is not something that I need most of the time. Instead, I prefer testing complete flows that cover multiple pages, and this is where PageObject pattern comes in handy. I think that the pattern helps to organize and reuse selectors (among a few other things).</p><p>As far as I know, it is a common technique in Java&#39;s “automation world” to store selectors in classes/interfaces and define them declaratively using annotations. The following is an example of code that uses <a href="https://github.com/qameta/atlas">atlas</a> selectors:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd7e3e63aebdbe43c0ffeda3e08e4182/href">https://medium.com/media/fd7e3e63aebdbe43c0ffeda3e08e4182/href</a></iframe><p>I have not found any libraries that would allow doing something similar in Cypress, so I have written my own one. It is called <a href="https://www.npmjs.com/package/cypress-selectors">cypress-selectors</a>, and it enables you to define your selectors declaratively (exactly like in the example above).</p><p>Let’s take a look at examples. At first, let&#39;s define a class and define our selectors declaratively:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5522e8d0bd53fc9fe5f28b9c9ab96b7b/href">https://medium.com/media/5522e8d0bd53fc9fe5f28b9c9ab96b7b/href</a></iframe><p>Next, let’s use these selectors in our “sample” test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeee7e73e79548249e644fb15c973a64/href">https://medium.com/media/aeee7e73e79548249e644fb15c973a64/href</a></iframe><p>As you can see, you can query elements just by accessing members of a class — as simple as that.</p><p>The library allows selecting elements by attribute, class, id, xpath, type and jQueryselector .</p><p>It also supports querying elements inside another element (compound selectors):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33f6371458ecb0044d8d3488f16548f7/href">https://medium.com/media/33f6371458ecb0044d8d3488f16548f7/href</a></iframe><p>As you can see in the example above, you can assign an “alias” to an element and then refer to it in another selector to specify its parent.</p><p>In addition to “pros” from approaches #1 and #2 that one has several more:</p><ul><li>this approach allows you to define selectors declaratively</li><li>you can query elements just by accessing members or your PageObject classes</li><li>it is easy to specify a “parent” of a selector</li><li>this approach is free of the issue described in approach #2 — the library doesn’t build a chain of find commands, but instead, it merges queries<a href="https://docs.cypress.io/guides/core-concepts/retry-ability.html#Merging-queries"> as suggested by the docs</a>.</li></ul><p>I’ve been using that approach for the last couple of months on my projects, and I’m satisfied with the results — the test code is concise and readable. Among all four approaches described above, this one seems to be the most optimal for me. Check out the documentation to find out more about the library <a href="https://anton-kravchenko.github.io/cypress-selectors/">https://anton-kravchenko.github.io/cypress-selectors/</a>.</p><p>Every approach has its own merits, and it is up to you to decide what works for you best. Feel free to share your thoughts in the comments, and happy coding!</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b9ac0dfe240" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/dealing-with-selectors-in-cypress-8b9ac0dfe240">How to Deal with Selectors in Cypress</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>