<?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"><channel><title><![CDATA[Tally's Blog]]></title><description><![CDATA[Tally's Blog]]></description><link>https://tallybarak.com</link><generator>RSS for Node</generator><lastBuildDate>Sat, 14 Nov 2026 14:44:05 GMT</lastBuildDate><atom:link href="https://tallybarak.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Common Questions About Software Testing]]></title><description><![CDATA[Recently, I was approached by an automation developer who was considering transitioning from Cypress to Playwright (smart developer!), asking me for some…]]></description><link>https://tallybarak.com/common-questions-about-software-testing</link><guid isPermaLink="true">https://tallybarak.com/common-questions-about-software-testing</guid><category><![CDATA[playwright]]></category><category><![CDATA[test-automation]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Wed, 30 Oct 2024 19:21:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/9SKhDFnw4c4/upload/9f52477cad4049ab2a66fcc7b34521be.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recently, I was approached by an automation developer who was considering transitioning from Cypress to Playwright (smart developer!), asking me for some advice on the transition. He shared a set of questions, and as those were pretty generic, I took the freedom to write a blog post with my responses.</p>
<p>Note of caution: this is opinionated and based on my experience; however, it is never a one-size-fits-all thing, and the suggestions here may not fit you.</p>
<h3 id="heading-what-is-the-best-way-to-use-locators-selectors-by-data-test-id-attributes-or-something-else">What is the best way to use Locators (selectors) by data-test-id attributes or something else?</h3>
<p>Playwright documentation says:</p>
<blockquote>
<p><em>Automated tests should verify that the application code works for the end users, and avoid relying on implementation details[…]. The end user will see or interact with what is rendered on the page, so your test should typically only see/interact with the same rendered output.</em></p>
</blockquote>
<p>I completely agree with this approach. User-facing selectors should be priority number one. That is getByText, getByLabel etc. followed by semantic HTML selectors (i.e. getByRole), and then CSS selectors.</p>
<p>Test-id attributes are not that useful in most cases. First, they require duplicate work on the development side, to define and maintain the ids. Also, they are prone to errors, as the developer might change the functionality and forget to update the ids, hence causing tests to fail for no reason, or worse - false positive tests.</p>
<p>User-facing selectors also include things like: <code>my-icon[name=”trash”]</code>; while the user does not actually see the name of the icon, we can assume that the name depicts some real visual.</p>
<p>Fun story: we had a set of actions that were dynamically generated based on attributes of the entity (think about Gmail mail actions icons): One of our tests was clicking on a locator similar to the above. Lol and behold, the trash icon was used for two separate actions, both showing on the same icon toolbar. Thanks to Playwright locator strictness, the test failed because of duplicate icons. Not only the test identified a logical bug, but also a UX bug!</p>
<h3 id="heading-whats-the-best-way-to-share-these-selectors-between-repos">What’s the best way to share these selectors between repos?</h3>
<p>Tests are code, and as such they should be shared like any other code. That could be via packages or by using a monorepo.</p>
<p>Selectors that need to be shared are likely related to some production code that is also shared between repos, and therefore the best method is to follow the same practice used to share the code. If the code is shared via packages, testing utilities (sometimes called test drivers) can be added to the same package, thus ensuring good versioning practices. Any change to the code will also include the changes to the relevant test code.</p>
<h3 id="heading-we-thought-about-using-the-pom-model-does-it-mean-that-we-should-use-class-structure-or-can-it-be-used-with-functional-code-as-well">We thought about using the POM model, does it mean that we should use class structure or can it be used with functional code as well?</h3>
<p>The POM model is inherited from strongly typed Object-oriented languages (read: Java). when using dynamic functional languages such as Javascript/Typescript, a functional approach is preferred. You can simply export simple functions that abstract repetitive functionality.</p>
<p>Having said that, you can still use POM in JS(TS) by defining classes and instantiating them with a page, and creating high-level functions. You can see an example in <a target="_blank" href="https://playwright.dev/docs/pom">Playwright's documentation</a>.</p>
<p>Moreover, with Playwright capabilities, you will find that in most cases high-order abstraction is not really required. Unlike the glory days of Selenium where you had to wrap a lot of low-level browser access APIs to make them stable, this is not required in Playwright, and you might find yourself writing tons of one-liner functions.</p>
<p>Last, but not least at all, the term POM itself refers to the days where we wrote web applications with pages. Most modern frameworks are now components based, so we should rethink our POMs as COM (Component Object Model). Assume you have some fancy date and time picker that is used in multiple places in your application, it makes more sense to abstract the selection of the data at the component level and not at the page level.</p>
<h3 id="heading-as-of-now-we-have-a-constants-file-separated-from-the-testlogic-file-we-have-a-lot-of-selectors-whats-the-best-way-to-manage-them">As of now, we have a constants file separated from the test/logic file, we have a lot of selectors- what’s the best way to manage them?</h3>
<p>In general, I am completely against kitchen sink code files. Code (and constants are code) should be split by concerns. Constants code should be kept next to the functionality they serve. Export whatever is needed from the relevant context.</p>
<h3 id="heading-is-there-a-preferred-way-to-generate-and-send-data-to-the-db-before-the-test-is-it-crucial-to-clear-db-between-suites">Is there a preferred way to generate and send data to the db before the test? Is it crucial to clear db between suites?</h3>
<p>Test data management is a huge topic. But to keep it short: yes. Your test should be isolated in every possible way. It should not rely on another test to run before, and it should explicitly define any data or dependencies it requires.</p>
<p>The best way to generate data is using your application APIs, if such exist. You can use Playwright Context to call those APIs. Axios is another very popular API calling library. While using Playwright is straight-forward, I found that Axios built-in interceptors can be extremely useful when calling APIs.</p>
<p>If you cannot generate data by calling APIs, use any library that fits your database to insert data directly into the DB.</p>
<p>You may or may not delete your data, as long as the data for your test is completely segregated, in order not to pollute your test or other tests.</p>
<p>Let’s take an example: your test starts with the user creating an order. Then the user views its orders and verifies it has 1 order. If your data is shared between multiple tests that are running in parallel, the user may see multiple orders which makes the test unstable. A possible solution is for each test to create a dedicated user that will be used by the test (generate usernames dynamically based on some random string) and then each user will only have the orders relevant to the test. At the end of the test it is recommended to delete the specific test data. However, it is not required, as the data will not be visible to other tests that are not reusing the same user. However, it might be a good idea to delete the data, especially if your tests are running in large volumes to avoid performance issues on the DB. A method that I found useful is to create the data for each test. Successful tests delete their data, while failing test keep the data to allow for interrogating the failure. A weekly process is resetting the whole DB so we do not end up with high (and costly) volumes.</p>
]]></content:encoded></item><item><title><![CDATA[The UI Testing Panorama: From E2E to Isolation and Everything in Between]]></title><description><![CDATA[In today's digital landscape, user interfaces have evolved far beyond simple forms and basic interactions. Modern UIs are rich tapestries of intricate…]]></description><link>https://tallybarak.com/the-ui-testing-panorama-from-e2e-to-isolation-and-everything-in-between</link><guid isPermaLink="true">https://tallybarak.com/the-ui-testing-panorama-from-e2e-to-isolation-and-everything-in-between</guid><category><![CDATA[Testing]]></category><category><![CDATA[playwright]]></category><category><![CDATA[Cypress]]></category><category><![CDATA[selenium]]></category><category><![CDATA[E2E]]></category><category><![CDATA[Storybook]]></category><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Sat, 22 Jun 2024 14:33:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/qWwpHwip31M/upload/5d252fe851c637cddf2e4148953c800a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today's digital landscape, user interfaces have evolved far beyond simple forms and basic interactions. Modern UIs are rich tapestries of intricate interactions, micro-animations, advanced gestures, and media-rich content. As users demand smooth, responsive experiences across a multitude of devices and screen sizes, the importance of robust UI component testing has skyrocketed.</p>
<p>This article explores six distinct methods for testing UI components, each with its own strengths and challenges. We'll delve into the practical aspects of each approach, discussing how to implement them and the tools that make them possible.</p>
<p>This diagram helps you in navigating between the different options, and understand the decisions you need to make when you select one or more options for your UI testing:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720630212788/8628a992-8158-4305-9e80-6ccf71eb12f6.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-1-the-classic-approach-testing-ui-components-as-part-of-e2e-testing">1. The Classic Approach: Testing UI Components as Part of E2E Testing</h2>
<p>End-to-end (E2E) testing has long been the gold standard for UI testing, often sitting at the apex of the testing pyramid. This method aims to replicate the user's experience as closely as possible, testing the entire system from front to back.</p>
<p>To implement E2E testing, you'll need to set up your entire application stack, including backend services and databases, mirroring your production environment as closely as possible. Tools like Selenium, Playwright, or Cypress are your go-to for automating browser interactions. These powerful tools allow you to script user flows, mimicking real-world usage scenarios. Playwright and Cypress come with their own test runners, while a vast number of options exist when using <a target="_blank" href="https://www.selenium.dev/">Selenium</a>, like <a target="_blank" href="https://webdriver.io/">Webdriverio</a> or <a target="_blank" href="https://nightwatchjs.org/">NightWatch</a>.</p>
<p>E2E tests shine in their comprehensiveness. They validate the entire system, from UI to backend, providing a high level of confidence in your application's functionality. They're particularly adept at uncovering integration issues that might slip through the cracks of more focused testing methods.</p>
<p>However, this approach is not without its challenges. E2E tests can be time-consuming to set up and run, often requiring significant computational resources. They can also be fragile, breaking due to changes in any part of the system. As your application grows, maintaining E2E tests can become increasingly complex, potentially slowing down rapid development cycles.</p>
<h2 id="heading-2-the-lightweight-alternative-testing-ui-components-with-a-mock-browser">2. The Lightweight Alternative: Testing UI Components with a Mock Browser</h2>
<p>For teams looking for a faster, more lightweight approach to UI testing, mock browser environments like <a target="_blank" href="https://github.com/jsdom/jsdom">jsdom</a> or <a target="_blank" href="https://github.com/capricorn86/happy-dom">Happy DOM</a> offer an intriguing alternative. These tools provide JavaScript implementations of web standards, allowing you to render and interact with UI components in a Node.js environment.</p>
<p>To get started with this approach, you'll set up a mock browser environment in your Node.js context. Jest or Vitest serve as excellent test runners, while Testing Library provides utilities for interacting with your rendered components. You'll write tests focusing on component logic, structure, and basic DOM interactions.</p>
<p>The perceived speed of this method can be misleading. While tests initially appear to run lightning-fast compared to full-browser tests due to the absence of browser launch time, this advantage can diminish with complex scenarios. For instance, when dealing with a large DOM, style calculations performed in JavaScript rather than native browser code can significantly slow down the tests. It's worth noting that modern tools like Playwright have evolved to keep browsers running between test executions, providing very fast feedback that can rival or even surpass mock browser environments in certain situations. Despite these considerations, mock browser tests remain lightweight and are particularly easy to integrate into continuous integration pipelines, making them a valuable tool in many development workflows.</p>
<p>However, this approach has its limitations. Mock browsers don't perfectly replicate all browser behaviors, especially when it comes to rendering and layout. You won't be able to test visual appearance or catch browser-specific issues. Complex user interactions and advanced CSS features may also be challenging to test accurately. Moreover, browser mocking often falls short when it comes to specialized functionalities like canvas operations or media loading lifecycle events, which are crucial for many modern web applications.</p>
<h2 id="heading-3-the-hybrid-solution-testing-ui-pages-with-data-mocking-and-browser-automation">3. The Hybrid Solution: Testing UI Pages with Data Mocking and Browser Automation</h2>
<p>This method strikes a balance between realism and control, running your front-end application in a real browser while mocking backend APIs. It's an excellent choice for teams who want to focus on UI behavior without the complexity of managing a full backend environment.</p>
<p>To implement this approach, you'll run your front-end application in a real browser environment. Tools like <a target="_blank" href="https://mswjs.io/">Mock Service Worker</a> (MSW) come in handy for intercepting and mocking API requests. You'll then use browser automation tools like <a target="_blank" href="https://playwright.dev/">Playwright</a> or <a target="_blank" href="https://www.cypress.io/">Cypress</a> to simulate user interactions and verify UI behavior.</p>
<p>This method offers the best of both worlds: the high fidelity of a real browser environment and the control of mocked data. It's particularly useful for testing various data scenarios, including edge cases and error states. Cross-browser testing becomes more manageable, and you can implement visual testing through screenshot comparisons.</p>
<p>The main challenges of this approach are multifaceted. Firstly, the setup is complex, requiring configuration of both browser automation and API mocking tools. Once set up, maintaining the mocks becomes an ongoing task; you'll need to keep them updated as your backend evolves. Browser automation itself can be finicky, often encountering timing issues that lead to flaky tests, especially for complex UI interactions. Performance can also be a concern: testing specific components may be slow if numerous steps are required to access them, and system processing can cause unexpected delays, resulting in long loading times even when attempting to access components directly. These challenges require careful consideration and ongoing attention to ensure effective and reliable UI testing.</p>
<h2 id="heading-4-the-isolation-technique-testing-components-in-real-browsers">4. The Isolation Technique: Testing Components in Real Browsers</h2>
<p>Component isolation testing allows you to focus on individual UI elements, from small widgets to full pages, rendering them independently in a real browser environment. This approach is particularly valuable for teams working with reusable component libraries.</p>
<p>For this method, you'll use a tool like <a target="_blank" href="https://storybook.js.org/">Storybook</a> to isolate and render your UI components in a browser. You can then employ browser automation tools to interact with and test these isolated components. This setup allows for thorough testing of individual components across different states and scenarios.</p>
<p>The beauty of this approach lies in its focus and reusability. You can test components thoroughly without the complexity of the entire application. It's faster than full application testing and makes debugging straightforward, as it is clear which component is malfunctioning. As an added bonus, your isolated component showcase can serve as living documentation for your UI library.</p>
<p>While this approach offers many benefits, it's not without its challenges. The primary drawback is the limited real-world context; testing components in isolation may miss issues that only surface when components interact within the full application environment. This includes potential discrepancies between isolated behavior and behavior in the complete app, limited ability to test complex component interactions, and difficulty in simulating all possible states a component might encounter in real usage. Additionally, there's extra development effort required to set up the isolation environment, which can be particularly challenging for components deeply integrated into the application. Maintenance becomes another consideration; as components evolve, you'll need to keep the isolation setup updated, which can be time-consuming. Lastly, while individual components may work flawlessly in isolation, this approach doesn't guarantee seamless integration in complete user journeys, potentially leaving gaps in your testing coverage.</p>
<h2 id="heading-5-the-newcomer-cypress-and-playwright-component-testing">5. The Newcomer: Cypress and Playwright Component Testing</h2>
<p>Cypress and Playwright, traditionally known for E2E testing, have recently introduced component testing features. This approach allows you to render and test UI components in isolation directly in the browser as part of the test execution.</p>
<p>To use this method, you'll leverage the component testing features of <a target="_blank" href="https://docs.cypress.io/guides/component-testing/overview"><mark>Cypress</mark></a> or <a target="_blank" href="https://playwright.dev/docs/test-components">Playwright</a>. These tools allow you to render components in isolation during test execution and interact with them using their powerful APIs. You'll write tests that focus on component behavior, leveraging the full capabilities of these robust testing frameworks.</p>
<p>This approach combines the benefits of component isolation with the power of established E2E testing tools. You get a real browser environment, fast execution, and powerful debugging capabilities. It's particularly appealing for teams already using these tools for E2E testing, as it allows for a unified testing approach.</p>
<p>The main challenges stem from the relative newness of these features. They may lack some advanced capabilities found in more established component isolation tools such as Storybook. There can also be a learning curve for teams not familiar with these frameworks, and you might face some limitations in styling and state management compared to your full application environment.</p>
<h2 id="heading-6-the-all-in-one-approach-storybook-test-function">6. The All-in-One Approach: Storybook Test Function</h2>
<p>This method leverages <a target="_blank" href="https://storybook.js.org/docs/writing-tests/test-runner">Storybook's built-in test function</a>, allowing you to write and run tests directly within your Storybook environment. You'll create stories for your components as usual, then add test functions to these stories to verify their behavior.</p>
<p>Using Storybook for both component development and testing offers a streamlined workflow. It provides all the advantages of isolated component testing while keeping everything within a single, familiar tool. Your tests run in the same environment where you develop and showcase your components, ensuring consistency.</p>
<p>However, this approach isn't without its limitations. Storybook's test function uses <a target="_blank" href="https://testing-library.com/">Testing Library</a> under the hood, which, while excellent for many scenarios, may not fully replicate real browser behavior for more complex interactions. Additionally, the structure of having a single test function per story can lead to less flexible test organization. You might find yourself creating "dummy" stories solely for the purpose of testing, which can clutter your Storybook.</p>
<h2 id="heading-conclusion-crafting-your-ui-testing-strategy">Conclusion: Crafting Your UI Testing Strategy</h2>
<p>As we've explored, each approach to UI component testing has its strengths and challenges. The best choice depends on your specific needs, resources, and the nature of your application. Often, a comprehensive testing strategy involves a combination of these methods.</p>
<p>You might use isolated component testing with Storybook for rapid development and feedback, combine it with Cypress or Playwright component tests for more integrated scenarios, and cap it off with a suite of E2E tests using Selenium or Playwright for critical user journeys.</p>
<p>Remember, the goal of UI component testing is twofold: to ensure a smooth, bug-free experience for your users, and to maintain developer productivity. By understanding these different approaches and leveraging the right tools, you can craft a testing strategy that helps you build robust, reliable user interfaces efficiently.</p>
<p>In the ever-evolving landscape of web development, staying adaptive in your testing approach is key. Keep exploring new tools and methods, and don't be afraid to adjust your strategy as your application and team needs change. Happy testing!</p>
]]></content:encoded></item><item><title><![CDATA[One Line to Run Tests on GitHub Actions Faster]]></title><description><![CDATA[Image by Florian Kurz from Pixabay OK, this is clickbait and yes, I’ve already captured your attention! For those seeking the essence of this article…]]></description><link>https://tallybarak.com/one-line-to-run-tests-on-github-actions-faster-798391e3b0b</link><guid isPermaLink="true">https://tallybarak.com/one-line-to-run-tests-on-github-actions-faster-798391e3b0b</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Mon, 07 Aug 2023 16:04:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681661063/a7889b25-dea3-4085-bcfe-9dd72b868e67.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Image by <a target="_blank" href="https://pixabay.com/users/flo222-4394947/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2025863">Florian Kurz</a> from <a target="_blank" href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2025863">Pixabay</a></p>
<p>OK, this is clickbait and yes, I’ve already captured your attention! For those seeking the essence of this article without the frills, here’s the TL;DR:</p>
<p>Define the matrix of shards on your test running job with the number of jobs you want to run in parallel:</p>
<p> strategy:<br />      matrix:<br />        shard: [1,2,3,4,5,6,7,8,9,10] # as many jobs as you want, but less than numbers of tests<br />      fail-fast: false</p>
<p>The SHARD_FILES env parameter will have the names of files to run:</p>
<p>- name: all test files sorted by size<br />  run: echo "SHARD_FILES=$(find  -type f -name "*.test.js" -exec stat -c "%s %N" {} + | sort -rn | cut -f2- -d ' ' | tr -d \' | sed -n '${{matrix.shard}}~${{strategy.job-total}}p' | tr '\n' ' ' )" &gt;&gt; $GITHUB_ENV</p>
<p>With the SHARD_FILES in your grip, you command your tests to run in a synchronized ballet of sharding:</p>
<p>- name: run tests<br />  run:  ${{env.SHARD_FILES}} </p>
<p>If you want to understand more about the logic, the rest of the article is for you.</p>
<p><strong><em>Cautionary words abound! The commands above are tailored for Ubuntu, and will not work on Mac OS shells (and possibly Windows) where sed and stat differ in their versions.</em></strong></p>
<h3 id="heading-why-sharding">Why Sharding?</h3>
<p>Assume you have a large number of tests and you want them to run faster, you are probably going to run them in parallel. Instead of running 1 test file at a time, your machine is going to run multiple tests at the same time. You can usually achieve that by setting a <code>-- parallel=4</code> configuration parameter (or a similar one) to indicate your test runner to run 4 tests in parallel. This option is supported by most test runners in the Javascript arena, and likely in other languages.</p>
<p>Running tests in parallel is only useful if you have a strong machine: 8, 12, or even 16 cores. Most test runners will default the number of processes run to the number of cores minus one. The 1 process is reserved for the parent process that orchestrates the tests, and all other cores are dedicated to executing the tests.</p>
<p>But when you run on CI, your machines are not going to be 12 or 16 cores. The standard Linux virtual machine on GitHub-hosted runners has <a target="_blank" href="https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources">2 cores and 7 GB of memory.</a> Probably miles behind your development machine.</p>
<p>On weak machines like CI machines, you should not use parallel execution. Instead, you should use <strong>Sharding</strong>. Sharding splits your tests to multiple machines by assigning each machine a subset of your tests to execute.</p>
<p><strong>With sharding you do not execute tests in parallel on a SINGLE machine. Instead, you run tests serially on MULTIPLE machines.</strong></p>
<p>But how do you run tests on multiple machines? well, You need to take all your files, split them into groups, each group contains some of the files, and assign each group to a machine. When running in parallel on a single machine, you have an orchestrater that pushes the “next file” to a worker that is available (or after a process has ended). But when working on multiple machines you cannot do that. You need to assign upfront all the files to these groups.</p>
<p>Quick note: the whole solution assumes your test runner can execute a list of files, which most runners can do. The command looks something like this:</p>
<p>npx my-test-runner file-a.test.js file-b.test.js file-c.test.js</p>
<h3 id="heading-files-selection-using-math">Files Selection — Using Math</h3>
<p>Your first thought is probably: not that complex. I need to know upfront how many machines I allocate (makes sense), and then I split the files into chunks according to the number of machines. Let’s do some math. Assume we have 62 tests and we split them over 10 machines.</p>
<p><strong>Attempt #1</strong>: The very simple math is to divide the number of tests by the number of machines we have: 62 / 10 = 6. OK, 6 files on each machine. But then we are left with 2 files. So we need to apply a special logic on the “last” machine. And also the last machine will have 8 files, which will probably make it slower than the others. Also — what if we have 68 files? now all of our machines will get 6 files while the last one will get… 14. Not ideal.</p>
<p><strong>Attempt #2</strong>: to avoid “leftovers” let’s divide by the number of machines but instead of rounding the value down ( “floor”) we will round it up (“ceil”). Now we need to assign 7 files to each machine. But now our first 8 machines will get 7 files, our 9th machine will get 6 and the 10th machine is left with, well — none. Waste of resources.</p>
<p>You can also try dividing by (machines + 1) or (machines -1) with floor and with ceiling. None of these maths works up too well.</p>
<h3 id="heading-files-selection-using-distribution">Files Selection Using Distribution</h3>
<p>The intelligent reader (that is YOU!) realized that the only way to properly distribute the files is like dealing a deck of cards. We are going to “deal” each machine with a single file until no more files are left in our deck.</p>
<iframe src="https://giphy.com/embed/3hcL78OV2bN4s/twitter/iframe" width="435" height="340"></iframe>

