Automated Selenium Testing with Jest and LambdaTest
Strategy

Automated Selenium Testing with Jest and LambdaTest


You know what the best thing is about building and running automated browser tests is? It means that the site you’re doing it on really matters. It means you’re trying to take care of that site by making sure it doesn’t break, and it’s worth the time to put guards in place against that breakages. That’s awesome. It means you’re on the right track.

My second favorite thing about automated browser tests is just how much coverage you get for such little code. For example, if you write a script that goes to your homepage, clicks a button, and tests if a change happened, that covers a lot of ground. For one, your website works. It doesn’t error out when it loads. The button is there! The JavaScript ran! If that test passes, a lot of stuff went right. If that fails, you’ve just caught a major problem.

So that’s what we’re talking about here:

  1. Selenium is the tool that automates browsers. Go here! Click this!
  2. Jest is the testing framework that developers love. I expect this to be that, was it? Yes? PASS. No? ERROR.
  3. LambdaTest is the cloud cross-browser testing platform you run it all on.

Are you one of those folks who likes the concept of automated testing but might not know where to start? That’s what we’re going to check out in this post. By stitching together a few resources, we can take the heavy lifting out of cross-browser testing and feel more confident that the code we write isn’t breaking other things.

Serenity Selenium now!

If you’re new to Selenium, you’re in for a treat. It’s an open source suite of automated testing tools that can run tests on different browsers and platforms on virtual machines. And when we say it can run tests, we’re talking about running them all in parallel. We’ll get to that.

It’s able to do that thanks to one of its components, Selenium Grid. The grid is a self-hosted tool that creates a network of testing machines. As in, the browsers and operating systems we want to test automatically. All of those machines provide the environments we want to test and they are able to run simultaneously. So cool.

Jest you wait ’til you see this

Where Selenium is boss at running tests, Jest is the testing framework. Jest tops the charts for developer satisfaction, interest, and awareness. It provides a library that helps you run code, pointing out not only where things fall apart, but the coverage of that code as a way of knowing what code impacts what tests. This is an amazing feature. How many times have you made a change to a codebase and been completely unsure what parts will be affected? That’s what Jest provides: confidence.

Jest is jam-packed with a lot of testing power and its straightforward API makes writing unit tests a relative cinch. It comes from the Facebook team, who developed it as a way to test React applications, but it’s capable of testing more than React. It’s for literally any JavaScript, and as we’ll see, browser tests themselves.

So, let’s make Jest part of our testing stack.

Selenium for machines, Jest for testing code

If we combine the superpowers of Selenium with Jest, we get a pretty slick testing environment. Jest runs the unit tests and Selenium provides and automates the grounds for cross-browser testing. It’s really no more than that!

Let’s hit pause on developing our automated testing stack for a moment to grab Selenium and Jest. They’re going to be pre-requisites for us, so we may as well snag them.

Start by creating a new project and cd-ing into it. If you already have a project, you can cd into that instead.

Once we’re in the project folder, let’s make sure we have Node and npm at the ready.

## Run this or download the package yourself at: https://nodejs.org/brew install node

## Then we'll install the latest version of npm
npm install [email protected] -g

Okey-dokey, now let’s install Jest. If you happen to be running a React project that was created with create-react-app, then you’re in luck — Jest is already included, so you’re good to go!

For the rest of us mortals, we’re going back to the command line:

## Yarn is also supported
npm install --save-dev jest

OK, we have the core dependencies we need to get to work, but there is one more thing to consider…

Scalability!

Yep, scale. If you’re running a large, complex site, then it’s not far-fetched to think that you might need to run thousands of tests. And, while Selenium Grid is a fantastic resources, it is hosted on whatever environment you put it on, meaning you may very well outgrow it and need something more robust.

That’s where LambdaTest comes into play. If you haven’t heard of it, LambdaTest is a cloud-based cross-browser testing tool with 2,000+ real browsers for both manual and Selenium automation testing. Not to mention, it plays well with a lot of other services, from communication tools like Slack and Trello to project management tools like Jira and Asana — and GitHub, Bitbucket, and such. It’s extensible like that.