<p>Let’s take an example: we have 62 files and 10 machines. Here is how the tests will be distributed:</p>
<p>Machine 1: 1, 11, 21, 31, 41, 51, 61 (7 files)<br />Machine 2: 2, 12, 22, 32, 42, 52, 62 (7 files)<br />Machine 3: 3, 13, 23, 33, 43, 53 (6 files)<br />Machine 4 - 10: (6 files each)</p>
<p>But how do we write this? Sure, we could have written a nice Javascript (or Python, or Rust or Go) code to do it, but when it comes to CI, I am trying to make it as minimal as possible for the sake of clarity. I avoid large chunks of code that requires too much maintenance, and instead, I prefer using Bash commands on CI.</p>
<p>And Bash has very nice tools…</p>
<p>In this case, the glorious Bash command is called <code>sed</code>, short of Streaming Editor. When sed gets a list of lines, it can use the <code>-n 'x~yp'</code> parameter that tells it to start with the x-th line and pick each y-th line. So <code>-n '2~4p’</code> means start with the 2nd line, then the 6th, then the 10th, etc. Exactly what we need to deal our deck of files.</p>
<p>our process is as follows:</p>
<ul>
<li>Read all the test files in a pre-defined order (e.g. alphabetically)</li>
<li>On each machine, start with the current shard and skip the total number of shards to get the list of files to run in the current shard.</li>
<li>Run the tests in the list of files for the current shard.</li>
</ul>
<p>The important thing to notice here is that we need to make sure our test files are always read in the same order for each job. Otherwise, we might end up with some tests running twice while others will be skipped. Reading the files in alphabetical order can ensure that, but we can make it run even faster.</p>
<h3 id="heading-lets-make-it-faster">Let’s make it faster</h3>
<p>When we read the files sorted alphabetically, files are just going to be randomly assigned to process. Although each machine gets approximately the same number of files, we might end up with one machine getting a list of really long tests while another will get the same number of files but of really short tests.</p>
<p>Ideally, we would like to also even the duration of the test execution. To do that we need to have some knowledge about how long each test runs. We can store information on the tests, but it requires us to constantly compare the list of files we are running every time we add, remove or change the test files.</p>
<p>Another option is to use heuristics.</p>
<blockquote>
<p>A heuristic is a mental shortcut commonly used to simplify problems and avoid cognitive overload. Heuristics are part of how the human brain evolved and is wired, allowing individuals to quickly reach reasonable conclusions or solutions to complex problems. These solutions may not be optimal ones but are often sufficient given limited timeframes and calculative capacity. (Investopedia)</p>
</blockquote>
<p>Heuristics are not perfect but might be sufficient to get our tests relatively balanced and without too much effort in storing the data and comparing it to changed files. We can use the file size as an indication of the duration the test takes to run. The longer the file is, the longer it needs to execute. (remember? this is a heuristic, so small files might take longer than expected, but overall it might end up nicely).</p>
<p>How can we split the files by their size? we will read our test files, sort them by their size, and distribute them across the different machines starting with the largest file to the smallest.</p>
<h3 id="heading-putting-it-all-together">Putting it all Together</h3>
<p>So now that we know how we want to do it: let’s write the code.</p>
<p>First, we need to tell GitHub actions to create multiple jobs that will run in parallel. This is done using the <a target="_blank" href="https://docs.github.com/en/actions/using-jobs/using-a-matrix-for-your-jobs">matrix parameter</a>:</p>
<p>strategy:<br />      matrix:<br />        shard: [1,2,3,4,5,6,7,8,9,10] # as many jobs as you want, but less than numbers of tests<br />      fail-fast: false</p>
<p>In the above, we have 10 jobs running in parallel. Each job will get the parameter <code>matrix.shard</code> that indicates the current shard.</p>
<p>Next, we write a command that finds all files matching the pattern <code>*.test.js</code> (adjust to your needs) in the specified directory (shown bellow as <code>&lt;dir&gt;</code>. (the find command is working on directories recursively, so it will read all your test files under that directory). The command retrieves each file its size and name, sort them by size in descending order, and then outputs the selected files with their full paths in a single line using the current shard as the starting number and skipping the total number of shards ( <code>${{strategy.job-total}}</code> ). All the names of the files that need to be tested are then stored in the environment parameter <code>SHARD_FILES</code> that we can later use.</p>
<ul>
<li>name: create the list of files to test on the shard<br /> run: echo "SHARD_FILES=$(find  -type f -name "*.test.js" -exec stat -c "%s %N" {} + | sort -rn | cut -f2- -d ' ' | tr -d \' | sed -n '${{matrix.shard}}~${{strategy.job-total}}p' | tr '\n' ' ' )" &gt;&gt; $GITHUB_ENV</li>
</ul>
<p>Let’s break down the above command step by step (or actually, let’s ChatGPT do it for us):</p>
<ol>
<li><code>find &lt;dir&gt; -type f -name "*.test.js"</code>: This starts the search from the specified directory <code>&lt;dir&gt;</code> and looks for all files (<code>-type f</code>) with names ending in <code>.test.js</code> using the <code>-name</code> option. The <code>&lt;dir&gt;</code> should be replaced with the actual directory path you want to search.</li>
<li><code>-exec stat -c "%s %N" {} +</code>: For each file found by <code>find</code>, the <code>stat</code> command is executed with the format <code>-c "%s %N"</code>. <code>%s</code> represents the file size in bytes, and <code>%N</code> represents the file name along with its path.</li>
<li><code>| sort -rn</code>: The <code>|</code> (pipe) symbol is used to take the output of the previous <code>find</code> and <code>stat</code> command and pass it as input to the <code>sort</code> command. The <code>-rn</code> option is used to sort the files in reverse numeric order based on their file sizes. This will display the largest files first.</li>
<li><code>| cut -f2- -d ' '</code>: The sorted output is then piped to the <code>cut</code> command. The <code>-f2-</code> option indicates that we want to retain all fields starting from the second field. The <code>-d ' '</code> specifies that the delimiter between fields is a space.</li>
<li><code>| tr -d \'</code>: The output is piped to the <code>tr</code> command, which is used to delete characters. In this case, it deletes the single quotes (<code>'</code>) from the output.</li>
<li><code>| sed -n '${{matrix.shard}}~${{strategy.job-total}}p'</code>: The output is piped to the <code>sed</code> command, which performs a pattern-based selection on the lines. The <code>${{matrix.shard}}~${{strategy.job-total}}p</code> expression is a placeholder that gets replaced with specific values in a CI environment. The <code>${{matrix.shard}}</code> and <code>${{strategy.job-total}}</code> are variables representing the current shard and the total number of shards in a CI job, respectively. The <code>sed</code> command selects lines starting from the <code>${{matrix.shard}}</code>-th line, with increments of <code>${{strategy.job-total}}</code>. This way, it selects lines based on the number of shards and distributes the output accordingly.</li>
<li><code>| tr '\n' ' '</code>: Finally, the output is piped to the <code>tr</code> command again, which is used to translate or replace characters. In this case, it replaces newline characters (<code>\n</code>) with a space character. This will convert the list of files into a single line.</li>
</ol>
<p>As a last step, we will use the environment parameter as an input to our test runner as the list of files to run:</p>
<p>name: run tests<br />run:  ${{env.SHARD_FILES}}</p>
<p>And that’s it — your test runner now runs only on the set of files that were defined for this shard.</p>
<p>It is probably worth mentioning that some test runners like Playwright, Jest, and Vitest have the sharding option built in as part of their command line. For other test runners — you can use this method.</p>
<h3 id="heading-how-many-shards-should-i-use">How Many Shards Should I Use?</h3>
<p>It depends.</p>
<p>GitHub Actions pricing is per execution minute and not affected by the number of jobs that you run. If the total time of your tests is 200 minutes, this will not be reduced and you will still pay these 200 minutes.</p>
<p>However, you will pay for the extra overhead per machine. So if your tests require 4 minutes per machine to set up the test environment (things like code checkout, package manager installation, docker spinning, etc.) this will be increased.</p>
<p>Let’s assume your setup time is 3 minutes per job. Your tests are in 40 files summed up to a total of 200 minutes of execution. Here are some indicative numbers:</p>
<p>// using 10 jobs:<br />total execution cost: 200 + 3 * 10 = 230 minutes<br />Execution elapsed time: 200 / 10 + 3 = 23 minutes  </p>
<p>// using 20 jobs:<br />total execution cost: 200 + 3 * 20 = 260 minutes<br />Execution elapsed time: 200 / 20 + 3 = 13 minutes</p>
<p>It is up to you to find the optimal sharding in terms of cost and execution elapse time.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>When I was looking to implement sharding on our e2e tests that are using Cucumberjs, I could not find any guidelines and best practices. I went thru some painful attempts to come up with a good method. If I saved you some of the trouble, I am rewarded.</p>
<p>Thus concludes our poetic tale of sharding tests with wisdom and wit. For those who found this elucidation helpful, let the claps and shares resound like a standing ovation in the theater of the internet!</p>
]]></content:encoded></item><item><title><![CDATA[The Illustrated Guide to Using Promise.all in Playwright Tests]]></title><description><![CDATA[In this article, I will go over the way Playwright communicates between the browser automation runner and the browser, and explain how to correctly use…]]></description><link>https://tallybarak.com/the-illustrated-guide-to-using-promise-all-in-playwright-tests-af7a98af3f32</link><guid isPermaLink="true">https://tallybarak.com/the-illustrated-guide-to-using-promise-all-in-playwright-tests-af7a98af3f32</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Sun, 13 Nov 2022 08:16:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681359332/d3bb3407-0da6-43ee-9807-cf1c2e6a7be1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, I will go over the way Playwright communicates between the browser automation runner and the browser, and explain how to correctly use Promise.all to avoid tests’ flakiness.</p>
<h3 id="heading-playwright-communication">Playwright Communication</h3>
<p>Playwright is running in two separate contexts:<br />- The Nodejs context is running the tests and sending the commands to the browser<br />- The Browser context is getting the commands, executing them together, and running your application code.</p>
<p>These two contexts run in parallel and are not synchronized in their actions. You cannot tell if something will happen in the node context before or after the browser has completed an action.</p>
<p>Browser and NodeJS are not synchronized in their actions</p>
<p>The two contexts are communicating over an asynchronous mechanism. NodeJS is sending requests to the browser and receives a response.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681348867/0f73a7ea-73cb-4c84-b100-fbaa7a604488.png" alt /></p>
<p>Playwright browser and node communication</p>
<p>You can imagine it like a Whatsapp conversation between two people, each one doing their own things during this chat:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681350538/114c2b57-b4ab-41b1-8ba6-9d8b5f0f2cee.png" alt /></p>
<p>(Hint: to see the real communication, run Playwright test with DEBUG=pw:api)</p>
<h3 id="heading-waiting-for-an-activity">Waiting for an Activity</h3>
<p>Assume you have a button that clicking on it will trigger a server request. You want to catch that request to verify it contains proper information.</p>
<h4 id="heading-attempt-1">Attempt #1</h4>
<p>Initially, you may write a fairly straightforward code:</p>
<p>await page.locator('button').click();<br />await page.waitForRequest('https://example.com/resource');</p>
<p>This code will go anywhere from not working to flaky. Let’s look at the timelines:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681352088/659418ad-52e0-4909-ac4d-5ef7fcbcf6b1.png" alt /></p>
<p>First — the NodeJS will send a request to the browser to click the button. Once the button is clicked and the NodeJS receives the response, it will send the browser an instruction to check if the request is sent. But since we do not know how long it takes the NodeJS to send this request, it can hit the browser at any time during the purple rectangle. Now if the instruction hits the browser before the request is sent, marked as A zone, we are lucky, and the browser will catch it. But we can also hit the browser during the section marked as B, and then it is too late. Our request has already left the station and we are going to miss it.</p>
<p>It is like telling your kid to open the door, and then sending them a message to make sure the dog does not run away. Well, by the time they read the second message, the dog is probably already chasing all of the neighborhood’s cats.</p>
<h4 id="heading-attempt-2">Attempt #2</h4>
<p>Ok, so let’s send the request to check the network request before hitting the button.</p>
<p>await page.waitForRequest('https://example.com/resource');<br />await page.locator('button').click();</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681353505/672d2ccf-7d68-4021-a02d-515b4eead6f7.png" alt /></p>
<p>Well, this is not going to work at all. Our browser will wait for the request to fire, but as our button was not clicked, it will not fire and the instruction will timeout with an error.</p>
<h4 id="heading-attempt-3">Attempt #3</h4>
<p>The solution is to send both requests in parallel, using promise.all:</p>
<p>await Promise.all([<br />  page.waitForRequest('https://example.com/resource'),<br />  page.locator('button').click()<br />])</p>
<p>What happens here?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681354888/0164a218-760c-46ff-aaab-956e29ae72e0.png" alt /></p>
<p>NodeJS instructs the browser to wait for the request, and immediately, before the request is resolved, it sends the browser the instruction to click on the button. We sent the waitForRequest before we sent the click, so the browser is already waiting for the request to fire.</p>
<p>Once the request is fired, the browser is already on the watch for it and intercepts it. The test is now stable.</p>
<h3 id="heading-short-lived-element">Short-Lived Element</h3>
<p>The other example we will look into is a short-lived element. Think of a loader that appears on the page after a button is clicked and the requests are sent and disappear when everything is ready. The browser of the timeline looks as follows:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681356308/7074c8af-2d4d-4078-89c3-7dd6b2e2e06d.png" alt /></p>
<p>We want to send 3 instructions to the browser:</p>
<ul>
<li>Click the button</li>
<li>Make sure that the loader appears</li>
<li>Make sure that the loader disappears.</li>
</ul>
<p>The “problematic” zone here is B. We cannot be sure that we will hit it to check that the loader appears before the loader disappears. Therefore, we need to send a request to check if the loader appears in parallel and before the loader appears.</p>
<p>Our code will then send:</p>
<p>await Promise.all([<br />  page.locator('#loader').waitFor(),<br />  page.locator('button').click()<br />];</p>
<p>This will make sure that we wait for the loader to appear in zone A above. Then, we just need to wait for it to disappear. We can do it after we get the response that the loader appeared:</p>
<p>await page.locator('#loader').waitFor({state: 'detached'};</p>
<p>And this is what the all flow looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681357872/323af81a-ed62-4b7d-b8df-00d8b9a62b4d.png" alt /></p>
<p>Our loader gone may hit the browser before or after the loader has disappeared. If the request hits in zone C it will wait until the loader disappears. If it will hit in zone D, it will resolve immediately.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Pkaywright is working in a really fast pace, and we cannot assume how the NodeJS and the Browser are synchronized. Promise.all( ) is extremely powerful in making your tests robust and reduce the flakiness.</p>
]]></content:encoded></item><item><title><![CDATA[Writing Storybook Stories with TSX for Stencil]]></title><description><![CDATA[Yes, you can! If you want to write your stencil stories for storybook using TSX (the Typescript version of JSX), this is actually possible. A bit of…]]></description><link>https://tallybarak.com/writing-storybook-stories-with-tsx-for-stencil</link><guid isPermaLink="true">https://tallybarak.com/writing-storybook-stories-with-tsx-for-stencil</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Mon, 09 May 2022 10:34:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Oaqk7qqNh_c/upload/18c708d66fd8e0721dd266318db9e372.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Yes, you can!</p>
<p>If you want to write your stencil stories for storybook using TSX (the Typescript version of JSX), this is actually possible. A bit of tweaking, and you should go to go. BUT - this is still a very preliminary work, and I expect it to suffer quite few bumps in different scenarios. Nevertheless, I thought it it worth sharing, as I know people were looking for a solution.</p>
<p>This is assuming you are using the html version of Storybook with Stencil. You can find a working version in my stencil-one <a target="_blank" href="https://github.com/Tallyb/stencil-one">demo repo</a>. (This is my demo repo for unit testing in Stencil, so feel free to look around).</p>
<p>These are the main versions I worked with. I have no idea if it will be compatible with other versions.</p>
<ul>
<li><p>Stencil: 2.15</p>
</li>
<li><p>Storybook: 6</p>
</li>
<li><p>webpack: 5</p>
</li>
<li><p>babel-loader: 8</p>
</li>
</ul>
<h2 id="heading-step-1-write-your-story">Step 1: Write your story</h2>
<p>This is what a story should look like, using CSF3 (Component Story Format). Obviously, it should be in a file named <code>.tsx</code>, so it will go thru the right tooling. Also, change the path that looks for your stories to include .tsx files. (stories option in the main file).</p>
<pre><code class="lang-plaintext">/** @jsx h */
/** @jsxRuntime classic */

import {h} from '@stencil/core';

export default {
  title: 'My Basic',
};

export const Default = {
  render: () =&gt; (&lt;my-basic first="Millie" last="Brown"&gt;&lt;/my-basic&gt;)
};
</code></pre>
<p>Note the <code>@jsx</code> directives. They seem to be necessary.</p>
<h2 id="heading-step-2-configure-webpack-for-jsx">Step 2: Configure Webpack for jsx</h2>
<p>We are going to tweak <code>.storybook/main</code> so it will include the babel jsx transformer. In order to do that we will find the rule that handles tsx and add the <code>@babel/plugin-transform-react-jsx</code> as plugin with the <code>pragma: {'h'}</code>.</p>
<pre><code class="lang-plaintext">  webpackFinal: async (config) =&gt; {
    const tsxRule = config.module.rules.find(rule =&gt; 'a.tsx'.match(rule.test));

    if(tsxRule) {
        const options = tsxRule.use[0].options;
        options.plugins = [
          ['@babel/plugin-transform-react-jsx', {
            prgama: 'h'
          }],
          ...options.plugins
        ];
    }
    return config;
  }
</code></pre>
<h2 id="heading-step-3-render-the-stories-using-stencils-rendervdom">Step 3: Render the stories using Stencil's renderVDom</h2>
<p>The last part is changes to the <code>storybook/preview</code> code. Create a function that will be used as a decorator and will render elements to the DOM.</p>
<pre><code class="lang-plaintext">const stencilWrapper = (storyFn, context) =&gt; {
  const host = document.createElement('div');
  stencilClient.renderVdom(
    {
      $ancestorComponent$: undefined,
      $flags$: 0,
      $modeName$: undefined,
      $cmpMeta$: {
        $flags$: 0,
        $tagName$: 'div',  
      },
      $hostElement$: host,
    },
    storyFn(context)
  );
  return host.children[0];
}
</code></pre>
<p>And then activate it: <code>addDecorator(stencilWrapper);</code></p>
<p>You will also need to make sure that you are calling the defineCustomElements (which you should, anyway) in the preview code or the preview-manager html file.</p>
<p>As mentioned above, this is still prone to errors. If you have any suggestions, improvements, bugs fixes etc, please comment.</p>
]]></content:encoded></item><item><title><![CDATA[E2E Testing with Cucumber and Playwright]]></title><description><![CDATA[Write BDD E2E tests using Cucumber and Playwright. While both tools support multiple programming languages (Python, Java, Javascript, and more), I will…]]></description><link>https://tallybarak.com/e2e-testing-with-cucumber-and-playwright-9584d3ef3360</link><guid isPermaLink="true">https://tallybarak.com/e2e-testing-with-cucumber-and-playwright-9584d3ef3360</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Sun, 07 Feb 2021 13:48:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/0iWXe0XYfEs/upload/5f00a3f911309312e01fc2a52ccba455.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Write BDD E2E tests using Cucumber and Playwright. While both tools support multiple programming languages (Python, Java, Javascript, and more), I will focus on my language of choice which is Javascript (more specifically — Typescript).</p>
</blockquote>
<h3 id="heading-why-bdd-behavioral-driven-development">Why BDD (Behavioral Driven Development)?</h3>
<p>In BDD you write your system requirements in structural but natural language. Writing End-to-End tests in a natural language enlarges the audience that can read and use them. This means your Product Management and Customer Success teams can read and comment on your tests without knowing any programming language.</p>
<p><a target="_blank" href="https://cucumber.io/docs/gherkin/">Gherkin</a> is a BDD language that uses some keywords to describe the scenarios. The general structure of Gherkin tests looks like this:</p>
<p>Feature: Title of the Scenario<br />Given [Preconditions or Initial Context]<br />When [Event or Trigger]<br />Then [Expected output]</p>
<p>You can imagine a Gherkin feature for a shopping site to look as follow:</p>
<p>Feature: Buy an item<br />Given anonumous user is on the main site<br />When user searches for "a horse walks into a bar"<br />Then results list contains 5 items<br />When user selects "a horse walks into a bar" book<br />And user adds selected book to the cart<br />And user goes to shopping cart<br />Then cart contains 1 item</p>
<p>If you compare the above to a test scenario written in a language like Javascript it is easy to see why the Gherkin syntax makes easier communication.</p>
<p>describe('shopping', () =&gt; {<br />test('buying a book item', async () =&gt; {<br />await goto('https://my-shopping.com');<br />await enterSearchItem('A horse walks into a bar');<br />const resultListLength = await resultsPage.getList();<br />expect(resultListLength).toEqual(5);<br />await selectItem('a horse walks int a bar');<br />await addSelectedToList();<br />const shoppingCartTotalItems = await<br />shoppingCart.getTotalItems();<br />expect(shoppingCartTotalItems).toEqual(1);<br />});<br />});</p>
<p>The clear syntax of Gherkin also allows for building complex business scenarios that require multiple steps and are still easy to read and understand.</p>
<h3 id="heading-why-cucumber">Why Cucumber?</h3>
<p><a target="_blank" href="https://cucumber.io/">Cucumber</a> is the most popular testing framework for writing Gherkin tests. Cucumber reads the Gherkin feature (usually stored in <code>.feature</code> files) and executes each step in the test.</p>
<p>To define a Gerkin step, you use the cucumber syntax to parse the text and execute the relevant code.</p>
<p>Given('anonumous user is on the main site', async function () {</p>
<p>// Step implementation goes here</p>
<p>}</p>
<p>Gherkin steps support enhanced parameters to define the steps. A simple parameterized step can be written as:</p>
<p>When('user searches for {string}', async function (<br />searchTerm: string<br />) {</p>
<p>// Step implementation goes here</p>
<p>}</p>
<p>A more complex step can use Regex expressions to define the steps:</p>
<p>When(/^user selects "([^"]+)" (book|movie)$/', async function (<br />title: string,<br />itemType: string<br />) {</p>
<p>// Step implementation goes here</p>
<p>}</p>
<h3 id="heading-why-playwright">Why Playwright?</h3>
<p>The last part is the implementation of the steps. For a web-based system, this means that a browser automation tool is needed. The most popular tool is Selenium but a new generation of tools now exists allowing for a faster and better development experience.</p>
<p>The most modern of them is <a target="_blank" href="https://playwright.dev/">Microsoft’s Playwright</a>. Playwright is built with testing in mind and overcomes most common problems when writing browser-based test automation. <a target="_blank" href="https://medium.com/@tally_b/5-ways-playwright-is-awesome-b94eff4da0ea">I detailed some of the reasons why I think Playwright is awesome</a>.</p>
<h3 id="heading-putting-it-all-together">Putting it All Together</h3>
<p>Typescript is your main programming language? here is some good news for you! I have created a <a target="_blank" href="https://github.com/Tallyb/cucumber-playwright">starter repository</a> that has cucumberjs, playwright, and Typescript. Just click on the “Use this template” button and you can start writing your own tests.</p>
<p><a target="_blank" href="https://github.com/Tallyb/cucumber-playwright"><strong>Tallyb/cucumber-playwright</strong><br />*A starter repo for writing E2E tests based on Cucumber(7) with Playwright using Typescript. This repository is based on…*github.com</a></p>
<p>E2E tests are <a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing/part-i-e2e-testing-and-selenium-ef031978ee20">written from the user’s perspective</a> so you can use this automation regardless of the development framework of the underlying system, be it React, Vue, Angular, Jquery, or even vanilla Javascript.</p>
<p>To make it even more fun, I threw in some goodies:</p>
<ul>
<li><p>Screens snapshotting that are included in the test report</p>
</li>
<li><p>An option to run the test and record its execution in a video (thank you Playwright!)</p>
</li>
<li><p>VSCode configuration to run and debug a single feature.</p>
</li>
</ul>
<p>You are welcome to leave comments to share your experience and opinions.</p>
]]></content:encoded></item><item><title><![CDATA[5 Ways Playwright is Awesome]]></title><description><![CDATA[Edit (7/22): This article was written in the early days of Playwright and is only referencing the browser automation part and not the playwright test…]]></description><link>https://tallybarak.com/5-ways-playwright-is-awesome-b94eff4da0ea</link><guid isPermaLink="true">https://tallybarak.com/5-ways-playwright-is-awesome-b94eff4da0ea</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Wed, 03 Feb 2021 19:02:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715426399957/88ac083f-ee35-4fed-99d2-06401f3ccd6d.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Edit (7/22): This article was written in the early days of Playwright and is only referencing the browser automation part and not the playwright test, which is awesome by itself. Also the Playwright browser automation, a.k.a Playwright Library, got tons of goodies. A new article would be more like “50 Ways Playwright is Awesome”.</p>
<p>Playwright is Microsoft’s new alternative to browser-based test automation. We have recently switched from Webdriverio / Selenium to Playwright. Here are the top reasons:</p>
</blockquote>
<h3 id="heading-1-selectors">1 — Selectors</h3>
<p>I just love PW selectors! Playwright selectors are built as strings comprised of sections where each section is a selector by itself. A selector looks like this:</p>
<p>css=#menu &gt;&gt; css=div.menu-item&gt;&gt; text="Books"</p>
<p>This will search the top for the menu element, a menu item inside that contains the text “Books”.</p>
<p>Moreover, if you are using Web Components on your website, you can decide if the selectors will pierce the shadow DOM or not. Piercing the Shadow Dom works with the syntax above and it will pierce all the shadow roots along the way. (For us, this was a winning feature!)</p>
<h3 id="heading-2-auto-waiting">2 — Auto Waiting</h3>
<p>Yet another winning feature of Playwright. PW has rules on waiting for specific actions. Clicking on an element ensures that it is:</p>
<ul>
<li><p>Stable: animation has finished</p>
</li>
<li><p>Visible: not hidden by any other element</p>
</li>
<li><p>Enabled: not disabled,</p>
</li>
<li><p>Receives events: not hidden by any other element.</p>
</li>
</ul>
<p>PW will also scroll the element into viewport if it is outside of it.</p>
<p>When entering data, PW also verifies that the element is editable.</p>
<p>All of the above make the test code shorter and reliable.</p>
<h3 id="heading-3-single-browser-launch">3 — Single Browser Launch</h3>
<p>Playwright introduces the concept of a browser context. For each browser engine (PW supports Chrome, Firefox, and Safari), you can launch the browser only once and open multiple contexts.</p>
<p>Each context can be configured differently. It can be personalized or incognito, have its own viewport size (or device emulation), and store its own data, locale, location, or timezone.</p>
<p>Single browser launch with multiple contexts makes Playwright go really fast when running multiple tests.</p>
<h3 id="heading-4-video-capturing">4 — Video Capturing</h3>
<p>Capturing the session flow can be easily achieved by setting a parameter on the browser context. The whole session is then automatically recorded and can be used to investigate problems’ root causes.</p>
<h3 id="heading-5-development-experience">5 — Development Experience</h3>
<p>Initially, Playwright supported Typescript with types definition, so you could use your IDE auto-complete. Newer versions also support Python, Java, and C#.</p>
<p>Playwright has excellent debugging options, so you can see in detail the API calls to the browser. You can also launch the browser from the command line, (or halt it during a debug session) so you test your selectors, as you can see in the video.</p>
<iframe src="https://www.youtube.com/embed/77giCdBm5wU?feature=oembed" width="640" height="480"></iframe>