Here’s an important thing to know: Jest doesn’t support running tests in parallel all by itself, which is really needed when you have a lot of tests and you’re running them on multiple browsers. But on LambdaTest, you can be running concurrent sessions, meaning different Jest scripts can be running on different sessions at the same time. That’s right, it can run multiple tests together, meaning the time to run tests is cut down dramatically compared to running them sequentially.

Integrating LambdaTest Into the Stack

We’ve already installed Jest. Let’s say Selenium is already set up somewhere. The first thing we need to do is sign up for LambdaTest and grab the account credentials. We’ll need to set them up as environment variables in our project.

From the command line:

## Mac/Linuxexport LT_USERNAME=<your lambdatest username> export LT_ACCESS_KEY=<your lambdatest access_key>

## Windowsset LT_ACCESS_KEY=<your lambdatest access_key>set LT_ACCESS_KEY=<your lambdatest access_key>

LambdaTest has a repo that contains a sample of how to set things up from here. You could clone that as a starting point if you’re just interested in testing things out.

Running tests

The LambdaTest docs use this as a sample test script:

const webdriver = require('selenium-webdriver');
const { until } = require('selenium-webdriver');
const { By } = require('selenium-webdriver');
const LambdaTestRestClient = require('@lambdatest/node-rest-client');

const username = process.env.LT_USERNAME || '<your username>';
const accessKey = process.env.LT_ACCESS_KEY || '<your accessKey>';

const AutomationClient = LambdaTestRestClient.AutomationClient({
  username,
  accessKey
});
const capabilities = {
  build: 'jest-LambdaTest-Single',
  browserName: 'chrome',
  version: '72.0',
  platform: 'WIN10',
  video: true,
  network: true,
  console: true,
  visual: true
};

const getElementById = async (driver, id, timeout = 2000) => {
  const el = await driver.wait(until.elementLocated(By.id(id)), timeout);
  return await driver.wait(until.elementIsVisible(el), timeout);
};

const getElementByName = async (driver, name, timeout = 2000) => {
  const el = await driver.wait(until.elementLocated(By.name(name)), timeout);
  return await driver.wait(until.elementIsVisible(el), timeout);
};

const getElementByXpath = async (driver, xpath, timeout = 2000) => {
  const el = await driver.wait(until.elementLocated(By.xpath(xpath)), timeout);
  return await driver.wait(until.elementIsVisible(el), timeout);
};

let sessionId = null;

describe('webdriver', () => {
  let driver;
  beforeAll(async () => {
    driver = new webdriver.Builder()
      .usingServer(
        'https://' + username + ':' + accessKey + '@hub.lambdatest.com/wd/hub'
      )
      .withCapabilities(capabilities)
      .build();
    await driver.getSession().then(function(session) {
      sessionId = session.id_;
    });
    // eslint-disable-next-line no-undef
    await driver.get(`https://lambdatest.github.io/sample-todo-app/`);
  }, 30000);

  afterAll(async () => {
    await driver.quit();
  }, 40000);

  test('test', async () => {
    try {
      const lnk = await getElementByName(driver, 'li1');
      await lnk.click();

      const lnk1 = await getElementByName(driver, 'li2');
      await lnk1.click();

      const inpf = await getElementById(driver, 'sampletodotext');
      await inpf.clear();
      await inpf.sendKeys("Yey, Let's add it to list");

      const btn = await getElementById(driver, 'addbutton');
      await btn.click();

      const output = await getElementByXpath(
        driver,
        '//html/body/div/div/div/ul/li[6]/span'
      );
      const outputVal = await output.getText();
      expect(outputVal).toEqual("Yey, Let's add it to list");
      await updateJob(sessionId, 'passed');
    } catch (err) {
      await webdriverErrorHandler(err, driver);
      throw err;
    }
  }, 35000);
});

async function webdriverErrorHandler(err, driver) {
  console.error('Unhandled exception! ' + err.message);
  if (driver && sessionId) {
    try {
      await driver.quit();
    } catch (_) {}
    await updateJob(sessionId, 'failed');
  }
}
function updateJob(sessionId, status) {
  return new Promise((resolve, reject) => {
    AutomationClient.updateSessionById(
      sessionId,
      { status_ind: status },
      err => {
        if (err) return reject(err);
        return resolve();
      }
    );
  });
}