<p>Checking selectors with playwright</p>
<p>Playwright has lots of other goodies. Network requests interceptions, multiple tabs, easy installation, docker support, and <a target="_blank" href="https://playwright.dev/docs/why-playwright">the list goes on</a>…</p>
]]></content:encoded></item><item><title><![CDATA[Lerna Graph]]></title><description><![CDATA[If you are using Lerna or have a monorepo that is compliant with Lerna structure - this is a Github Action you would love.]]></description><link>https://tallybarak.com/lerna-graph</link><guid isPermaLink="true">https://tallybarak.com/lerna-graph</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Tue, 01 Sep 2020 05:36:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/gcsNOsPEXfs/upload/5b6053fdc2bc6f46ab72873fe0794aa7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>The action generates a graph for all the Lerna packages in the repo and their current version.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681270214/d96944e9-bc5d-42bc-9f68-abcbfb7399ff.png" alt="Alt Text" /></p>
<p><strong>Important!!!</strong> Even if you do not use Lerna, you can simply add a <code>lerna.json</code> file with minimal configuration (packages, version) and the action will work!</p>
<p>You can find this action in the <a target="_blank" href="https://github.com/marketplace/actions/lerna-graph">marketplace</a></p>
<h3 id="heading-submission-category">Submission Category:</h3>
<p>Maintainer Must-Haves</p>
<h3 id="heading-yaml-file-or-link-to-code">Yaml File or Link to Code</h3>
%[INVALID_URL]<p> </p>
<h3 id="heading-additional-resources-info">Additional Resources / Info</h3>
<p>You cannot go more meta than this: Lerna project graph <a target="_blank" href="https://github.com/Tallyb/lerna/actions/runs/233133309">generated by this action</a></p>
]]></content:encoded></item><item><title><![CDATA[Packaging a UI Library for Distribution]]></title><description><![CDATA[Image by Arek Socha from Pixabay The JavaScript world has a unique feature: it has multiple runtime environments all running the same code. On one side we…]]></description><link>https://tallybarak.com/packaging-a-ui-library-for-distribution-d153219def28</link><guid isPermaLink="true">https://tallybarak.com/packaging-a-ui-library-for-distribution-d153219def28</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Wed, 15 Jul 2020 19:26:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681670309/af14f38a-c742-4e51-927e-cc3eb4a1b591.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h4 id="heading-guidelines-you-may-want-to-follow-if-you-are-publishing-a-ui-components-library">Guidelines you may want to follow if you are publishing a UI components library.</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681663809/b3c5c685-4b08-4594-af0b-1d5bafc71904.jpeg" alt /></p>
<p>Image by <a target="_blank" href="https://pixabay.com/users/qimono-1962238/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1893642">Arek Socha</a> from <a target="_blank" href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1893642">Pixabay</a></p>
<h3 id="heading-the-problem">The problem</h3>
<p>The JavaScript world has a unique feature: it has multiple runtime environments all running the same code. On one side we have the browsers, provided by different manufacturers and in different versions. On the other side, we have Nodejs running on the server, also in different versions. (Side note: you probably want to watch out Deno, an interesting server runtime).</p>
<p>After almost two decades of hibernation of the language, JavaScript gained huge momentum with new features coming to the language daily (well, yearly, but the metaphor works better this way). At the same time, new flavors of JS, such as Typescript and Flow showed up, adding additional syntax to the language.</p>
<p>We end up with a mixture of dialects, execution platforms, and evolving standards. All leading to the fact that building a UI components package in Javascript and sharing it with the world is anything but simple.</p>
<p>Anyone publishing a library should consider how the components are going to be consumed: as a browser tag, installed as an NPM module on the server, or compiled with bundlers like Webpack for the browser.</p>
<h3 id="heading-what-to-deliver-then">What to deliver then?</h3>
<p>Here are my suggestions for the formats that you want to deliver for your package, and in the last section, we will go through the tools that can help you get there.</p>
<p>mage by <a target="_blank" href="https://pixabay.com/users/AnnaliseArt-7089643/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=5293336">Annalise Batista</a> from <a target="_blank" href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=5293336">Pixabay</a> (modified)</p>
<p>I will discuss the delivery of the package in the following 4 aspects. But worth noticing that they are interrelated.</p>
<ul>
<li>ES syntax format</li>
<li>Module format</li>
<li>Files bundling</li>
<li>Package distribution</li>
</ul>
<p>You will also notice that the discussion is completely framework agnostic. The guidelines discussed here are cross-framework and are relevant to components written in Angular, React, and Vue.</p>
<h4 id="heading-es-syntax-format">ES Syntax Format</h4>
<p>Most web browsers as well as Nodejs are supporting at least ES2015 syntax, and most of them are evergreen and are up to date on new features of the language. The infamous exception is IE11, which its market share is thankfully declining. Unless explicit support for IE11 is needed, it is ok to assume that ES2015 can be considered as the lingua franca of the JS environment. Modern browsers and NodeJs newer formats such as ES2017 can also be acceptable.</p>
<p>Recommendation:</p>
<blockquote>
<p>Use ES5 if you are targeting old browsers, ES2015, or ES2017 for modern browsers and NodeJS.</p>
</blockquote>
<h4 id="heading-module-format">Module Format</h4>
<p>It was not until 2015 that Javascript, or Ecamscript as it is officially known, has a norm for module format — the ES6 Module format (AKA ESM, ES2015 Modules). During this twilight zone, multiple formats were created by the community but with not a single standard to adhere to.</p>
<p>formats were created to support browsers and NodeJS.</p>
<ul>
<li>AMD (Asynchronous Module Definition) — Requirejs describe the reasons for developing it back in 2011. <a target="_blank" href="https://requirejs.org/docs/whyamd.html">https://requirejs.org/docs/whyamd.html</a></li>
<li>CommonJS / CJS — developed for server-side modules.</li>
<li>UMD (Universal Module Definition) is a pattern for supporting both client and server and combines AMD with CJS.</li>
<li>ESM / ES Modules / ES6 Modules / ES2015 modules — the standard format introduced in ES6. Support is still experimental in NodeJS 14 and before that was behind a flag ( — experimental-modules).</li>
</ul>
<p>This table summarizes some of the differences between the formats:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681665078/48ae11c1-6b84-426f-8acc-314293f6a0e8.png" alt /></p>
<p>To get the feeling of the differences, we look at how Typescript code is compiled to the different formats:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681666522/92032a57-b927-44f1-8aaf-6c64ad81119d.png" alt /></p>
<p>Recommendation:</p>
<blockquote>
<p>Generate your library with multiple formats: ESM, CJS, and UMD / AMD.</p>
</blockquote>
<h4 id="heading-files-bundling">Files Bundling</h4>
<p>When distributing as an NPM package for browser-based or server-based applications, it is acceptable to provide a directory with multiple files. The server can easily read them one by one, while the browser is likely to have a preparation step that bundles the whole application into a single file (or split into chunks).</p>
<p>However, to use the components as a script tag, you might want to generate a single file that contains all of the library code. A single file can also improve the performance of the bundlers as it reduces the number of disk accesses during the process.</p>
<p>Recommendation:</p>
<blockquote>
<p>Provide UMD formats in a single file for the browser and ESM / CJS formats in separate files and a single file format.</p>
</blockquote>
<h4 id="heading-package-distribution">Package Distribution</h4>
<p>Most packages are available via the NPM registry. This is the common method of publishing them. Publishing a package to NPM also makes it available on CDN for directly used in the browser (via script tags).</p>
<p>Recommendation:</p>
<blockquote>
<p>Make sure your package is providing a UMD format, so it is available via unpkg as well.</p>
</blockquote>
<p>Note: New CDN is coming that support ES Module format. Pika.dev is the one to look at!.</p>
<h3 id="heading-tools">Tools</h3>
<p>The tools for creating those files are:</p>
<ul>
<li>Transpilers</li>
<li>Bundlers</li>
<li>Manifest (package.json)</li>
</ul>
<h4 id="heading-transpilers">Transpilers</h4>
<p>For code written in modern ES formats or Typescript, you should use Babel or Typescript transpilers. Both of them support JS syntax and TS syntax, but <a target="_blank" href="https://blog.logrocket.com/choosing-between-babel-and-typescript-4ed1ad563e41/#:~:text=TypeScript%20by%20default%20compiles%20an,that%20require%20reading%20multiple%20files.&amp;text=A%20const%20enum%20is%20an%20enum%20that%20TypeScript%20compiles%20away%20to%20nothing">with some differences</a><a target="_blank" href="https://blog.logrocket.com/choosing-between-babel-and-typescript-4ed1ad563e41/#:~:text=TypeScript%20by%20default%20compiles%20an,that%20require%20reading%20multiple%20files.&amp;text=A%20const%20enum%20is%20an%20enum%20that%20TypeScript%20compiles%20away%20to%20nothing.">.</a></p>
<p><strong>Babel</strong> includes transformation plugins that transform the code, such as <a target="_blank" href="https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs">transform-modules-commonjs</a> and <a target="_blank" href="https://babeljs.io/docs/en/babel-plugin-transform-modules-umd">transform-modules-umd</a> . They will generate the relevant module format.</p>
<p><strong>Typescript</strong> compiler can also produce different formats using the “module” property in the tsconfig.json is responsible for generating the relevant module output.</p>
<h4 id="heading-bundlers">Bundlers</h4>
<p>Bundlers usually run plugins that execute the transpilation. This includes the language and module format but also generates additional assets such as CSS and images.</p>
<p>bundlers work best with ES Modules format as it has the best support for tree shaking unused code done by the</p>
<p>The common tools are:</p>
<p><strong>Webpack</strong>, up until version 4, can only generate UMD and CommonJS bundles. It also contains some more fine-grained definitions (such as CommonJS2). Read the details <a target="_blank" href="https://webpack.js.org/configuration/output/#outputlibrarytarget">here</a>.</p>
<p><strong>Rollup</strong> is the other bundler. Rollup can export ES modules as an <a target="_blank" href="https://rollupjs.org/guide/en/#outputformat">output format</a>.</p>
<p><a target="_blank" href="https://medium.com/webpack/webpack-and-rollup-the-same-but-different-a41ad427058c">This article</a> summarizes the differences (as of 2017…), but with a conclusion that is probably still valid: Use Webpack for apps, and Rollup for libraries.</p>
<h4 id="heading-manifest">Manifest</h4>
<p>Package.json is the way to manifest the contents of the library. Besides the name of the version, it should point to relevant files in the directory or bundle.</p>
<p>Sadly, as there is no official standard, some ad-hoc tools are using agreed-upon properties for different uses:</p>
<p>Some attribute to note:</p>
<ul>
<li><strong>main</strong>: should point to the main file (the default is index.js at the root). For files that are transpiled it should point to the dist folder, e.g. dist/index.js. Normally this should point to a CJS bundle, as it is the most common format.</li>
<li><strong>module</strong>: this should point to an ES entry point or file. Bundlers such as Webpack know to search for this entry when bundling. Using ES6 for bundling can improve tree shaking.</li>
<li><strong>browser</strong>: should point to an AMD / UMD entry. Usually a single file.</li>
<li><strong>typings</strong>: points to the definitions of the types as used by the Typescript compiler. This is a d.ts file. e.g. dist/index.d.ts</li>
<li><strong>unpkg</strong>: points to the UMD single file that is available via CDN. Unpkg uses this property if exist, or falls back to main.</li>
<li><strong>type</strong>: setting a type field to <strong>module</strong> makes node identifies it as ESM and tries to load it as such.</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In the future, hopefully, in the short future, we are likely to see the Javascript ecosystem converged into a standard format for syntax and modules.</p>
<h3 id="heading-share-amp-manage-reusable-js-components-with-bithttpsbitdev">Share &amp; Manage Reusable JS Components with <a target="_blank" href="https://bit.dev/">Bit</a></h3>
<p>Use <a target="_blank" href="https://bit.dev/"><strong>Bit</strong></a> (<a target="_blank" href="https://github.com/teambit/bit">Github</a>) to share, document, and manage reusable components from different projects. It’s a great way to increase code reuse, speed up development, and build apps that scale.</p>
<p><a target="_blank" href="https://bit.dev"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681668282/88e6babf-fd7f-410a-a0d9-8e54c82c30cc.gif" alt /></a></p>
<p>Example: exploring shared React components on <a target="_blank" href="https://bit.dev/">Bit.dev</a></p>
<p>[<strong>The shared component cloud</strong><br /><em>Bit is a scalable and collaborative way to build and reuse components. It's everything you need from local development…</em>bit.dev](https://bit.dev "https://bit.dev")<a target="_blank" href="https://bit.dev"></a></p>
<h3 id="heading-related-stories">Related Stories</h3>
<p>[<strong>NPM Tips and Tricks</strong><br /><em>12 useful NPM tips and tricks for more productive JavaScript coding.</em>blog.bitsrc.io](https://blog.bitsrc.io/npm-tips-and-tricks-24c5e9defea6 "https://blog.bitsrc.io/npm-tips-and-tricks-24c5e9defea6")<a target="_blank" href="https://blog.bitsrc.io/npm-tips-and-tricks-24c5e9defea6"></a></p>
<p>[<strong>How to Publish React Components</strong><br /><em>How to quickly publish React components from any repository.</em>blog.bitsrc.io](https://blog.bitsrc.io/how-to-publish-react-components-d04e0a7e33b9 "https://blog.bitsrc.io/how-to-publish-react-components-d04e0a7e33b9")<a target="_blank" href="https://blog.bitsrc.io/how-to-publish-react-components-d04e0a7e33b9"></a></p>
<p>[<strong>How to Set Up a Private NPM Registry Locally</strong><br /><em>Setting up a local NPM registry for private packages.</em>blog.bitsrc.io](https://blog.bitsrc.io/how-to-set-up-a-private-npm-registry-locally-1065e6790796 "https://blog.bitsrc.io/how-to-set-up-a-private-npm-registry-locally-1065e6790796")<a target="_blank" href="https://blog.bitsrc.io/how-to-set-up-a-private-npm-registry-locally-1065e6790796"></a></p>
]]></content:encoded></item><item><title><![CDATA[Selecting the Right Tool for Your Monorepo]]></title><description><![CDATA[Image by Alex Myers from Pixabay Monorepos used to be thought of as a solution suitable only to large enterprises, but recently, it seems, the need for…]]></description><link>https://tallybarak.com/selecting-the-right-tool-for-your-monorepo-fafe409134b3</link><guid isPermaLink="true">https://tallybarak.com/selecting-the-right-tool-for-your-monorepo-fafe409134b3</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Thu, 25 Jun 2020 18:32:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681679633/f04c1c99-0f86-4fed-890b-33ccdbd172aa.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Image by <a target="_blank" href="https://pixabay.com/users/myersalex216-4979749/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2638126">Alex Myers</a> from <a target="_blank" href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2638126">Pixabay</a></p>
<p>Monorepos used to be thought of as a solution suitable only to large enterprises, but recently, it seems, the need for them has become apparent to teams of all sizes.</p>
<p>This growth in demand has been met by the creation of numerous tools that offer simpler implementations for this type of code management architecture.</p>
<p>Before we review the most prominent tools, let’s first set out a clear definition for monorepos.</p>
<p>The Wikipedia definition refers to a monorepo as a</p>
<blockquote>
<p>Software development strategy where code for many projects is stored in the same repository.</p>
</blockquote>
<p>I aim for a more precise definition saying that a monorepo is a single VCS repository where you produce multiple artifacts.</p>
<p>Wait? What?</p>
<p>Isn’t a monorepo the whole codebase of your company? probably not. Some companies may have their whole codebase reside in a single repository, but it is also perfectly fine if you have multiple monorepos. If you use a single repository and publish multiple applications, multiple packages for NPM, or multiple microservices, this can be considered as a monorepo.</p>
<p>So that immediately leads to the next question: what is monorepo good for? Few answers come to mind:</p>
<h4 id="heading-code-sharing">Code Sharing</h4>
<p>The most common use of monorepos is for code sharing. When multiple applications need to share a piece of code, creating them in a monorepo and using the code in all applications is the most straightforward approach. Referencing the code directly inside the monorepo saves the overhead of publishing or exporting the shared code to external artifact storage before the resident projects can consume it.</p>
<h4 id="heading-publish-smaller-changes">Publish smaller changes</h4>
<p>Let’s imagine you have a library or a product that you publish inside your company, sell to customers, or share with the community. The library may be delivered in one of two ways to its consumers:</p>
<ul>
<li>As a single package that contains all the code</li>
<li>As a set of smaller packages, each one with a specific responsibility.</li>
</ul>
<p>The latter approach can rip high benefits to the consumers of the package:</p>
<ul>
<li>They can get smaller changes so the stability of their product is less impacted. Instead of replacing GIANT PACKAGE from 1.0.0 to 1.1.0, they might be able to upgrade only the parts they need, such as packages where bugs were fixed.</li>
<li>They can decide what parts of the software they are willing to install. In tools that provide plugins-like architecture, the consumer has the power to decide which of the plugins are relevant and only install those.</li>
</ul>
<h4 id="heading-reduce-the-development-burden">Reduce the development burden</h4>
<p>Splitting a codebase into smaller units that are self-contained can reduce the build and test times in large projects. If the repository is becoming large, breaking it into smaller pieces can optimize test and build time.</p>
<p>Since all packages reside in the same repository, they are aware of each other and a change in one package can trigger only the relevant test and build chain.</p>
<p>Look at the diagram below. A change in package C results in only the build of application A and there is no need to build and test application B.</p>
<h3 id="heading-functionality">Functionality</h3>
<p>Monorepo tools should at least support 3 key functions:</p>
<ul>
<li>Bootstrapping or preparing the package environment, including linking the local packages among themselves.</li>
<li>Build the code. That might include transpilation and code bundling.</li>
<li>Test / validate the code: static analysis and test execution.</li>
<li>Publish the code to the package registry</li>
</ul>
<p>Let’s go over some of the tools that provide the needed functionality and understand how they do it.</p>
<h4 id="heading-lernahttpsgithubcomlernalerna"><a target="_blank" href="https://github.com/lerna/lerna">Lerna</a></h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681673773/d1bad302-f08c-4155-808d-91640bd16066.png" alt /></p>
<p><a target="_blank" href="https://lerna.js.org/">https://lerna.js.org/</a></p>
<p>This piece of an architectural gem is a dependency for almost 40,000 repositories on GitHub and is almost a synonym for monorepos in JS. A Lerna based repository is built from multiple directories, each one with a package.json file. To configure Lerna, it is only required to define the top-level directories that contain Lerna packages. The loose structure of Lerna lets it support any framework and language flavor, as the actions that can be performed on each package are defined and configured inside the package.json of each package.</p>
<p>Lerna supports the installation of all packages separately under each package’s folder, but also the hoisting of all packages to the root of the workspace, so install and update times are reduced. Lerna is also responsible for linking packages inside the repository, so packages that depend on other packages are linked locally.</p>
<p>To build and test the code you can execute a command on each package with a single Lerna command. Lerna runs the command on each package but does not provide a dependency build.</p>
<p>Publishing is where Lerna excels. Lerna support unified versioning or independent versioning. when publishing packages in the independent mode, only packages that have changed are going to get a version bump.</p>
<h4 id="heading-yarn-workspaceshttpsclassicyarnpkgcomendocsworkspaces"><a target="_blank" href="https://classic.yarnpkg.com/en/docs/workspaces/">Yarn Workspaces</a></h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681675338/5acb235b-4910-49a4-9ff9-3e2e083e992a.jpeg" alt /></p>
<p><a target="_blank" href="https://classic.yarnpkg.com/en/docs/workspaces/">https://classic.yarnpkg.com/en/docs/workspaces/</a></p>
<p>Yarn workspaces is also mentioned quite often as a tool for managing monorepos. Yarn repository structure is similar to the Lerna structure (and often they work together).</p>
<p>The workspaces functionality of Yarn, in version 1, only supports installation and bootstrapping of packages. Following a rough start, it is now stable and effective.</p>
<p>Yarn 2, currently in active development, is extending this functionality with functions similar to Lerna such as running commands on each package including parallel run and topological sort.</p>
<h4 id="heading-nxhttpsnxdevangular"><a target="_blank" href="https://nx.dev/angular">NX</a></h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681676541/13a24e0a-736f-4334-8035-fb95dfbb7155.png" alt /></p>
<p><a target="_blank" href="https://nx.dev/react">https://nx.dev/react</a></p>
<p>NX by nrwl is a monorepo for multiple applications, heavily inspired by the Angular CLI, but also extended to support React.</p>
<p>NX works in a centralized manner. An NX repository requires a centralized file (workspaces.json) that defines all the actions that can be performed on the workspace. To perform an action you need to define a dedicated code, called “builder” that runs on the package. A builder can build, test, lint, or any other action on each package.</p>
<p>NX also provides a schema that can be used as a boilerplate for each type of package inside the repository. Generating an NX package using the CLI also generates a boilerplate in the configuration file.</p>
<p>To support additional frameworks or tools, a dedicated builder needs to be configured for it. NX is geared towards bundling and compiling the full application, so it does not support the publishing of single packages.</p>
<p>NX supports distributed and incremental builds by executing only packages that are “affected” by changes. The NX paid cloud service is built to accelerate builds and tests by caching the already built packages and only building incremental differences.</p>
<h4 id="heading-bitdevhttpsbitdev"><a target="_blank" href="https://bit.dev/">Bit.dev</a></h4>
<p><a target="_blank" href="https://bit.dev"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681677938/f56c7c54-0656-435d-87df-0133382402f0.gif" alt /></a></p>
<p><a target="_blank" href="https://bit.dev">https://bit.dev</a></p>
<p><a target="_blank" href="https://bit.dev">Bit.dev</a> takes a different approach altogether which extends beyond the single repository. Bit works in a distributed manner where each package can reside in any repository. Bit server (self-hosted or a paid cloud service) is storing versions of the packages from all repositories that changed it, similar to NPM.</p>
<p>Bit does not require to have each package defined with a package.json, and it can generate a package.json based on the code and global configuration.</p>
<p>Each package in Bit is associated with a “compiler” which contains the full configuration required to build each component. Similarly, a component is associated with a “tester” that contains test configuration.</p>
<p>The SaaS version of <a target="_blank" href="https://bit.dev">Bit.dev</a> also supports the publishing of packages so they can be consumed as NPM packages.</p>
<h4 id="heading-honorable-mentions">Honorable mentions</h4>
<p>There are some additional tools worth watching:</p>
<p><a target="_blank" href="https://github.com/boltpkg/bolt"><strong>Boltpkg</strong></a><strong>,</strong> also under active development, is employing a similar approach to Lerna and Yarn 2.</p>
<p><a target="_blank" href="https://bazel.build/"><strong>Bazel</strong></a> is a google tool for large monorepos. Bazel goes beyond Javascript and supports multi-languages, and can also run on parallel machines (so it is useful if you are Google and own a cloud infrastructure).</p>
<p><a target="_blank" href="https://rushjs.io/"><strong>RushJS</strong></a>, developed by Microsoft is another tool that should support the full lifecycle of monorepos, including bootstrapping, incremental and full builds, and publishing. Rushjs did not get a lot of traction yet, but with the Microsoft -&gt; Github -&gt; NPM acquisition chain, it might mature and become more popular.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>There is not yet a clear winner in the monorepos arena, but a lot of interesting things are going in that domain. If you find any mistakes I have made, or a cool tool that should be mentioned, do not hesitate to leave a comment.</p>
<h3 id="heading-learn-more">Learn More</h3>
<p>[<strong>Code Principles Every Programmer Should Follow</strong><br /><em>YAGNI, Law of Demeter, Single Responsibility and other useful principles for better coding.</em>blog.bitsrc.io](https://blog.bitsrc.io/code-principles-every-programmer-should-follow-e01bfe976daf "https://blog.bitsrc.io/code-principles-every-programmer-should-follow-e01bfe976daf")<a target="_blank" href="https://blog.bitsrc.io/code-principles-every-programmer-should-follow-e01bfe976daf"></a></p>
<p>[<strong>How to Publish React Components</strong><br /><em>How to quickly publish React components from any repository.</em>blog.bitsrc.io](https://blog.bitsrc.io/how-to-publish-react-components-d04e0a7e33b9 "https://blog.bitsrc.io/how-to-publish-react-components-d04e0a7e33b9")<a target="_blank" href="https://blog.bitsrc.io/how-to-publish-react-components-d04e0a7e33b9"></a></p>
<p>[<strong>Composing Documents with MDX: Markdown for the Component Era</strong><br /><em>Using React UI components and MDX content components to compose and style a markdown document. Then, publish all…</em>blog.bitsrc.io](https://blog.bitsrc.io/composing-documents-with-mdx-markdown-for-the-component-era-ed9d87142703 "https://blog.bitsrc.io/composing-documents-with-mdx-markdown-for-the-component-era-ed9d87142703")<a target="_blank" href="https://blog.bitsrc.io/composing-documents-with-mdx-markdown-for-the-component-era-ed9d87142703"></a></p>
]]></content:encoded></item><item><title><![CDATA[Deep dive into Monorepos]]></title><description><![CDATA[title: Deep dive into Monorepos published: true description: tags: Lerna, Bazel, Yarn, Monorepo What are the best tools to use with a monorepo? As with any…]]></description><link>https://tallybarak.com/deep-dive-into-monorepos</link><guid isPermaLink="true">https://tallybarak.com/deep-dive-into-monorepos</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Mon, 01 Jun 2020 17:44:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681273070/a1f1ff97-0651-4432-8214-95d17485083f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>title: Deep dive into Monorepos
published: true
description: 
tags: Lerna, Bazel, Yarn, Monorepo</p>
<h2 id="heading-coverimage-httpsdev-to-uploadss3amazonawscomijw4tlw9pm1fu4u3xx6atjpeg">cover_image: https://dev-to-uploads.s3.amazonaws.com/i/jw4tlw9pm1fu4u3xx6at.jpeg</h2>
<p>What are the best tools to use with a monorepo? As with any other software design consideration, the answer is - it depends on what you need. 
But when we talk about monorepo, we should also clarify what a monorepo is. Too often, when discussing mono-repo, the answers resemble the people in the image on the cover of this article. </p>
<p>Allow me to share a few thoughts and clarification on this. </p>
<h1 id="heading-whats-inside-a-monorepo">What's inside a monorepo?</h1>
<p>The one commonality for all mono-repos is that somewhere in their folder structure, you will find multiple package.json files, each with its own name. So, while we commonly use the term mono-repo, an adequate term is probably a multi-package repo.</p>
<p>The "monorepo" (and now quotes are appropriate) may contain all of your company projects, or can just have a single project broken into packages. </p>
<p>Look under the Facebook GitHub organization and you will find that most of their open-source projects, such as Jest, React, CRA, Docosaurus, are built as monorepo. So clearly, this is not a mono (single) repo, but poly (multi) repos. </p>
<p>So your initial consideration should be the scope of your monorepo. Your monorepo may contain: </p>
<ul>
<li>All of the organization's backend and front end applications</li>
<li>Your backend applications or microservices and their shared code split into packages.</li>
<li>Utilities shared between your backend and frontend applications (.e.g types, schemas).</li>
<li>Components shared between multiple frontend applications (such as design system)</li>
</ul>
<h1 id="heading-goals">Goals</h1>
<p>Next, you should consider the goals you are trying to achieve by using a multi-package repo. Some of the answers are: </p>
<ul>
<li>Increase code quality using small loosely-coupled units </li>
<li>Publish packages independently  </li>
<li>Decrease installation footprint at the consumer (i.e. install package X only if I consume it. Select between installing package Y and Z)</li>
<li>Reduce maintenance overhead across repos</li>
<li>Reduce build / CI time by JIT building and testing.</li>
</ul>
<p>It is essential to decide where you are heading as this impacts the decisions you make later. </p>
<h1 id="heading-organizing-a-monorepo">Organizing a monorepo</h1>
<p>I found three dimensions that impact the organization of the mono repo. </p>
<p>a) Installation (bootstrapping)
b) Development flow 
c) Publishing</p>
<h2 id="heading-installation">Installation</h2>
<p>In multiple packages repo, each package.json contains its NPM packages dependency. The dependencies include runtime dependencies (i.e., <code>dependencies</code>) and development time dependencies (<code>devDependencies</code>). </p>
<p>The two methods for installing the dependencies are: </p>
<ul>
<li>Install in a node_modules folder inside each package</li>
<li>Install all shared node_modules in the root of the project, and only packages that their versions collide inside each package. </li>
</ul>
<p>The latter method is called "hoisting," and it is working because of <a target="_blank" href="https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders">node package resolution algorithm</a>. When resolving modules, the process "bubbles" until it finds the packaged. </p>
<p>Hoisting npm packages is useful in saving time and disk space. (As we all learned, node_modules are the heaviest object in the universe.) </p>
<p>Installing local node_modules ensures that the package correctly defines its requirements in the package.json manifest. It can also avoid the cases of <a target="_blank" href="https://rushjs.io/pages/advanced/phantom_deps/">phantom dependencies</a> and <a target="_blank" href="https://rushjs.io/pages/advanced/npm_doppelgangers/">doppelgangers</a>.</p>
<p>The standard tools to enable NPM hoisting are Lerna and Yarn (using workspaces). Lerna supports hoisting also for NPM, but in general, is doing a lesser job than Yarn. </p>
<h2 id="heading-development-workflow">Development workflow</h2>
<p>The package.json must include the runtime dependencies for each NPM package (or else it will fail to run). 
But what about the development dependencies? </p>
<p>There are two main options on how to build and test our packages: </p>
<ul>
<li>Centralized development</li>
<li>Federated development</li>
</ul>
<h3 id="heading-centralized">Centralized</h3>
<p>In a centralized development, the development tools are only 
installed and configured once.  </p>
<p>├── babel.config.json
├── jest.config.js
├── node_modules
│   ├── jest
│   └── typescript
├── packages
│   ├── package-a
│   │   └── package.json
│   └── package-b
│       └── package.json
└── tsconfig.json</p>
<p>Test configuration, for example, will point to search all of the <code>.spec</code> or <code>.test</code> files all over the repository and run them.
Build can run centralized but need to generate a build directory for each package (for publishing it). In some cases, you may need to create dedicated scripts to achieve this. </p>
<p>A centralized development workflow is useful when building multiple packages that use the same technology. In such a case, it reduces the maintenance overhead, as there is only a single place for configuring the workflow. 
A centralized workflow can become a maintenance nightmare if you are adding multiple different technologies.   </p>
<h3 id="heading-autonomous-workflow">Autonomous workflow</h3>
<p>In a federated workflow, each package is autonomous in the tools, process, and configuration it uses. Here is an example of such a folder structure:</p>
<p>└── packages
    ├── package-a
    │   ├── jest.config.js
    │   ├── node_modules
    │   │   ├── jest
    │   │   └── typescript
    │   ├── package.json
    │   └── tsconfig.json
    └── package-b
        ├── babel.config.json
        ├── node_modules
        │   ├── babel
        │   └── mocha
        └── package.json</p>