The ‘Capabilities’ object look confusing? It’s actually a lot easier to write this sort of thing using the Selenium Desired Capabilities Generator that the LambdaTest team provides. That sample script defines a set of tests that can be run on a cloud machine that have browser configuration Chrome 72 and operating system Windows 10. You can run the script from the command line, like this:

npm test .single.test.js

The sample script also have an example that you can use to run the tests on your local machine like this:

npm test .local.test.js

Great, but what about test results?

Wouldn’t it be great to have a record of all your tests, which ones are running, logs of when they ran, and what their results were? This is where LambdaTest is tough to beat because it has a UI for all of that through their automation dashboard.

The dashboard provides all of those details and more, including analytics that show how many builds ran on a given day, how much time it took to run them, and which ones passed or failed. Pretty nice to have that nearby. LambdaTest even has super handy documentation for the Selenium Automation API that can be used to extract all this test execution data that you can use for any custom reporting framework that you may have.

Test all the things!

That’s the stack: Selenium for virtual machines, Jest for unit tests, and LambdaTest for automation, hosting and reporting. That’s a lot of coverage from only a few moving pieces.

If you’ve ever used online cross-browser tools, it’s kind of like having that… but running on your own local machine. Or a production environment.

LambdaTest is free to try and worth every minute of the trial.

Get Started



Source link

Top 7 Programming Languages for Test Automation in 2020
Strategy

Top 7 Programming Languages for Test Automation in 2020


So you are at the beginning of 2020 and probably have committed to a New Year’s resolution as a tester to leap into automation testing. However, to automate your test scripts, you need to get your hands dirty on a programming language, and that is where you are stuck! 

Or you are already proficient in automation testing through a single programming language and are thinking about venturing into new programming languages for test automation, along with their respective frameworks. You are bound to be confused about picking your next milestone. After all, there are numerous programming languages to choose from.

You may be looking for guidance to help you out with your test automation journey or your new chapter in the test automation diaries. Well, lucky for you, you landed in the right place! In this article, I am going to highlight the top 7 programming languages to look out for for test automation in 2020.

You may also like: Automated Testing: Improving Application Speed and Quality

1. Python

Python is an open-source programming language for test automation, machine learning, and more. The latest version of Python is 3.8.1. The major advantage that Python has over other programming languages for test automation is the easy learning curve due to the readability of the language.

As per Stack Overflow Developer Survey (2019), a whopping 73.1% voted for Python as the most-wanted programming language, indicating the popularity of the Python language.

Below are some of the primary reasons regarding the popularity of Python:

  • There are a number of libraries for Python programming language, and these libraries ease the job of the developer as they help in performing actions without writing much code.
  • Python is much more portable when compared to other programming languages.
  • The syntax of Python is easy to learn which makes it an ideal programming language even for beginners.
  • A strong presence of Python Community.

Selenium and Appium libraries for Python ease the job of automation testing and cross browser testing on desktop and mobile devices. PyUnit and Pytest are the most popular test automation frameworks in Python that are used for Selenium automation testing to perform automated cross browser testing.

2. Java

Java is a general-purpose programming language that is owned by the Oracle Corporation. Java is built on the principles of object-oriented programming. The language follows the WORA (Write Once, Run Anywhere) principle which brings a lot of cross-platform benefits.

Many large corporations use Java to maintain their back-end systems. There are more than 3 billion devices that are running applications built using Java. Though JUnit is a popular unit testing framework, a number of open-source automation testing frameworks have been developed using Java. Automated browser testing for a web product (website/web application) can be performed using JUnit with Selenium WebDriver.

3. JavaScript

As per Stack Overflow Developer Survey (2019), JavaScript attained the top spot in the ‘Programming, Scripting, and Markup Languages’ section in ‘Most Popular Technologies’ category.

JavaScript is also a great programming language for test automation that is predominantly used for front-end development. Many large consumer websites use JavaScript for front-end development and it is equally popular for automation testing.

One of the primary reasons for its dominance in test automation could be because of wider adoption of shift-left testing methodologies where developers are also involved in test code development. In shift-left methodology, QA team works in close collaboration with the development team to come up with efficient test automation implementation.

Developers also prefer to use JavaScript along with Selenium for test scenarios related to automated browser testing. It can also be used with remote Selenium Grid like LambdaTest without major changes in the source code.

Availability of a wide range of testing frameworks for unit testing and E2E (End-to-End) testing makes JavaScript a preferred programming language for test automation. Some of the top JavaScript test automation frameworks are:

  • Jest
  • Mocha
  • Jasmine
  • Nightwatch

4. C#

Created by Microsoft, C# is also trending as a programming language for test automation. It is designed on the concepts of object-oriented programming. It is one of the most popular languages using the .NET framework. 67% of the respondents in the Stack Overflow Developer Survey (2019) consider C# to be the most loved programming language for test automation, web development, and more. C# as a programming language for test automation is well-suited for applications that are based on Android, Windows, and iOS platforms. The latest version of C# is 8.0.

This programming language is slowly and steadily gaining momentum in the area of test automation. Due to powerful features of the language and its compatibility with Selenium WebDriver, many automation testers are inclined to use C# for automation testing and cross browser testing. Using the Page Object Model (POM) design pattern, testers can come up with efficient & maintainable test code.

There are a number of automation testing frameworks in C# that aid in Selenium automation testing or automated browser testing. Due to the availability of a wide range of test frameworks, many developers are considering C# for the development of test cases related to cross browser testing. Below are the most commonly used test automation frameworks in C#:

5. Ruby

Ruby is another programming language for test automation that is gaining momentum in the arena of test automation and automated browser testing. It is open-source in nature and is focused on simplicity & productivity. Like Python, Ruby is also easy to learn and implement. Human-friendly syntax and flexible object-oriented architecture make Ruby a powerful programming language.

Another interesting aspect is Ruby is the support of the growing community of Ruby users who are considered to be the most important strengths of the language. It is slowly becoming a preferred programming language for the creation of web applications. Developers can build useful applications with Ruby using much lesser lines of code.

Selenium framework also works with Ruby language hence it can be used for Selenium automation testing. Getting started with Ruby and Selenium is not challenging and you can execute the first cross-browser test with Selenium WebDriver and Ruby with very few lines of code.

There are a number of test automation frameworks in Ruby that help in cross-browser testing. Below are the most popular testing frameworks in Ruby:

  • Capybara
  • RSpec
  • Test::Unit

6. PHP

PHP is a server-side scripting language used for web development. However, it is also well-utilized as a programming language for test automation. If you are getting started with programming, you should definitely have a go at PHP. The difficulty level of PHP is low when compared to other backend programming languages like Python and Java.

PHP has good community support and a growing ecosystem. It offers XDebug, a powerful debugging and profiling tool that has powerful capabilities. It has support for a good number of test automation frameworks like:

  • Laravel Dusk
  • Codeception
  • PHPUnit
  • BeHat

7. SmashTest

SmashTest is a programming language for test automation that makes use of NodeJS. It is an open-source tool and language that enables the rapid generation of tests. The language is 10x faster but the documentation on SmashTest is not that great. When I was working on automation testing with SmashTest, I had to literally run from pillar to post for test case development.

Once I had a knack of the language, test automation with SmashTest was like a joyride. The language is easy to understand, has human-readable steps, and powerful reporting features that make it an ideal language to learn if you want to dabble with test automation.

Bottom Line

That was all for now. I am sure you must have your mindset on which programming language for test automation in 2020 you want to learn next. The languages that we listed so far are the most-preferred languages for automation testing as they have support for a good number of automation testing frameworks and a large user community. 

You can start your automation testing adventure with any of these programming languages. So what will be your pick? Do let me know if I missed out on your favorite programming language for test automation. Happy testing!

Further Reading

The What, Why, and How of Automation Testing

Get Started With Test Automation



Source link

Post image
Strategy