<p>A decentralized model supports heterogeneous packages, such as backend and frontend applications. This comes with the price tag of higher maintenance overhead.  </p>
<p>Lerna can be used to support both workflows. Lerna supports autonomous workflow by specifying each command separately in each package.json and running it centrally using the <code>lerna run</code> command. It can also run ad-hoc commands using the <code>lerna exec</code> syntax. 
Nx takes a slightly different approach by using a centralized configuration file (<code>workspace.json</code>, heavily inspired by angular cli configuration) and specifying a dedicated toolchain for each package. 
Bazel is another tool that supports monorepo development workflow. Bazel not only decentralized the workflow process but can harness multiple machines to work concurrently. Bazel is suited for very large mono-repos, and can easily become overkill for smaller ones. </p>
<h2 id="heading-publishing">Publishing</h2>
<p>The last part of using the package is publishing it to a public or private NPM registry. Packages published to a registry are versioned. You can publish all packages with a single version or each package with its own version. Publishing a version also implies publishing a changelog. According to the method selected, there will be a single changelog for all packages or a separate one for each published package.  </p>
<p>Lerna is probably the leading tool for multi-package publishing (in fact, this is what the Facebook repos are using it for). Under the hood, Lerna uses Npm and Yarn pack and publish commands. </p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Deciding to go "monorepo" is only the first step in the journey. It derives a set of further decisions to optimize the repo for the specific project needs.</p>
]]></content:encoded></item><item><title><![CDATA[Documentation made nicer with visuals]]></title><description><![CDATA[5 tips on the best way to add diagrams to your product's documentation.]]></description><link>https://tallybarak.com/documentation-made-nicer-with-visuals</link><guid isPermaLink="true">https://tallybarak.com/documentation-made-nicer-with-visuals</guid><category><![CDATA[documentation]]></category><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Mon, 17 Feb 2020 13:29:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714721768621/bb31301e-5cba-451e-934a-2af3204cef4a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>8 months ago I have joined <a target="_blank" href="https://bit.dev">bit.dev</a> as head of the developer's experience. One of the first tasks I had on my plate was a major facelift for our <a target="_blank" href="https://docs.bit.dev">documentation</a> site. Bit.dev is a revolutionary product and requires people to understand its mental model to be successful in implementing it. For me, that meant good documentation with plenty of drawings. Diagrams and visuals are the best tools in documentation when trying to convey complex concepts. Today bit.dev documentation site has multiple visuals reducing the time it takes for the developers to learn the tool.</p>
<p>Let me share some of the tips on building those visuals that worked well for me during this process.</p>
<h1 id="heading-grab-ideas-from-design-meetings">Grab ideas from design meetings</h1>
<p>What should be in the diagrams? Here is a tip that can work pretty well: pick the papers that fell during design meetings. When people are explaining the concepts of their work, this is probably the best diagram that will help someone from the outside to understand what they are talking about. Grab your mobile and take a photo of the paper sketches and the whiteboards. These diagrams are the skeleton for your future visuals.</p>
<h1 id="heading-be-independent">Be independent</h1>
<p>Transforming those sketches into documentation level visuals require some graphical skill. Naturally, this means that we rely on the designer in our company or team. This method did not really work for me. I needed to be independent and to quickly change my diagrams as well as creating new diagrams when ideas pop up. Sadly, this means that I had to use a lot of the designer time to come up with an idea, review it with the designer, proof-read his work and restart the whole process when I wanted to change something.<br />Soon enough I decided to put my faith in my own hands which led to the next two tips...</p>
<h1 id="heading-get-inspired-by-designers">Get inspired by designers</h1>
<p>Unless you have a degree in graphical design (in addition to technical and literature degree), there are probably quite a few things you do not know about design. It is best then to ask the designer for an initial version and start working from that point. Notice the little tricks the designer made: line endings, backgrounds and so on.</p>
<p><img src="https://storage.googleapis.com/static.bit.dev/docs/images/workflow-projects.svg" alt="bit.dev documentation diagram" /></p>
<p>In the diagram above I combined some of the elements created by our designers, such as the element depicting a component or the light background. I used those tricks in all of my next designs based on this initial inspiration.</p>
<h1 id="heading-use-a-simple-tool">Use a simple tool</h1>
<p>If you feel comfortable with Sketch or Photoshop - go ahead. Those tools are extremely powerful. However, you can achieve great results in diagraming with much simpler tools. I decided to use Google Slides. It is easy to use, easy to share (Google, you know...), and can export the diagrams the drawing in png, jpg or even SVG format with ease.</p>
<h1 id="heading-be-consistent">Be consistent</h1>
<p>Last but not least, is to keep consistency. There is something very pleasant about consistency, and the readers are more likely to feel at home when the diagrams follow a standard format. Using a standard color palette, typography, shapes, and metaphors make the reader feel at home when they browse through your documentation. I put all my drawings in a single slideware, so I have all the colors and shapes in place and I can easily copy what I need between my drawings.</p>
<p>I hope these simple tips will encourage you to also add diagrams to your documentation. After all, we are all attracted to nice colors and shapes.</p>
]]></content:encoded></item><item><title><![CDATA[The Digest Guide to React Styling]]></title><description><![CDATA[title: The Digest Guide to React Styling published: true description: Notes from understanding React Styling tags: React,CSS,CSS-in-js,css-modules Are you…]]></description><link>https://tallybarak.com/the-digest-guide-to-react-styling</link><guid isPermaLink="true">https://tallybarak.com/the-digest-guide-to-react-styling</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Tue, 17 Dec 2019 17:19:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681288875/d81eef0a-7bdb-40c7-99a2-b78456dad977.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p>title: The Digest Guide to React Styling
published: true
description: Notes from understanding React Styling
tags: React,CSS,CSS-in-js,css-modules </p>
<h2 id="heading-coverimage-httpsthepracticaldevs3amazonawscomirbgzk6dc1bdody83ngqtpng">cover_image: https://thepracticaldev.s3.amazonaws.com/i/rbgzk6dc1bdody83ngqt.png</h2>
<p>Are you confused over the different styling approaches for components in React? So am I. 
To avoid verbosity, I summed it up in 5 bullet points and 4 images, with some footnotes. 
Use this article as a starting point for exploring deeper with a basic understanding of how each method works. </p>
<h2 id="heading-css-in-the-dom">CSS in the DOM</h2>
<p>Here is how you can add styles to a web page:</p>
<h3 id="heading-external-stylesheet">External stylesheet</h3>
<pre><code>&lt;link rel=<span class="hljs-string">"stylesheet"</span> type=<span class="hljs-string">"text/css"</span> href=<span class="hljs-string">"mystyle.css"</span>&gt;
</code></pre><p>The styles are global and applied on the whole DOM</p>
<h3 id="heading-embedded-internal-stylesheet">Embedded (internal) stylesheet:</h3>
<pre><code>&lt;style&gt;
   p {
        font-family: georgia, serif; 
        font-size: x-small;
    }