Help, jquery doesn’t work here? What can I do to fix it? (fi…


I’m just starting out and this is my first time trying to make a website but I can’t use other people’s code. How do I fix this?

I want to use this plugin here: https://github.com/oriongunning/gridder

Here’s what I have in my work:

<!doctype html>
<html>

<head>
    <Title>Thumbnail</Title>
    <link rel="stylesheet" href="css/style.css">
   

</head>

<!-- Gridder navigation -->

<body>
    <ul class="gridder">

        <!-- You can load specify which content is loaded by specifying the #ID of the div where the content is  -->
        <li class="gridder-list" data-griddercontent="#content1">
            <img src="https://www.thesprucepets.com/thmb/jbD_0GJnIVGmnLve7QDe9hCDbPU=/960x0/filters:no_upscale():max_bytes(150000):strip_icc()/Stocksy_txp33a24e10lxw100_Medium_214761-5af9d6d7875db900360440a7.jpg" />
        </li>
        <li class="gridder-list" data-griddercontent="#content2">
            <img src="https://icatcare.org/app/uploads/2018/06/Layer-1704-1920x840.jpg" />
        </li>
        <li class="gridder-list" data-griddercontent="#content3">
            <img src="https://icatcare.org/app/uploads/2018/06/Layer-1704-1920x840.jpg" />
        </li>

        <!-- You can also load html/ajax pages by replacing the #ID with a URL -->
        <li class="gridder-list" data-griddercontent="/content.html">
            <img src="https://icatcare.org/app/uploads/2018/06/Layer-1704-1920x840.jpg" />
        </li>
    </ul>
    <div id="content1" class="gridder-content"> Content goes here... </div>
    <div id="content2" class="gridder-content"> Content goes here... </div>
    <div id="content3" class="gridder-content"> Content goes here... </div>
  
    
    <script src="Files/jquery-3.4.1"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="dist/jquery.gridder.min.js"></script>
    <script>
        $(function() {
            // Call Gridder
            $('.gridder').gridderExpander({
                scroll: true,
                scrollOffset: 30,
                scrollTo: "panel", // panel or listitem
                animationSpeed: 400,
                animationEasing: "easeInOutExpo",
                showNav: true, // Show Navigation
                nextText: "Next", // Next button text
                prevText: "Previous", // Previous button text
                closeText: "Close", // Close button text
                onStart: function() {
                    //Gridder Inititialized
                },
                onContent: function() {
                    //Gridder Content Loaded
                },
                onClosed: function() {
                    //Gridder Closed
                }
            });
        });
    </script>

</body>
<!-- Gridder content --></html>

I have jquery downloaded on my computer as shown here: https://www.youtube.com/watch?v=kwb_YKRiq6c

I also used this tutorial as a guide: https://www.youtube.com/watch?v=MaEyWOI7Abs

I’m hoping it’ll look something like this in the end: http://oriongunning.github.io/gridder/

Here’s a picture of my code:

Post image

Any help would be really appreciated!



Source link

Venn diagram of things React does and doesn
Strategy

What React Does (and Doesn’t Do)


React doesn’t do a whole lot.

Don’t get me wrong – it’s great at what it does! But the things React is actually responsible for, in a fully-functioning production app? That list is pretty small. The universe of things you might call “a React problem” or “a React thing” is probably smaller than you think.

Venn diagram of things React does and doesn't do

What React Does

React is a UI library. It draws components on a web page. You write components as JavaScript functions or classes, pass them to React, and it will call them to figure out what the page should look like.

React components result in HTML on the page

After it’s done rendering the page, it stops. It is not constantly running in the background waiting for something to happen. You described what to render, React rendered it, and React is done.

The illusion of interactivity, then, is a series of starts and stops.

React Re-renders When You Trigger It

You click a button, that changes something, and React kicks off another render cycle.

An HTTP call comes back with new data to display: that kicks off another render cycle.

Maybe your code set up a listener for a websocket when it started up, and that listener is fired when a message comes in. That could kick off another render cycle.

Every one of these re-renders is in response to a state change. React only re-renders when you tell it to, by changing the state within a component.

React lifecycle: Initial render. Then state change, re-render, repeat.

So: if a button is clicked, but that click doesn’t trigger a state change? React will not know that anything happened. (again: it’s not constantly running in the background)

If a tree falls in the forest and that tree didn’t call setState… well, as far as React is concerned that tree is still standing.

What React Doesn’t Do

It might be easier to get a gut feel for what React does by seeing some of the things it doesn’t do.

Fetching Data

React doesn’t know how to make API calls. For that you need the fetch function built into browsers, or another library. Fetching data is not a React problem.

But you’ve gotta do it though, right? Because what good is an app without data? The key is that the actual fetching of the data is just some JavaScript code that runs, and you need to tell React when to run that code – either by queueing it up with the useEffect hook or using the componentDidMount lifecycle.

Centering a div

React cares exactly zero about styling. Think of it as generating the barebones HTML. React will put elements on the page, but everything after that is the job of CSS: how they appear, what they look like, how they’re positioned, and how centered or uncentered they are.

“How to center a div in React” is… not a React problem. It’s a CSS problem. You don’t need “react” in your Google query. Once you figure it out, use React to apply the right CSS class name to your components and voila 🙂

CSS is for positioning and alignment. React only puts elements on the page.

What about CSS-in-JS libraries like styled-components though? And UI frameworks like Material UI or Reakit? These libraries come with ready-made React components that include some of the CSS baked in, but make no mistake, it’s still CSS doing the styling under the hood.

Special Syntax (other than JSX)

Pop quiz! Which of these bits of syntax are React-specific (not JavaScript)?

a) function Button({ onClick }) { ... }
b) const Button = ({ onClick }) => ( ... )
c) const [flag, setFlag] = useState(false)

Go ahead, think it over.

If you answered “none of them” you got it right 🙂

Object Destructuring

a) function Button({ onClick }) { ... }

This first example is using object destructuring to unpack fields from the object that’s being passed to the function.

This is a common pattern for React components, because React passes an object containing the component’s props and their values – but this syntax is standard JavaScript (since ES6, anyway).

When a component is invoked with props, like this:

<Button onClick={someFunction} className="btn" />

React will end up calling the Button function with a plain JS object that looks like this:

{
  onClick: someFunction,
  className: "btn"
}

You can write components without that syntax, too. Destructuring the props object is just a nice shorthand. This does the same thing:

function Button(props) {
  const onClick = props.onClick;
  ...
}

Arrow Functions

b) const Button = ({ onClick }) => ( ... )

This second example is a combination of object destructuring with an arrow function. Arrow function syntax was added to JavaScript with ES6, and it’s a shorthand version of the longer function way of writing it.

No special React syntax here.

Array Destructuring

c) const [flag, setFlag] = useState(false)

This last one has no special React syntax either. The [flag, setFlag] on the left side of the = is using destructuring assignment to pick apart an array into two named variables.

The useState function is part of React, but there’s no special syntax here. It’s just the name of a regular function, which is part of React’s hooks API for state.

Maybe you feel this was a trick question. “It calls useState! That’s a React thing for sure!”

You’re right that useState is a function that React provides! But all of the syntax here: const, the square brackets for array destructuring, calling a function with the value false – that’s all JavaScript. useState is the name of a function. Just as function myThing() { } would create a function called myThing, React includes something like that to create the useState function.

Even the variable names aren’t special. You could write it like const [a, b] = useState(false) and React would never know nor care. It would work fine. (Your coworkers and/or your future self would probably have something to say about those names, though! Conventions are useful for a reason 🙂

Interpreting Your Components

React is responsible for calling your components, but it doesn’t parse and execute them line by line as an interpreter would. Components are JavaScript functions, so executing them is still the browser’s job.

Rendering a List of Items

Here’s one more for you: which parts of this are React syntax? (some of it actually is, this time!)

function ItemList({ items }) {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>
          {item.name}
        </li>
      )}
    </ul>
  )
}

This code shows the React way to render a list, and the JSX syntax (all the HTML-looking stuff with the <angle brackets>) actually is syntax that isn’t part of JavaScript. JSX is a React thing. (some other frameworks support it too)