&lt;/style&gt;
</code></pre><p>Also here, the styles are global and applied on the whole DOM</p>
<h3 id="heading-inline-styles">Inline styles</h3>
<pre><code>&lt;h1 style=<span class="hljs-string">"color:blue;"</span>&gt;This is a Blue Heading&lt;/h1&gt;
</code></pre><p>The style is local and impacts only the element</p>
<h3 id="heading-scoped-css-deprecated">Scoped CSS - deprecated!</h3>
<p>https://caniuse.com/#feat=style-scoped</p>
<h3 id="heading-shadow-dom-css">Shadow DOM CSS</h3>
<p>It is a style tag that only applied to the shadow DOM part where it is included. </p>
<h2 id="heading-css-in-react">CSS in React</h2>
<p>Let's see how React styles are translated to the above (internal and external stylesheet and inline styles): 
General note: Any .CSS file bellow can also be a CSS with pre-processor such as Less or Scss file. </p>
<h3 id="heading-basic-styling">Basic Styling</h3>
<p><strong>With styles</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681283865/2cbe81a1-8b91-49e2-b639-70d141c4b4fc.png" alt="Alt Text" /></p>
<p><strong>With classes</strong>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681285133/50a35857-704f-4631-aa73-b6b15673587d.png" alt="Alt Text" /></p>
<ul>
<li>Styling is processed during build time. </li>
<li>Styles can be exported to an external stylesheet. </li>
<li>Dynamic styling can be achieved using changing inline styles or applying dynamic classes. </li>
</ul>
<h3 id="heading-css-modules">CSS Modules</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681286403/44431bfe-e0d3-4f6a-b66b-ac1a5e603a01.png" alt="Alt Text" /></p>
<ul>
<li>Styles are created during build time (Webpack)</li>
<li>Styles can be exported to an external stylesheet.</li>
<li>In Create-React-App CSS modules are differentiated from regular CSS by adding the <code>.module.css</code> suffix to the files. Webpack configuration in CRA refers to this suffix. </li>
</ul>
<h3 id="heading-css-in-js">CSS in JS</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681287522/061c6350-7589-462a-aded-06eb18dea165.png" alt="Alt Text" /></p>
<ul>
<li>Styles are created during runtime. </li>
<li>Some libraries allow extracting static CSS parts to external CSS stylesheet (critical CSS). </li>
<li>In CSS in JS JS objects are playing the role of classes. </li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Sharing Components is Caring]]></title><description><![CDATA[Photo by Sophie Elvis on Unsplash Here is a scenario which may look very familiar: SOSA company has two code repositories: Shoppy is an online shopping…]]></description><link>https://tallybarak.com/sharing-components-is-caring-f8235cf1a0c</link><guid isPermaLink="true">https://tallybarak.com/sharing-components-is-caring-f8235cf1a0c</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Wed, 03 Jul 2019 15:01:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681689689/17802144-a887-4870-ac88-362e33fbbf77.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h4 id="heading-a-real-life-story-of-one-component-and-two-applications">A real-life story of one component and two applications</h4>
<p>Photo by <a target="_blank" href="https://unsplash.com/@thetechnomaid?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sophie Elvis</a> on <a target="_blank" href="https://unsplash.com/search/photos/sharing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p>
<h3 id="heading-why-share-components">Why Share Components?</h3>
<h4 id="heading-a-story-of-two-applications">A story of two applications</h4>
<p>Here is a scenario which may look very familiar:</p>
<p>SOSA company has two code repositories: <strong><em>Shoppy</em></strong> is an online shopping e-commerce application, and <strong><em>Stocky</em></strong> — an inventory management application. Jane is a developer in the Shoppy team and her colleague, John, is working in the Stocky team.</p>
<p>Recently, Jane has developed a great product-list component for displaying products in Shoppy. John has seen Jane’s component and would like to use it in Stocky. He realized that this component would be great to be used in Stocky to show the existing products and updating their current Stock. John is inquiring into Jane’s code and sees that the product-list component depends on an external npm package for showing a grid.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681682976/1305fe9e-1481-4212-8b3e-b2d6e897a854.jpeg" alt /></p>
<h3 id="heading-how-to-share-components">How To Share Components?</h3>
<p>What are John and Jane options? They really just want to quickly share the component, and keep it updated later on.</p>
<h4 id="heading-option-1-copy-the-product-list-source-code">Option 1 — Copy the product-list source code</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681684189/64943897-abb8-4945-96cb-21b4c3779d3c.jpeg" alt /></p>
<p>Copying Source Code Between Projects</p>
<p>John has access to the Shoppy repository and he is copying the source code of the product-list component to the Stocky repo. However, to make the code work he needs to install the npm dependency and copy the product viewer code.</p>
<p>The process of identifying all the required dependencies in the project is lengthy, cumbersome and requires multiple copies. Not only the source code needs to be identified, but also related test files need to be copied and maintained in the Stocky repository.</p>
<p>At the end of the process, 2 separate copies of the same component exist in 2 different repositories. Any fix or change that Jane is doing in her component locally will not be reflected in John’s code and he will need to implement the same change himself.</p>
<p>It saved John some coding and debugging, but the future does not look bright.</p>
<h4 id="heading-option-2-moving-the-component-to-a-separate-repository">Option 2 — Moving the Component to a separate Repository</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681685496/7d908d41-59fc-424d-a4a2-ab8376dbdc20.jpeg" alt /></p>
<p>Use a shared repository</p>
<p>John Asks Jane to move the code into a separate repository. This requires refactoring work from Jane. Luckily for John, Jane is a friend and is willing to do so. Both John and Jane are now installing the component from the third repository. While this initially works well, Jane’s work is now harder, as she ends up working on multiple repositories.</p>
<p>Jane and John also understand that moving components to a separate repository will require a distribution tool, such as using a private npm registry to share or using git sub-modules or sub-trees to access multiple repositories.</p>
<p>Working with multiple repositories also adds a great overhead to debugging. Debugging the package outside of its original context, as well as using links to work with it in the application context can become hard.</p>
<p>The team also realizes that while this pinpoint solution may be useful for few components, it will become a maintenance nightmare in the long run when more and more components will need to be shared with other repositories.</p>
<h4 id="heading-option-3-using-a-mono-repo">Option 3 — Using a mono-repo</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681686875/0c4259a6-a92a-47ab-af7f-592460c8f535.jpeg" alt /></p>
<p>Using a single repository for all projects</p>
<p>In the last years, using a single repository (mono-repo) for all applications has become a common practice. The main goal was to try and solve exactly this projects reusability problem. In a mono-repo, all projects are located in a single repository, and multiple applications can share the same code.</p>
<p>John and Jane would like to have a single mono-repo for the applications, however, this requires an overall organizational change, which is not likely to happen in the forthcoming future.</p>
<p>While mono-repo has multiple benefits, it also has some drawbacks:</p>
<ul>
<li>Established in an existing environment — if a project is starting from the ground up, building a single mono-repo can be the right solution. However, integrating this process into an existing infrastructure may require a large investment which is not always possible.</li>
<li>Mono-repos require strong tooling to let it work as a set of single repositories. While some larger companies such as Google use such tools, not every organization has the capacity to introduce those changes. You can read more <a target="_blank" href="https://medium.com/@mattklein123/monorepos-please-dont-e9a279be011b">here</a>.</li>
<li>Mono-repos make it hard to secure parts of the code. In some scenarios, it is not desirable for everyone to be able to change any piece of code. Also, it is impossible to let only certain people, such as external contractors or collaborators view all of the code. It’s also hard to open-source parts of it.</li>
</ul>
<h3 id="heading-a-better-option-share-components-in-the-cloud">A Better Option — Share Components in the Cloud</h3>
<p><a target="_blank" href="https://bit.dev"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681688089/bd36a521-d5f2-4b3a-9306-7aea48910b30.jpeg" alt /></a></p>
<p>Share only the components via the cloud</p>
<p>A better option will be for Jane and John to <strong>focus</strong> <strong>only on the component</strong> they want to share. That means that only the code of the component, with all of its files and dependencies, will be shared between the projects. Both sides could suggest changes and receive updates to the component.</p>
<p>Let’s think of how this workflow should be like:</p>
<ul>
<li>The original author, Jane, marks all the files she wants to share that create a single reusable component or module. That means — the relevant HTML and CSS files if exist as well as test specs that are related (Jane is famous for writing good tests).</li>
<li>A designated tool will bundle all the files of the component with all their dependencies to create a shareable unit that is uploaded to the cloud.</li>
<li>John is building his own app and could really use Jane’s component.</li>
<li>John is searching in their shared component cloud, looking for such a component. He finds Jane’s component.</li>
<li>John is playing with a live version of the component, checks the requirements and is also peeking at the code. He decides to use it.</li>
<li>John can choose if he wants to install the component as a project dependency (that is, doing an npm or yarn install), or if he wants the actual code of the component to be added to his project.</li>
<li>Whenever there is a new change, John can update the component with the new installation or with the updated source code.</li>
<li>If John sources the actual code of the components in his project he can make modifications to the component and submit them back to Jane while keeping the changes in his project.</li>
<li>Jane can accept John’s changes and fixes, and submit a new version of the component. John can now install the new version.</li>
</ul>
<p>In this flow, only the code of the component, with all of its dependencies is packed and uploaded to a remote cloud service. No local repo cloning, no complex setup.</p>
<p>The original project, Shoppy, still has the code of the component and Jane can make any changes she wants and test it to it without going through advanced maneuvers.</p>
<p>Stocky will only consume a reflection of the original code, which is still pointing to its original source. John is able to get any updates Jane is making to the component, but without copying the code.</p>
<p>The projects code structure will stay the same and there is no need to go through large code restructuring to get to the point that the code is shared.</p>
<blockquote>
<p>Learn more about <a target="_blank" href="https://bit.dev">Bit</a> to share components between your projects in the cloud, collaborate and build faster as a team.</p>
</blockquote>
<h3 id="heading-summary">Summary</h3>
<p>Sharing components between projects can accelerate projects development. It can simplify the maintenance of your apps, and help you build better software. And yet, existing practices do not always achieve the efficiency and effectiveness we would expect. To make code reuse and components sharing a breeze, a new generation of tools is needed, built for components</p>
<p>[<strong>Share reusable code components as a team · Bit</strong><br /><em>Easily share reusable components between projects and applications to build faster as a team. Collaborate to develop…</em>bit.dev](https://bit.dev "https://bit.dev")<a target="_blank" href="https://bit.dev"></a></p>
<p>[<strong>teambit/bit</strong><br /><em>Easily share code between projects with your team. - teambit/bit</em>github.com](https://github.com/teambit/bit "https://github.com/teambit/bit")<a target="_blank" href="https://github.com/teambit/bit"></a></p>
]]></content:encoded></item><item><title><![CDATA[More Unfolding on iOS Signings]]></title><description><![CDATA[Welcome to the rescue zone. If you have come so far, it is probably because you found yourself cursing Apple for their iOS signing process and the…]]></description><link>https://tallybarak.com/more-unfolding-on-ios-signings-b6886236d7fc</link><guid isPermaLink="true">https://tallybarak.com/more-unfolding-on-ios-signings-b6886236d7fc</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Sat, 30 Mar 2019 14:25:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681696752/e3bcacd1-0b5b-442c-88b2-3db29d4a7cda.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to the rescue zone. If you have come so far, it is probably because you found yourself cursing Apple for their iOS signing process and the confusion around it. Stay calm, we have all been there and survived to tell.</p>
<p>This is not another how-to article. Plenty of those exist around. Here, I will try and draw a higher level picture of how the iOS signing work. Getting a mental model of the process is useful when things go less smoothly and you need to trouble shoot your errors.</p>
<p>This article is written and published on March 2019. XCode 10.2 is the current version. This is important as Apple keeps changing its signing methods and capabilities, so at some time this article will also become obsolete.</p>
<h3 id="heading-why-signing">Why Signing</h3>
<p><em>(What is this good for? Skip this if you are already convinced signing is important).</em></p>
<p>There are 2 reasons that applications need to be signed:</p>
<ul>
<li>To allow Apple to authorize each app before it is available for users and signing the app ensures that the app has not been modified by bad people and that no malicious code into your app.</li>
<li>To allow Apple make heaps of money by limiting builds to run only on Macs and by charging for its developer’s account license.</li>
</ul>
<p>The Apple “Closed Garden” philosophy drives them to not only limiting the applications downloaded from the App Store, but anything installed on your device. So if you are now developer that built a beautiful shiny Tinder for cats, you will not be able to install it on your device unless you will get an explicit signed permission from Apple to do so.</p>
<p>And this is where the whole mysterious process of application signing starts.</p>
<h3 id="heading-the-signing-entities">The Signing Entities</h3>
<p><em>(The participants in iOS signing hell)</em></p>
<p>There are 3 things Apple needs to know to allow you installing any app on any device: Who? What? Where?</p>
<ol>
<li>Who — a certificate will identify the owner</li>
<li>What — the application to develop and install</li>
<li>Where — on which devices the apps will be installed.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681692626/6365edcf-2fb5-4654-a08f-73dd137433a1.png" alt /></p>
<p>The signing identities</p>
<p>Let’s start with the easy one:</p>
<h4 id="heading-device-identifier">Device Identifier</h4>
<p>A unique device identifier (<strong>UDID</strong>) is a 40-character string assigned to Apple devices. In the mac it can be found by accessing the hardware info. On iPhone / iPad this site can help finding it: <a target="_blank" href="http://whatsmyudid.com/">http://whatsmyudid.com/</a></p>
<p>Next is the Application identified. This is something that you can make up:</p>
<h4 id="heading-application-identifier-app-id-bundle-id">Application Identifier (App Id / Bundle Id)</h4>
<p>This is a key that identifies your application. It is customary to have the App Id as a reverse order of the domain, e.g. com.company.app. Application IDs are owned by a team and therefore they need to be registered on the Team developer portal.</p>
<p>The application Id needs to be registered on the team’s developer portal. Each app also specifies what Apple services to be used. Such services can be push notifications (via APS → Apple Push Services. Only apple can push notifications to devices), iCloud, Siri and so on.</p>
<p>[To be really accurate the com.company.app is called the bundle Id. The App Id is a combination of the Team identifier and the Bundle ID, such as ABCD1234.com.company.app]</p>
<p>The most complex one is the certificate.</p>
<h4 id="heading-certificate">Certificate</h4>
<p>The certificate’s goal is to verify that a person or a team is the true owner of the application, and that its identity cannot be stolen by another person. A person is identified by its Apple Id, and it can also belong to a team.</p>
<p>A development team is created on the Apple Developer Portal and the administrator can add additional developers to it. Adding developers (with certain privileges) mean that the team administrator is trusting them to distribute the application on his behalf.</p>
<p>A new application is defined on the provisioning portal and the users are becoming the owners in this application. But how can someone tell if an App was actually modified only by this user? For this the user can generate a signing certificate. A signing certificate works (very loosely) like a broken heart necklace. Apple holds one half of the necklace and the user needs to present the other half when changing the application so Apple will know they are who they said they are.</p>
<p>Signing certificate metaphor</p>
<p>A certificate is identified by a string of 8 characters and also contains the name of the certificate holder (developer or team). There are 2 types of certificates:</p>
<ul>
<li><strong>Developer certificate</strong> is generated for a specific person, or in fact a single Apple Id and can used during development (we will see how in a moment)</li>
<li><strong>Distribution certificate</strong>, as the name implies, allows distributing the application for users who are not the developers. The distribution certificated is generated to an organization or a team (which might be only a single person).</li>
</ul>
<h3 id="heading-provisioning-profiles">Provisioning Profiles</h3>
<p><em>(Putting them all together)</em></p>
<p>As described above, apple wants to make sure what software is installed on which device. A provisioning profile is where everything comes together: it tells who is the authorized user, what is the application and which devices can be used.</p>
<p>There are 4 different types of provisioning profiles used in different stages of the application development:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681693947/4f3a5beb-f28c-4269-a9d9-8f653dd52941.png" alt /></p>
<ul>
<li><strong>Development</strong> — this is used to enable a developer install the application during development to specific devices during the development process. The device needs to be connected to the development computer. This provisioning profile is using a development certificate, and the devices that will be used need to be registered and installed.</li>
<li><strong>Ad Hoc</strong> — This enables user to install the application on a known and limited number of devices for testing purposes. The devices do not need to be physically connected to the development computer, but they are need to be known and registered on the development portal. Although this provisioning profile is a using a distribution certificate, an application signed with adhoc provisioning profile cannot be uploaded to the App Store.</li>
<li><strong>App Store</strong> — this is the provisioning profile that is used for distributing the application to the app store. It uses a distribution certificate, but is not limited to specific devices.</li>
<li><strong>Enterprise</strong> — a 4th type of provisioning profile is aimed for larger organizations that want to control which applications are limited on their users’ devices. It requires joining Apple Enterprise program (yes, more money!) and is using special registration.</li>
</ul>
<p>Each provisioning profile has a unique identifier The provisioning profiles are signed and embedded in the application, but a short googling will tell you how to extract it from the packaged IPA.</p>
<p>The Provisioning files themselves are signed and cannot be viewed just by looking at the file, but thanks to this guy <a target="_blank" href="https://github.com/ealeksandrov/ProvisionQL">https://github.com/ealeksandrov/ProvisionQL</a>, you can install a finder add-on that will show you all the information inside easily.</p>
<h3 id="heading-the-signing-verification-process">The signing Verification Process</h3>
<p><em>(What do they do with it?)</em></p>
<p>The last part is to explain, in a very high level, how the provisioning profile verification work. But first let’s talk about 2 tools involved in the process:</p>
<ul>
<li>Keychain is a safe that knows how to store secret items (and in fact is a nice UI for the openssl protocol used for Apple security).</li>
<li>XCode build tools (and the UI) know how to sign the application with the correct signing profile.</li>
</ul>
<h4 id="heading-step-1-generating-signing-certificate">Step 1 — Generating Signing certificate</h4>
<ul>
<li>An authorized user logs into the developer portal and requests a signing certificate for itself.</li>
<li>The user generates a private key locally (a half of broken heart) and sends a reflection of it to Apple via the developer portal.</li>
<li>Apple creates the certificate (the other half of the broken heart) based on the private key signed.</li>
<li>The newly created certificate is installed in the development computer of the user. The certificate is only valid when it is paired with the private key signed.</li>
</ul>
<h4 id="heading-step-2-generating-the-provisioning-profile">Step 2 — Generating the Provisioning profile</h4>
<ul>
<li>The singing certificate is registered on the portal, and now the user can log into the portal and request a provisioning profile. The user specifies the application and the type of provisioning profile that is requested.</li>
<li>For development or adhoc provisioning profiles the user specifies the devices from the list of registered devices.</li>
<li>For development provisioning profile the user may define a set of valid development certificates that can use the same provisioning profile.</li>
<li>The user downloads the provisioning profile to the development machine. The default location for storing the provisioning profiles is ~/<strong>Library</strong>/MobileDevice/Provisioning Profiles.</li>
</ul>
<h4 id="heading-step-3-building-the-application">Step 3 — Building the application</h4>
<ul>
<li>Application is built and signed on a development computer. The signing is done with a provisioning profile that fits what is specifies in the xcode signing properties.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681695403/9b1d141f-4dbe-4ca1-863d-859aad73536a.gif" alt /></p>
<p>Credit: someone on the internet. I am still thankful for saving me the snapshot trouble.</p>
<p>For a debug signing a provisioning profile that has a development certificate is required, and for release signing a distribution certificate will be needed. Of course, only provisioning profiles that were generated for the specific application that is built can be used.</p>
<p>If the app is aimed for App Store distribution it needs to be uploaded via the <a target="_blank" href="https://itunesconnect.apple.com/login">iTunes Connect portal</a>. App that has any provisioning profile other than App Store will be rejected.</p>
<p>If you use the automatic signing, XCode will attempt to find a suitable provisioning profile, but if it will not find one it will simply access the developer portal APIs and generate a new one according to the type of build.</p>
<h4 id="heading-step-4-installing-the-application">Step 4 — Installing the Application</h4>
<p>The last step occurs when a user tries to install the application.</p>
<ul>
<li>If the application is downloaded from the App Store after it has been approved, it can installed on any device (there are some limitation such as regional, but this will be ignored for the time being).</li>
<li>If the app is Ad Hoc or Development, when attempting to install on a device, the UDID will be checked and the installation will be approved or rejected.</li>
</ul>
<h3 id="heading-fastlane">Fastlane</h3>
<p><em>(Can we avoid the mess?)</em></p>
<p>If you have been working with iOS applications for a while in an organization, you might have learned about Fastlane. Fastlane has multiple tools (actions) that can simplify the process of building iOS and Android applications.</p>
<p>Fastlane tools allow you to perform the certificates and provisioning profiles generation without the need to access the developer portal. It is even more useful as it let’s you share provisioning profiles between users on your team using a shared git repository, such as one on Github. All certificates used by the team will be stored on the git repository and users can use them to build their application without the need to access the developer portal.</p>
<p>Fastlane documentation is quite comprehensive for each action, but somewhat lacking on explaining the concepts. It is useful to know that Fastlane has 3 actions that are relevant for iOS signings:</p>
<ul>
<li><a target="_blank" href="https://docs.fastlane.tools/actions/cert/">Cert</a> (alias for <code>get_certificates</code>)— allows managing certificates profiles</li>
<li><a target="_blank" href="https://docs.fastlane.tools/actions/sigh/">Sigh</a> (alias for <code>get_provisioning_profile</code>) — allows managing certificates profiles</li>
<li>Match (alias for <code>sync_code_signing</code> ) — allows synchronizing certificates and provisioning profiles with the centrally managed repository of certificates and provisioning profiles.</li>
</ul>
<p>With this understanding, you can now go back to fastlane documentation and learn more about the different options.</p>
<h3 id="heading-summary">Summary</h3>
<p>I am no hacker or security expert. My first experience with iOS signing was a terrified one. I have noticed my company’s team certificate on my keychain and was sure that accidentally deleting will make our application access lost forever. The truth is that no actions done locally can harm the application in an irreversible manner. At worse, you will need to generate a new profile or certificate. (Note: Developer portal and iTunes Connect can have more destructive impact).</p>
<p>If this article has reduced your level of anxiety from Apple signing and helped clarifying things. If you have found some horrible mistakes, do point them out. I would hate to mislead people. If you find this helpful , a clap, a share, or both will be highly appreciated.</p>
]]></content:encoded></item><item><title><![CDATA[Testing Stenciljs Components]]></title><description><![CDATA[Photo by Alvaro Reyes on Unsplash Update: The newer version of this article is here. Changes made in Stencil make this article mostly irrelevant. Note…]]></description><link>https://tallybarak.com/testing-stenciljs-components-3a48cd209dce</link><guid isPermaLink="true">https://tallybarak.com/testing-stenciljs-components-3a48cd209dce</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Sat, 21 Apr 2018 13:18:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/liMvhbUq4Xg/upload/badac7f692b2b4aa57c7b9d42897f8a3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Photo by <a target="_blank" href="https://unsplash.com/photos/4eTnTQle0Ks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alvaro Reyes</a> on <a target="_blank" href="https://unsplash.com/search/photos/computer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p>
<blockquote>
<p>Update: The newer version of this article is <a target="_blank" href="https://medium.com/@tally_b/unit-testing-stenciljs-1-0-c4e902a4e63c?postPublishedType=initial">here</a>. Changes made in Stencil make this article mostly irrelevant.</p>
<p>Note: Tests were adopted to changes performed in Stencil 0.7.19</p>
</blockquote>
<p>Testing stenciljs is still in its infancy, and I found myself collecting some best practices and code examples on testing the component. The first batch is here:</p>
<p>The application tested is a Todo app, similar to the ones on the T<a target="_blank" href="http://todomvc.com/">odomvc</a> website. The application is based on the <a target="_blank" href="https://github.com/ionic-team/stencil-app-starter">stencil-app-starter</a> and has 3 components:</p>
<ul>
<li><p><a target="_blank" href="https://github.com/Tallyb/stencil-todo/blob/master/src/components/my-app/my-app.tsx">my-app:</a> App main component</p>
</li>
<li><p><a target="_blank" href="https://github.com/Tallyb/stencil-todo/blob/master/src/components/todo-list/todo-list.tsx">todo-list</a>: manages the list of todo items</p>
</li>
<li><p><a target="_blank" href="https://github.com/Tallyb/stencil-todo/blob/master/src/components/todo-item/todo-item.tsx">todo-item</a>: A single todo item editing, removing and completion.</p>
</li>
</ul>
<h3 id="heading-describe-components-instance-tests">Describe Component’s Instance Tests</h3>
<p>The first method to test components is by creating an instance of the component class:</p>
<p>import { TodoList } from './todo-list';<br />let comp = new TodoList();</p>
<h4 id="heading-it-should-test-complex-logic">It should test complex logic *</h4>
<p>( *The logic of getRemainingItems is not really complex)</p>
<p>This is a great way to test that the logic of a method of your class is done correctly with a large number of variances. Don’t just go the happy path! add few edge cases to see you are handling those.</p>
<p>import { TodoList } from './todo-list';<br />const ITEMS = [<br />{ name: 'an item', done: false},<br />{ name: 'an item', done: false},<br />{ name: 'an item', done: true}<br />];</p>
<p>it('should display remaining items', () =&gt; {<br />let comp = new TodoList();<br />comp.items =ITEMS;<br />expect(comp.getRemainingItems()).toEqual(2);<br />});</p>
<h4 id="heading-it-should-test-events-and-payloads">It should test events and payloads</h4>
<p>You can test that events are fired with correct payload by spying on the class events emitting and verifying the received payload:</p>
<p>it('should remove item from list on remove', () =&gt; {<br />let comp = new TodoList();<br />comp.items = ITEMS;<br />const changedSpy = jest.fn();<br />comp.todoItemsChanged = {<br />emit: changedSpy<br />};<br />//const changedSpy = jest.spyOn(comp.todoItemsChanged, 'emit');<br />comp.removeItem(1);<br />expect(changedSpy).toHaveBeenCalledWith([<br />{ name: 'Item 1', done: false},<br />{ name: 'Item 3', done: true}<br />]);</p>
<p>});</p>
<p>In most cases these tests better occur on rendered components, but if you have (again) relatively complex rendering logic, you can test it faster with component instance.</p>
<h3 id="heading-describe-rendered-component-tests">Describe Rendered Component Tests</h3>
<p>The second method for testing (and where most tests should occur) is by rendering a component and performing action on it. The first thing is to define a test window to be used. The window is (as of 0.7.25) a <a target="_blank" href="https://github.com/jsdom/jsdom">jsdom</a> window:</p>
<p>let win;<br />beforeEach(() =&gt; {<br />win = new TestWindow();<br />});</p>
<h4 id="heading-it-should-test-components-rendering">It should test Components Rendering</h4>
<p>Use <a target="_blank" href="https://facebook.github.io/jest/docs/en/snapshot-testing.html">Jest snapshots</a> to render the items with different parameters. The following test will only render the TodoList component (shallow).</p>
<p>it('should render with items list', async () =&gt; {<br />let element = await win.load({<br />components: [TodoList],<br />html: ''<br />});<br />element.items = [<br />{name: 'Milk the cow', done: true},<br />{name: 'Buy milk', done: false}<br />];<br />win.flush();<br />expect(element).toMatchSnapshot();<br />});</p>
<p>You can also test integration between components by deep rendering components:</p>
<p>it('should do deep rendering', async () =&gt; {<br />let element = await win.load({<br />components: [TodoList, TodoItem],<br />html: ''<br />});<br />element.items = ITEMS;<br />win.flush();<br />expect(element).toMatchSnapshot();<br />});</p>
<h4 id="heading-it-should-test-user-events">It should test user events</h4>
<p>When certain user interactions occur (click, resize etc.), an event may be fired up. The tests should catch the events and evaluate the received payload to be the correct one after the interaction occurred. The following is an example of testing that the event was raised when a todo item was toggled:</p>
<p>it('should emit item toggled', async () =&gt; {<br />let eventSpy = jest.fn();<br />win.document.addEventListener('itemToggled', eventSpy);<br />element.querySelector('.toggle').click();<br />expect(eventSpy).toHaveBeenCalled();<br />});</p>
<p>Or we can use it in integration test with the parent component. In this tests we verify that todo-list has emitted an event with the item changed:</p>
<p>it('should toggle second item', async () =&gt; {<br />let eventSpy = jest.fn();<br />win.document.addEventListener('todoItemsChanged', eventSpy);<br />let toggles = element.querySelectorAll('.toggle');<br />toggles[1].click();<br />win.flush();<br />expect(eventSpy).toHaveBeenCalled();<br />// event called data is in the mock.calls of the jest function<br />expect(eventSpy.mock.calls[0][0].detail[2].done).toEqual(true);<br />});</p>
<h4 id="heading-it-should-test-user-dom-events">It should test user DOM events</h4>
<p>User DOM events, such as change of an input are not triggered automatically with jsdom. The todo-item uses the <code>&lt;input onChange={ev =&gt; triggeredFunction(ev)}</code> . To trigger the onChange during test we need to create the event and dispatch it on the input element:</p>
<p>it('should emit item changing', () =&gt; {<br />// create a spy on the event and attach to listener<br />let eventSpy = jest.fn();<br />win.document.addEventListener('itemChanged', eventSpy);</p>
<p>// Click on the label to enable input<br />element.querySelector('label').click();<br />win.flush();</p>
<p>// create the change event<br />let change = win.document.createEvent('Event');<br />change.initEvent('change', true, false);</p>
<p>// Set value on the input element &amp; dispatch the change event<br />let value = 'New Value';<br />let input = element.querySelector('.edit');<br />input.value = value;<br />input.dispatchEvent(change);</p>
<p>// expectations<br />expect(eventSpy).toHaveBeenCalled();<br />expect(eventSpy.mock.calls[0][0].detail).toEqual(value);<br />});</p>
<p>You can also expand this test to be an integration test with the parent todo-list:</p>
<p>it('should update second item', async () =&gt; {<br />let eventSpy = jest.fn();<br />win.document.addEventListener('todoItemsChanged', eventSpy);<br />let todo = element.querySelectorAll('todo-item')[1];<br />todo.querySelector('label').click();<br />win.flush();</p>
<p>// create an input event<br />let change = win.document.createEvent('Event');<br />change.initEvent('change', true, false);</p>
<p>// Set value on the input element &amp; dispatch the event<br />let value = 'New Value';<br />let input = element.querySelector('.edit');<br />input.value = value;<br />input.dispatchEvent(change);<br />win.flush();</p>
<p>// expectations<br />expect(eventSpy).toHaveBeenCalled();<br />expect(eventSpy.mock.calls[0][0].detail[1].name).toEqual(value);<br />});</p>
<p>The full repo is <a target="_blank" href="https://github.com/Tallyb/stencil-todo">here</a>.</p>
<p>Happy testing and share your best practices.</p>
]]></content:encoded></item><item><title><![CDATA[Part IV — Win Some. Lose Some.]]></title><description><![CDATA[Quick recap: In previous parts we covered the notion of E2E testing, extended to the mobile world and discussed the tooling required. Software design is…]]></description><link>https://tallybarak.com/part-iv-win-some-lose-some-5d35c91e8c00</link><guid isPermaLink="true">https://tallybarak.com/part-iv-win-some-lose-some-5d35c91e8c00</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Wed, 28 Feb 2018 05:48:26 GMT</pubDate><content:encoded><![CDATA[<p>Quick recap: In previous parts we covered <a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing/part-i-e2e-testing-and-selenium-ef031978ee20">the notion of E2E testing</a>, extended to <a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing/part-ii-not-only-desktop-6c0d22f7db33">the mobile world</a> and discussed the <a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing/part-iii-testing-environment-2da5f63d782b">tooling required</a>.</p>
<p>Software design is the art of trade offs. You make some decisions that will gain some value but will likely preclude some other benefits. A famous example is the <a target="_blank" href="https://en.wikipedia.org/wiki/Project_management_triangle">Project Management Triangle</a>, balancing between cost, time and scope.</p>
<p>A similar, but more specific triangle can be applied on E2E testing (although the above is still true for any project). I would claim that when you design your tests, you may balance between 3 factors:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681658162/49f64131-fd47-4c93-8eb4-5dd4ed373174.png" alt /></p>
<h4 id="heading-coverage-velocity">Coverage Velocity</h4>
<p>The coverage and the coverage velocity defines how many of your business flows are covered by the tests, and how fast you can achieve this coverage. As your requirements and hence your software functionality is likely to change often, it also means how fast you can adapt your tests to those changes.</p>
<p>The exact number of tests vary according to the specific domain. 20 test scenarios may provide a good coverage for a small consumer app, but will barely scratch the surface for a large enterprise web software.</p>
<p>Based on the resources you have, you can design your tests in a manner that will allow reuse of testing actions when creating new tests easily or tailor craft each testing scenario.</p>
<h4 id="heading-resilience">Resilience</h4>
<p>E2E tests are infamous for being flaky. Changes in the underlying software is one example, but also careless design that does not take into considerations the activity that occur in the system under the hoods, such as the time it takes to get the data from the server, can make the tests extremely brittle. Verifying each screen element prior to handling it and waiting until it is available reduces the chances of tests to break, but takes it costs elsewhere.</p>
<h4 id="heading-performance">Performance</h4>
<p>This simply says how long the tests will run. Releasing multiple times a day requires that the tests will run often and relatively fast. But with less frequent releases, extra minutes during the run may not be so critical, or may be compensated with additional hardware.</p>
<h3 id="heading-what-does-it-mean">What Does It mean?</h3>
<p>Writing a very small set of E2E tests, verifying basic scenarios such as login and a main flow, will probably run relatively fast (<strong>high performance</strong>) and will not break often (<strong>high resilience</strong>) but is only testing small part of functionality (<strong>low coverage</strong>). This is sometimes referred to as Smoke Tests (or Sanity tests).</p>
<p>Using automated recording tools (such as Selenium IDE or Katalon) can achieve a large number of tests in a short time (<strong>high coverage</strong>) and the tests may run fast with very explicit selectors (<strong>high performance</strong>), but are likely to be very brittle and prone to break on every small change in the system (<strong>low</strong> <strong>resilience</strong>).</p>
<p>Creating tests with lots of generic functions to select the elements can expedite the creation of additional tests (<strong>high coverage</strong>) and can make them relatively stable (<strong>high resilience</strong>), but will have a cost at execution time (<strong>low performance</strong>).</p>
<p>I will demonstrate the last example in a piece of code we use in our project. We have a function called SafeClick (code is in webdriver.io syntax):</p>
<p>export function safeClick(el, options?, timeout?) {<br />    options = options || {};<br />    browser.waitForExist(el, timeout);<br />    if (!options.skipVisible) {<br />        browser.waitForVisible(el, timeout);<br />    }<br />    let tagName = browser.getTagName(el);<br />    if (['button', 'input', 'textarea', 'a'].indexOf(tagName) &gt; -1 )     {<br />        browser.waitForEnabled(el, timeout);<br />    }<br />    browser.click(el);<br />}</p>
<p>This code is waiting for the element to exist, then checking the type of the element and if it is an element that can be enabled (i.e. not a div or a custom element), it will wait for it to become enabled and eventually perform the click.</p>
<p>This function enables us to write tests faster. We do not need to repeat in every test the wait for the element to become visible or enabled, and we are hiding this complexity away from the test scenarios, but at the same time we are paying an extra cost of superfluous browser access. In the above case, we will access the browser at least 4 times:</p>
<ul>
<li>Finding that the element exists</li>
<li>Finding the element tag name</li>
<li>Checking the element enable state</li>
<li>Clicking on the element.</li>
</ul>
<h3 id="heading-what-is-right-for-me">What is Right For me?</h3>
<p>Needless to say, there is no one correct answer for that. It is common to focus on performance of the tests and ignore other aspects, but eventually the correct answer is the one that serves your business goals the best.</p>
<p><em>Need someone to help you around the E2E testing world? Read the</em> <a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing"><em>whole series</em></a><em>. If you are happy and joyful — you may clap!</em></p>
]]></content:encoded></item><item><title><![CDATA[Part III— Testing Environment]]></title><description><![CDATA[Part I and part II of this series reviewed the tools that we can use in order to access the system under test — a browser-based a desktop or a mobile app…]]></description><link>https://tallybarak.com/part-iii-testing-environment-2da5f63d782b</link><guid isPermaLink="true">https://tallybarak.com/part-iii-testing-environment-2da5f63d782b</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Sat, 17 Feb 2018 08:23:13 GMT</pubDate><content:encoded><![CDATA[<p><a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing/part-i-e2e-testing-and-selenium-ef031978ee20">Part I</a> and <a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing/part-ii-not-only-desktop-6c0d22f7db33">part II</a> of this series reviewed the tools that we can use in order to access the system under test — a browser-based a desktop or a mobile app. But accessing the application is not sufficient to be able to execute the tests. For that we will need a full testing environment that will help us run the tests.</p>
<h3 id="heading-the-e2e-testing-environment">The E2E Testing Environment</h3>
<p>As described in the first part of the series, the E2E test is mimicking a user actions on the system at hand. It will usually work as follow:</p>
<ul>
<li><p>Perform a series of actions similar to what a user will do. Such as go to a specific url, <a target="_blank" href="http://www.google.com,">www.google.com,</a> enter some text “ [Meghan Markle](https://www.google.com/search?q=Meghan+Markle "Search for "Meghan Markle"")” into the input field and click the button labeled “Search”.</p>
</li>
<li><p>Define the results that you expect: title will contain the search text and you will see 10 results.</p>
</li>
<li><p>Run the test on your application with specific capabilities, such as the chrome browser on Android 8 device.</p>
</li>
</ul>
<p>The description of the actions and the assertions are defined in test files called Test Specs. Their format depends on the specific tool you use. The expected results (assertions) are also defined there. The specific environment requirements are usually described in a configuration file. The results will also be extracted into a file (or on the console).</p>
<p>To make all of this happen, we need a testing environment. Here is what the testing environment will know to do:</p>
<ul>
<li><p>Find all the files where your tests are described</p>
</li>
<li><p>Execute all the tests on the requested configurations</p>
</li>
<li><p>Spit out the results in a format we can read.</p>
</li>
</ul>
<p>So here is what we want it to look like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681632777/528f62ef-1af0-46b4-9216-9865ca23131a.png" alt /></p>
<p>Testing Environment Parts</p>
<h3 id="heading-testing-environment-parts">Testing Environment Parts</h3>
<p>Just like a car needs an engine, wheels and a steering wheel to make it move from one point to another, your testing environment need few parts, all connected, to run the tests:</p>
<h4 id="heading-test-framework">Test Framework</h4>
<p>The notion of whether an assertion result is good or bad is defined in the test spec. The test framework is reading the tests and translating them to browser commands. The responses received from the language bindings can also be asserted to understand if they are correct. Popular test frameworks (in JS world!) include Jasmine and Mocha with Chai for assertions.</p>
<h4 id="heading-language-bindings">Language Bindings</h4>
<p>The language bindings are the part that is talking to your Selenium Server (or a Selenium like server) to execute the commands. The language bindings have no notion of good or evil. They can only interrogate the browser if an item exist or not, what is the displayed value etc. Is the fact that that an element with id <code>#welcome</code> is visible is a good or a bad thing? Language bindings would not know. They can only report on the element state, or perform an action.</p>
<h4 id="heading-reporter">Reporter</h4>
<p>The reporter is collecting all the results from the assertions and outputs them in a friendly format.</p>
<h4 id="heading-test-runner">Test Runner</h4>
<p>Test runner is responsible for making everything play nicely together. It will gather all the test specs, send them to the test framework to start running them (one by one or in parallel). It will know how to trigger the tested environment and eventually it will activate the reporter for the results.</p>
<h3 id="heading-testing-frameworks-in-nodejs-world">Testing Frameworks in NodeJS World</h3>
<p>As the series is titled “The hitchhiker’s guide to E2E Testing in Javascript world”, we will focus on NodeJS based testing frameworks. Here is the list of the popular ones.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681634299/66ade42f-b3a8-4ff9-a1b8-c39860cd4a67.png" alt /></p>
<p>A specific attention should be given to <strong>Selenium Webdriver</strong> which is the Selenium official language bindings for Nodejs. It is included in the Selenium Github repository and was used as the basis for some other frameworks. But being an open source and standardized , additional language bindings emerged, dealing with different aspects (such as Node’s asynchronous nature) in different manners. (Testcafe is probably additional name worth mentioning that was omitted Above.</p>
<p>So which one is the right one for you? As with any design decision, there is no one decisive answer. It depends on your needs, on the company you work for, and on the tools you are familiar with. [spoiler alert: Webdriverio is my tool of preference] Let’s go over some of the considerations you may want to weigh into your decision:</p>
<h4 id="heading-popularity">Popularity</h4>
<p>Popularity is a not just about having many likes and shares. In the Open Source community, popularity is directly translated to tangible benefits:</p>
<ul>
<li><p>More people using the software which means lot of bugs were already identified and fixed (or worked around).</p>
</li>
<li><p>More people are likely to encounter an issue you are struggling with and already posted a github issue or answered a stack overflow question regarding the issue.</p>
</li>
<li><p>A live community maybe up and kicking on slack or on Gitter to respond to the most noob or complex questions and guiding you on best practices.</p>
</li>
</ul>
<p>A common measure for NodeJS packages’ popularity is the number of npm downloads. Check out this graph:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681636070/c1a345fd-215e-47d0-a6f5-2b365876646e.png" alt /></p>
<h4 id="heading-comprehensibility">Comprehensibility</h4>
<p>The speed at which you will be able to absorb the mental model of the testing library, the better your tests will be. Comprehensibility is achieved by having well organized and complete documentation, but also from the inherent complexity (or simplicity) of the tool itself.</p>
<p>The ability to find answers quickly within the documentation is a key for moving fast with the tool.</p>
<h4 id="heading-synchronous-support">Synchronous Support</h4>
<p>Node is asynchronous in nature. But tests are much more comprehensible when written in a synchronous manner. Almost all popular libraries have taken some approach in trying and hide the async complexity behind a sync-like syntax. The devil, as always, is in the details: does that work for errors as well? what if I need to include server requests?</p>
<p>Because the browser (or application) tests are also asynchronous in nature, a specific support that is worth noticing is for waits and retries. It will take a while until a page will render on screen and you will want your test to wait until the page is ready. This can be built into the library or you may need to manage waiting and retrying yourself.</p>
<h4 id="heading-configuration-flexibility">Configuration Flexibility</h4>
<p>As shown in the testing environment structure above, the configuration file is a major input to the tool. The tool flexibility is derived from the number of configuration options it has. Can you specify the wait time? the number of retries before it fails? What hooks are available to run your own code — before each session, or can you run a function before each spec file, or even each line of code? What parameters are available at each hook? Flexible tool will provide with lot of hooking and configuration options.</p>
<h4 id="heading-frameworks-support">Frameworks Support</h4>
<p>The testing framework may dictate a use of specific test language such as Mocha and provide assertions via Chai, and reporting with a specific report. Alternatively, it may provide you the flexibility to select your preferred stack. Using Jasmine with Allure reporting.</p>
<h4 id="heading-mobile-support">Mobile Support</h4>
<p>If you plan to run tests also on mobile devices, it is worth checking upfront what are the capabilities provided by the tool, based on your needs. Supporting mobile device means first of all — integration with Appium to access the mobile device. But it also means access to mobile specific capabilities: mobile gestures (swipe, pinch), mobile actions (rotate, turn network on and off), file access, setting language and so on.</p>
<h3 id="heading-why-webdriverio">Why Webdriver.io?</h3>
<p>As noted in the spoiler alert above, I ended up with Webdriver.io. Here is why:</p>
<ul>
<li><p>Best mobile support of all other tools. Easy integration with Appium and a set of mobile specific commands.</p>
</li>
<li><p>Easy configuration with an excellent plug in systems that allows you to pick your testing framework of choice (Mocha, Jasmine or Cucumber)</p>
</li>
<li><p>A comprehensive model, including the support for async backed by good documentation and a lively Gitter channel.</p>
</li>
<li><p>Framework flexibility. I ended up with Cucumber, and will explain the reasons later on in the series.</p>
</li>
</ul>
<p><em>Need someone to help you around the E2E testing world? Read the</em><a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing"><em>whole series</em></a><em>. If you are happy and joyful — you may clap!</em></p>
]]></content:encoded></item><item><title><![CDATA[Part II — Not Only Desktop]]></title><description><![CDATA[In Part I we covered how Selenium is used for testing desktop browsers. But, hey, it’s 2018 and testing desktop web is only a part of the story. We also…]]></description><link>https://tallybarak.com/part-ii-not-only-desktop-6c0d22f7db33</link><guid isPermaLink="true">https://tallybarak.com/part-ii-not-only-desktop-6c0d22f7db33</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Thu, 01 Feb 2018 12:05:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681641955/0c100c15-8ce1-4f98-9106-d690b7c1c936.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In <a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing/part-i-e2e-testing-and-selenium-ef031978ee20">Part I</a> we covered how Selenium is used for testing desktop browsers. But, hey, it’s 2018 and testing desktop web is only a part of the story. We also have Web applications running on mobile devices (and on other platforms such as TV and wearables which we will skip as my knowledge in this area is limited to non existent…). While this topic is covered in many articles, we will go thru the main areas so to have better understanding how Selenium may be used to test on non desktops.</p>
<h3 id="heading-a-mixture-of-platforms">A Mixture of Platforms</h3>
<p>One way to understand the various platform is to try to look at it as a matrix. On one axis we have the various operating systems on which the software will run. And on the other axis we have the technology used for developing it:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681639366/23545e0d-833b-474c-888f-3c6df4cdb6c5.png" alt /></p>
<p>Platform Matrix</p>
<h4 id="heading-operating-systems">Operating Systems</h4>
<p>There are 2 main types of platforms that exist: desktop and Mobile (actually, these lines are becoming blurred with things like Chromebook on one hand and <a target="_blank" href="https://www.winehq.org/announce/3.0">wine</a> on the other), but let’s stay there for a minute. Desktop and Mobile platform run a specific set of Operations Systems. On Desktop that is Windows, Linux and MacOS. On Mobile the popular operating systems are iOS (for Apple products) and Android (for the rest of the Universe).</p>
<h4 id="heading-development-technology">Development Technology</h4>
<p>On those Operating systems we can run 3 types of applications:</p>
<ul>
<li><strong>Web based app</strong> — that means applications that run inside a browser installed on our platform, such as Chrome or Firefox. The application is developed in “Web Technology” — meaning the technology that the web browser can understand and execute: HTML pages, CSS and Javascript files. Chrome and Firefox are cross platform browsers that can run on a large variety of Operations Systems, both desktop and mobile. Some browsers are limited to specific OS, such as Edge or Safari.</li>
<li><strong>Native Applications</strong> — those are applications that are compiled to run on a specific Operating system. When referring to mobile, this is a native code development such as Swift for iOS and Java for Android. On desktop OS it can refer to any machine compiled development language such as c++.</li>
<li><strong>Hybrid Application</strong>s are, as the name implies is well, an hybrid of the two. It is a web browser wrapped with a native applications that runs on the target OS. This allows developing the code in web technologies, but execute it on different platforms. For mobile this is achieved by using Cordova tools (aka PhoneGap) for creating iOS, Android (and Windows) apps. For desktop operating systems this is achieved via Electron.</li>
</ul>
<h3 id="heading-testing-the-platforms-plethora">Testing the Platforms Plethora</h3>
<p>With so many technologies, we need tools to test all of them. Thanks to the fact that the Webdriver API are evolving as a standard for browser automation / testing, more tools could grow while leveraging the standard to develop tools for testing different types of applications. So:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681640693/e9e87e2d-4906-41b5-9b00-fac9849f97d4.png" alt /></p>
<h4 id="heading-desktop-apps">Desktop Apps</h4>
<p>Testing web apps on desktop is achieved by using a selenium server or by bypassing it with direct browser APIs, as described in the previous chapter.</p>
<p>Testing Hybrid apps, developed with Electron is by using Atom’s (Electron developers) Spectron.</p>
<h4 id="heading-mobile-apps">Mobile Apps</h4>
<p>Google’s Espresso can be used for Android apps only, but the dominating tools for testing mobile devices is currently Appium, mainly thanks to its support for both iOS, Android and Windows Mobile.</p>
<h3 id="heading-meet-appium">Meet Appium</h3>
<p><a target="_blank" href="http://appium.io/">Appium</a> is dated back to 2012, and has been re-written 3 times in 3 different languages. It was originally developed to support iOS testing automation but then was extended to support Android and recently also Windows. It is currently the only test framework that is cross mobile platform.</p>
<blockquote>
<p>Appium is built on the idea that testing native apps shouldn’t require including an SDK or recompiling your app. And that you should be able to use your preferred test practices, frameworks, and tools. Appium is an open source project and has made design and tool decisions to encourage a vibrant contributing community.</p>
</blockquote>
<p>Appium provides a Webdriver API compliant server that receives the requests from your favorite language bindings and transfers them to the Mobile platform. Talking to the Mobile device is by using the specific OS tools, such as UI Automator for Android and Xcode UI Test for iOS (and yes, also for Windows mobile).</p>
<p>Appium can be used for testing applications on mobile devices such as mobile web, but running a browser on the device, and native and hybrid apps, by installing and executing the specific app on the device.</p>
<p>Because Appium uses the standard APIs, any language binding that is generating Webdriver HTTP requests, may also be used for running Appium. Well, almost: the language for mobile OS testing need to support the APIs that are mobile device specific, such as install app, unlock device and perform a swipe gesture.</p>
<p><em>Need someone to help you around the E2E testing world? Read the</em> <a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing"><em>whole series</em></a><em>. If you are happy and joyful — you may clap!</em></p>
]]></content:encoded></item><item><title><![CDATA[Part I — E2E Testing and Selenium]]></title><description><![CDATA[E2E Testing, as it will be defined here, is testing your system from the system’s user perspective. The key difference between E2E tests and other…]]></description><link>https://tallybarak.com/part-i-e2e-testing-and-selenium-ef031978ee20</link><guid isPermaLink="true">https://tallybarak.com/part-i-e2e-testing-and-selenium-ef031978ee20</guid><dc:creator><![CDATA[Tally Barak]]></dc:creator><pubDate>Thu, 01 Feb 2018 11:29:40 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-what-is-e2e-testing">What is E2E Testing?</h3>
<p>E2E Testing, as it will be defined here, is testing your system from the system’s user perspective. The key difference between E2E tests and other functional tests (namely: unit and integration) is as follow:</p>
<ul>
<li>In a unit or integration test the testing framework is playing the role of software <strong>CODE</strong> that is <strong>RUNNING</strong> the tested code. The testing framework calls the functions in the tested code and will wait for responses from the code. The testing framework is very aware of the internals of your code, such as your development language.</li>
<li>In an E2E test, the testing framework is playing the role of a <strong>USER</strong> that is <strong>INTERACTING</strong> with the application like a user would do: click on the screen, input text and expect to see screen changes in response.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681617882/fd76eeee-580b-46e2-913b-eb4207054122.png" alt /></p>
<p>Unit and integration vs E2E testing</p>
<h4 id="heading-how-do-we-e2e-test-a-system">How do we E2E Test a system?</h4>
<p>Here are some good news: if you are about to test an application from the end user’s perspective, you do not really care about the internals of the system. If we are referring to a browser based app (or a mobile app, but we will get to that later), then all you have to do is run a browser and interact with it. You need to find a certain input field, paste some value, click on a button and wait until the system has reacted.</p>
<p>Was the front end developed in React, Angular or Vue? who cares. Is the backend based on Nodejs or Java or PHP? As long as it works it is fine. All is required is this magic system that will find this input field and button and will know how to interact with them .</p>
<h3 id="heading-meet-selenium">Meet Selenium</h3>
<p>This is where Selenium comes into picture. Selenium (actually: Selenium WebDriver<strong>)</strong> is a tool for <strong>automating web application</strong> testing, and in particular to verify that they work as expected.</p>
<p>Selenium originally started at 2004. Its original version was called Selenium RC (Remote Control), or Selenium 1.0. It worked by injecting javascript into the browser and executing its functions.</p>
<p>Later, Selenium was evolved into Selenium Webdriver, which uses the browser APIs to execute the required commands. Here is Selenium Webdriver’s architecture:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714681619697/240e053d-1e77-40e8-8273-010b0645feee.png" alt /></p>
<h4 id="heading-how-does-it-work">How Does it Work?</h4>
<ul>
<li>Selenium language bindings (in our favorite language) sends a JSON (HTTP) to the Selenium Server.</li>
<li>The server receives the request and translates it to the browser’s specific APIs</li>
<li>The server sends the request to the browser.</li>
<li>Browser executes the requests and send the response back to Selenium server</li>
<li>Selenium server returns the response the the HTTP request response.</li>
</ul>
<p>Let’s make this a bit more real:</p>
<p><strong>COMMAND POST </strong>  "/session"<br /><strong>DATA</strong> {"desiredCapabilities":{"javascriptEnabled":true,"locationContextEnabled":true...}<br /><strong>INFO</strong> SET SESSION ID 67379a3fab9310256090bd4fbe8839df<br /><strong>RESULT</strong> {"acceptInsecureCerts":false...}</p>
<p>Language Bindings: Create me a new session with the following characteristics: enable js, enable location and more…</p>
<p>Selenium server: I hear you. Here is the session Id I created for you!.</p>
<p><strong>COMMAND POST</strong>   "/session/67379a3fab9310256090bd4fbe8839df/url"<br /><strong>DATA</strong> {"url":"https://somewere.example.com/"}</p>
<p>LB: Great. Can you now go to that url I am sending you?</p>
<p>SS: yep! (no result body, just returning status code).</p>
<p>COMMAND POST   "/session/67379a3fab9310256090bd4fbe8839df/elements"DATA  {"using":"css selector","value":"#welcome"}RESULT  [{"ELEMENT":"0.7584651621036613-3"}]</p>
<p>LB: Can you find me an element on page using the css selector <code>#welcome</code></p>
<p>SS: Found it — here is its ID. Go ahead and use it if you want to do anything with this element.</p>
<p><strong>COMMAND POST</strong>   "/session/67379a3fab9310256090bd4fbe8839df/element/0.7584651621036613-3/click"<br />DATA  {}</p>
<p>LB: Click on it!</p>
<p>SS: ditto!</p>
<p>And so on and on…</p>
<h4 id="heading-what-are-those-apis">What are those APIs?</h4>
<p>The APIs that are now part of the spec that is governed by W3C (the web committee). They are called Webdriver APIs and are defined <a target="_blank" href="https://www.w3.org/TR/webdriver/">here</a>. Those API are not yet an official standard, but this is likely to occur at some point. Another <a target="_blank" href="https://github.com/w3c/webdriver/blob/master/implementation-report.md">useful link</a> points to the implementation status of the APIs in the major browser. It is a great source to check when your tests do not work as expected.</p>
<h4 id="heading-but-what-is-selenium-language-bindings-anyway">But, what is Selenium Language Bindings Anyway?</h4>
<p>Because the APIs are a standard, we can use any language to trigger them. So if you would like to write your tests in Java — go ahead. C++ or C#? sure. The language binding is running your tests and translates them to the JSON requests. Selenium originally was developed in Java, but later Language Bindings were added in other languages. You can see the various official language bindings in the <a target="_blank" href="https://github.com/SeleniumHQ/selenium">Selenium official repository</a>.</p>
<h4 id="heading-selenium-less-selenium">Selenium-less Selenium</h4>
<p>So, in order to test on a browser, we need to set a language binding server that will call the APIs, and a Selenium Server that will receive the Webdriver API requests and will dispatch the requests to the right browser.</p>
<p>This is true, BUT there is also a shortcut: the major browsers (read: Firefox, Chrome and lately Safari) can receive the HTTP API calls directly without the need to install Selenium Server. This means that in order to test chrome you can simply install <a target="_blank" href="https://sites.google.com/a/chromium.org/chromedriver/">Chromedriver</a> locally and send the requests to the default port 9515. Chrome will execute the commands and respond without the need to go thru the Selenium Server.</p>
<p>So if you are using non official language bindings, such as webdriverio, and a direct browser connection to, let’s say Chrome, you are running “Selenium” like tests (in fact — webdriver) without really using or installing Selenium itself.</p>
<h4 id="heading-selenium-grid">Selenium Grid</h4>
<p>One additional term you may encountered is the Selenium Grid. This is required when you are running multiple browsers or multiple operating systems. The Selenium Grid keeps track of all your sessions and will direct the correct session request to the relevant browser. If you are testing against single browser, this is not needed — see Selenium-less.</p>
<p><em>Need someone to help you around the E2E testing world? Read the</em> <a target="_blank" href="https://medium.com/the-hitchhikers-guide-to-e2e-testing"><em>whole series</em></a><em>. If you are happy and joyful — you may clap!</em></p>
]]></content:encoded></item></channel></rss>