JSX lets you embed the result of JavaScript expressions, though, so everything inside {curly braces} is real actual JavaScript syntax.

In my head I think of this as flipping back and forth between contexts. I see <ul> and I think “I’m in JSX now” – which means I can write more tags like <li> or whatever, but I can’t write regular JavaScript.

But then I see a single open brace, and that signifies “I’m back to JavaScript”. Inside those braces I can write JavaScript expressions. That word expression is important though, because I can’t write statements like if or const thing = 7 or a while loop. Only expressions, a.k.a. things that evaluate to a value.

items.map is the first thing inside the brace: that is regular JavaScript code, invoking the map function on the array of items.

Into the map call we’re passing an arrow function, item => .... This function describes how to transform the list of items into a list of something else. It takes one item item at a time, and returns a new thing, “mapping” the item onto another value.

Array .map function maps each item into a new value

The result of the items.map call is the array of <li>s, and React knows how to render an array of items (as long as they have a key, anyway).

After the closing curly brace } we’re back to JSX-land until the closing </ul> tag.

What else doesn’t React do?

There’s a ton more stuff to do in a web app: Saving stuff to the database. Querying the database. Serving web pages. Sending push notifications. Whatever your app does, there’s a very high chance that React doesn’t do most of it 🙂 (React does none of those things)

Next time you open up Google, and you’re about to type “how to do XYZ in React”, pause for a second and ask yourself whether XYZ is a thing that React does, or if it’s just a thing that your app does. What technology is responsible for that piece of the puzzle? Draw out a block diagram to map out the chain of events. You’ll get better results that way.

And if you’re not sure? Do some searching. When you start to get the feeling that none of the results are answering your question, almost like nobody has ever had this problem before – take heart, because that’s probably not true! But you might be asking the wrong question.

Success! Now check your email.



Source link

JavaScript Libraries Are Almost Never Updated Once Installed
Strategy

JavaScript Libraries Are Almost Never Updated Once Installed


Cloudflare helps run CDNJS, a very popular way of including JavaScript and other frontend resources on web pages. With the CDNJS team’s permission we collect anonymized and aggregated data from CDNJS requests which we use to understand how people build on the Internet. Our analysis today is focused on one question: once installed on a site, do JavaScript libraries ever get updated?

Let’s consider jQuery, the most popular JavaScript library on Earth. This chart shows the number of requests made for a selected list of jQuery versions over the past 12 months:

Spikes in the CDNJS data as you see with version 3.3.1 are not uncommon as very large sites add and remove CDNJS script tags.

We see a steady rise of version 3.4.1 following its release on May 2nd, 2019. What we don’t see is a substantial decline of old versions. Version 3.2.1 shows an average popularity of 36M requests at the beginning of our sample, and 29M at the end, a decline of approximately 20%. This aligns with a corpus of research which shows the average website lasts somewhere between two and four years. What we don’t see is a decline in our old versions which come close to the volume of growth of new versions when they’re released. In fact the release of 3.4.1, as popular as it quickly becomes, doesn’t change the trend of old version deprecation at all.

If you’re curious, the oldest version of jQuery CDNJS includes is 1.10.0, released on May 25, 2013. The project still gets an average of 100k requests per day, and the sites which use it are growing in popularity:

To confirm our theory, let’s consider another project, TweenMax:

As this package isn’t as popular as jQuery, the data has been smoothed with a one week trailing average to make it easier to identify trends.

Version 1.20.4 begins the year with 18M requests, and ends it with 14M, a decline of about 23%, again in alignment with the loss of websites on the Internet. The growth of 2.1.3 shows clear evidence that the release of a new version has almost no bearing on the popularity of old versions, the trend line for those older versions doesn’t change even as 2.1.3 grows to 29M requests per day.

One conclusion is whatever libraries you publish will exist on websites forever. The underlying web platform consequently must support aged conventions indefinitely if it is to continue supporting the full breadth of the web.

Cloudflare is very interested in how we can contribute to a web which is kept up-to-date. Please make suggestions in the comments below.



Source link