Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Modern Web Testing with TestCafe
Modern Web Testing with TestCafe

Modern Web Testing with TestCafe: Get to grips with end-to-end web testing with TestCafe and JavaScript

eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Modern Web Testing with TestCafe

Chapter 2: Exploring TestCafe Under the Hood

The main goal of this chapter is to learn how TestCafe works under the hood and how it can be used in test automation to cover different features of websites and portals. We will get acquainted with the architecture of TestCafe, its API, and custom client-side code.

These topics will give us the ability to understand what main methods and functions of TestCafe are available out of the box and how to invoke them.

In this chapter, we're going to cover the following main topics:

  • Scouting the TestCafe architecture.
  • Learning about the TestCafe API.
  • Executing custom client-side code.

Scouting the TestCafe architecture

From the beginning of time, end-to-end web testing frameworks have depended on external drivers to emulate user actions in real browsers. This approach, however, has a number of downsides:

  • Third-party dependencies and a limited number of supported browsers: You had to download, install, configure, and update additional drivers or libraries for each test environment (and sometimes even for each test run). In addition to that, you could only use the browsers supported by each driver.
  • Lack of flexibility: Old tools were unable to operate on the tested page directly. As long as the test code does not interfere with the app code, operating on the tested page directly enables the tool to execute many additional scenarios and workarounds. For example, this way it can add and remove styles or change the visibility of any elements on the tested page.
  • Code duplication: Legacy testing frameworks ran with the same browser instance during the entire test run, maintaining the tested web application state from test to test (and keeping the same values in cookies and storage). As a consequence, end-to-end tests had a huge amount of duplicated code for clearing the web application state between tests to avoid interference.

However, TestCafe has a fix for each of these problems.

The core idea behind the architecture of TestCafe is that users should not need any external drivers to run end-to-end browser tests. Instead, all the test scripts that emulate user actions can be executed from the page itself. This enables a true cross-platform and cross-browser approach as tests will be able to run on any device with a modern browser!

After each test finishes its execution, TestCafe purges the browser state: it deletes cookies, clears localStorage and sessionStorage, and reloads the page. If you launch several tests in parallel, TestCafe executes each test run in an independent server-side context to prevent server-side collisions.

TestCafe execution can be split into two parts:

  • Server-side (in the Node.js process).
  • Client-side (in the browser).

Let's take a look at each of these parts.

The server side

Test code is performed in the Node.js environment on the server side. This enables TestCafe to use advantages of standalone server-side code, including the possibility of launching tested web application servers before tests and enhanced control over the testing environment and test execution.

Executing test code in Node.js provides a lot of advantages:

  • Database preparation and the launching of the application can be done from within the tests.
  • Tests have access to the server's filesystem, so you can read data or create files needed for testing.
  • Tests can use all recent syntax features of Node.js. In addition to that, you can include and utilize any Node.js third-party packages.
  • Improved stability and speed of execution due to test logic separation from automation scripts.

Since Node.js code executes on the server, it doesn't have direct access to the Document Object Model (DOM) of the page or browser API, but this is handled by custom client-side functions that have access to the DOM and are executed in the browser context.

The client side

TestCafe automation scripts are designed to imitate user actions on any tested page. Their main goal is to enable you to write high-level cross-browser tests, so element-focusing, triggering events, and processing attributes are performed in the same way as a real human would in a browser.

Scripts that emulate user activity (TestCafe internal scripts) run on the client side on the tested page in the browser. This enables TestCafe to utilize the advantages of browser scripts, including built-in smart waits, mobile testing, and user roles. For client-side code to work in the browser, TestCafe proxies the tested page on the server and injects the scripts into its code. This approach is also known as a reverse proxy. When you run TestCafe tests, the browser address bar shows a URL that is prefixed with some digits – this is because TestCafe uses its own open source URL-rewriting proxy (https://github.com/DevExpress/testcafe-hammerhead) and proxies the tested pages.

When you run tests with TestCafe, a reverse proxy is automatically launched locally on your computer. It injects automation scripts into the tested page, so neither the page code nor the resources it communicates with can tell that the page has been modified. In other words, when TestCafe proxies the tested page, it adds automation scripts and rewrites all the URLs on the tested page to point to the proxy:

Figure 2.1 – TestCafe reverse proxies between the user's browser and the web server

Figure 2.1 – TestCafe reverse proxies between the user's browser and the web server

When the browser refers to these new, rewritten URLs, the original resources are also proxied and enhanced in the same way. TestCafe also mocks the browser API to separate automation scripts from the rest of the page code. The proxying mechanism is absolutely safe – it guarantees that the page appears to be hosted at the original URL, even to the test code.

In this section, we reviewed how TestCafe operates from the server and client sides. We also learned about the main advantages of this architecture, including the possibility to prelaunch applications before tests, extend control over testing environments, proxying and injecting scripts, which enables smart waiting, mobile testing, and user roles, which we will discuss a bit later.

TestCafe supports JavaScript – the most popular programming language for web development – which allows most users to use their existing coding skills and minimizes the learning curve for newcomers. In addition to that, its clear API makes tests easy to create, read, and maintain. So, let's see what methods TestCafe has to offer.

Learning about the TestCafe API

Since the server-side code runs in Node.js, tests should be written in JavaScript (TypeScript and CoffeeScript are also supported, but eventually, everything should be transpiled into JavaScript).

TestCafe utilizes a minimalistic API that provides less than a few dozen methods, which are then transformed into user actions on the page. As our tests will be using the TestCafe API methods to interact with the pages, let's review the main interaction groups supported in TestCafe:

  • Elements selection.
  • Actions.
  • Assertions.
  • User roles.

Let's discover each of these interactions in more detail.

Elements selection

TestCafe utilizes an advanced mechanism with built-in waiting to locate target elements for an action or assertion. To perform an action (such as click, hover, type, and so on) or to make an assertion, you should first identify the target page element. This is as easy as specifying a standard CSS selector. For more complex situations, you can chain methods (such as, for example, getting an element by class name, then getting its second child, and then finally, getting its third sibling). Selector strings should be passed inside chainable Selector constructors to create a selector.

For example, you can click on a button with the button-test class, as follows:

const { Selector } = require('testcafe');const buttonTest = Selector('.button-test');

For more complex situations, you can traverse the DOM tree by chaining selectors:

const { Selector } = require('testcafe');const linkTest = Selector('#block-test')    .child('a')    .withAttribute('href', 'https://test-site.com/main.html')    .withText('Second link');

What this chain of selectors does is the following:

  1. Selects an element with the block-test id.
  2. Selects its child elements.
  3. Filters them by the a tag.
  4. Selects elements with the href attribute that includes https://test-site.com/main.html.
  5. Selects elements that include the Second link text.

    Note

    If a selector matches several elements, the subsequent methods return results for all the elements that were matched.

TestCafe provides a number of methods that search for elements relative to the selected element (keep in mind that all of these methods should be prepended with Selector(cssSelector)). Most of these methods accept index as an argument, which should be a zero-based number (0 will be the closest relative element in the set). If the number is negative, the index is counted from the end of the matched set. Here are the methods:

Now, let's look at the methods that filter elements from the selector. The same as before, all of these methods should be prepended with Selector(cssSelector). Here are the methods:

When a selector is executed, TestCafe will be waiting for the target node to appear on the page until the selector timeout expires. You can specify the timeout (in milliseconds) in the following cases:

During the timeout, the selector is rerun until it returns a DOM element or the timeout is surpassed. If TestCafe can't find the corresponding node in the DOM, the test is marked as failed.

Actions

The TestCafe API provides a set of action methods to interact with the page (such as click, type, select text, hover, and so on). You can call them one after another in a chained fashion. All of these methods should be prepended with t as they are the methods of the test controller object (https://devexpress.github.io/testcafe/documentation/reference/test-api/testcontroller/). Also, selector can be a string, selector, DOM node, function, or Promise; and optionally, you can use options, which is an object with a set of options containing supplementary parameters for the action (unless otherwise specified). Here are all the main action methods:

Assertions

TestCafe allows you to verify elements, page properties, and parameters (equals, contains, greater, match, and so on). To write assertions, use the test controller's t.expect method, followed by an assertion method that accepts an expected value and optional arguments; message is the assertion message string that shows up in the report if the test fails and options is an object with a set of options containing supplementary parameters for the assertion. Here are all the assertion methods available in TestCafe out of the box:

User roles

TestCafe has a built-in user role mechanism that emulates user actions for logging in to a website. It also saves the logged-in state of each user in a separate role that can be reused later on in any part of your tests to switch between user accounts. This approach gives access to some unique features:

  • Login actions are not duplicated upon switching to a previously used role during the same session. So, for example, if you activate a role in the beforeEach hook, the login actions will run only once before the first test. All further tests will just reuse the existing authentication data.
  • When you switch roles, the browser automatically navigates back to the page where the switch happened, so there is no need to additionally open any URLs for a new role (this behavior can be disabled if required).
  • If during a test you log in to several websites, authentication data from cookies and browser storage is saved in the active role. When switching back to this role in the same test, you will be logged in to all the websites automatically.
  • An anonymous built-in role that logs you out of all accounts.

Let's have a look at a practical example of creating and using roles.

To create and initialize a role, we will need to use a Role constructor. Then, the login page URL and actions needed to log in should be passed to Role. This is shown in the following code block:

const { Role, Selector } = require('testcafe');const regularUser = Role('https://test-site.com/login', async (t) => {    await t.typeText('.login', 'TestUser')        .typeText('.password', 'testuserpass')        .click('#log-in');});const admin = Role('https://test-site.com/login', async (t) => {    await t.typeText('.login', 'TestAdmin')        .typeText('.password', 'testadminpass')        .click('#log-in');});const linkLoggedInUser = Selector('.link-logged-in-user');const linkLoggedInAdmin = Selector('.link-logged-in-admin');fixture('My first test Fixture').page('https://test-site.com');test('Test login with three users', async (t) => {    await t.useRole(regularUser)        .expect(linkLoggedInUser.exists).ok()        .useRole(admin)        .expect(linkLoggedInUser.exists).notOk()        .expect(linkLoggedInAdmin.exists).ok()        .useRole(Role.anonymous())        .expect(linkLoggedInUser.exists).notOk()        .expect(linkLoggedInAdmin.exists).notOk();});

After you create all the required roles, you can switch between them anytime; roles are shared across tests and fixtures. Roles can even be created in a separate file and then used in any test fixture that references (requires or imports) this file.

To sum up, in this section, we reviewed the TestCafe API and the main methods that it provides. We also learned how to select elements, conduct assertions, and utilize user roles to switch between different accounts. Now, let's take a look at how custom client-side code can be executed in TestCafe to give us even more control over the browser.

Executing custom client-side code

With TestCafe, you can create client functions that can run on the client side (in the browser) and return any serializable value. For example, you can obtain the URL of the current page, set cookies, or even manipulate any elements on the page.

In some complex scenarios, TestCafe helps you write code to be executed on the tested page. Here are several examples of tasks that can be done with custom client-side code:

  • Get elements from the web page for further actions. TestCafe allows you to create selectors based on client-side code that returns DOM nodes. You can write this code in the server-side test and TestCafe will run these functions in the browser when it needs to locate an element:
    const { Selector } = require('testcafe');const testElement = Selector(() => {    return document.querySelector('.test-class-name');});await t.click(testElement);
  • Obtain data from a client function that returns any serializable object from the client side (including any objects that can be converted to JSON). Unlike selectors, test code can access the object this client function returns. Usually, the data obtained from client functions is used to assert different page parameters. Here is an example of getting and verifying a page URL:
    const { ClientFunction } = require('testcafe');const getPageUrl = ClientFunction(() => {    return window.location.href;});await t.expect(getPageUrl).eql('https://test-site.com');
  • Inject custom code into the tested page. Injected scripts can then be used to add helper functions or to mock browser API:
    fixture('My second test Fixture')    .page('https://test-site.com')    .clientScripts(        'assets/jquery-latest.js',        'scripts/location-mock.js'    );

    Note

    It is recommended that you avoid changing the DOM with custom client-side code. A rule of thumb is to use client-side code only to explore the page, find and return information to the server.

You can find more examples of client-side scripts and injections at the following links:

As we just discovered, TestCafe client functions are quite useful for different browser manipulations and getting additional data to verify in our tests.

Summary

In this chapter, we learned how TestCafe works under the hood. We got acquainted with the architecture of TestCafe, saw how it performs on client and server sides, and learned about the strategies for selecting elements, actions, assertions, roles, and custom client-side code.

All of this will be used in the upcoming chapters to write our own suite of end-to-end tests. In addition to that, you can always use this chapter as a reference to search for any particular method or assertion and see how it's called and what it does.

Now, let's move on from the main methods and functions of TestCafe to more practical aspects, such as setting up the testing environment for our future automated tests.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Build a proof-of-concept project to demonstrate your familiarity with TestCafe
  • Discover useful tips and best practices for building production-ready and fault-tolerant tests
  • Write clean and maintainable tests by refactoring your codebase using PageObject pattern

Description

TestCafe is an open source end-to-end testing framework that combines unmatched ease of use with advanced automation and robust built-in stability mechanisms. This book is a comprehensive, project-based introduction to TestCafe that will show you how to use the TestCafe framework and enable you to write fast and reliable tests; plus you’ll have a proof of concept ready to demonstrate the practical potential of TestCafe. You’ll begin by learning how to write end-to-end web tests using the TestCafe syntax and features of the TestCafe framework. You’ll then go from setting up the environment all the way through to writing production-ready tests. You’ll also find out how to build a sample set of tests in a step-by-step manner and use TestCafe to log in to the website, verify the elements present on different pages, create/delete entities, and run custom JavaScript code. As you advance, you’ll delve into several stages of refactoring that will take you through the showcase setup/teardown and PageObject patterns. While this test suite is relatively simple to build, it showcases some of the most prominent features of TestCafe. Finally, this TestCafe book will show you how the tests can be run on a free and simple-to-use website, without requiring you to build and deploy your own servers or backend services. By the end of this book, you’ll have learned how to write and enhance end-to-end tests with TestCafe to solve real-world problems and deliver results.

Who is this book for?

The book is for QA professionals, test engineers, software engineers, and test automation enthusiasts looking for hands-on guidance on learning about TestCafe. This book is also great for full-stack developers who want to learn more about new tools for testing their code. The book assumes a basic understanding of JavaScript, Node.js, HTML, CSS, and some simple Bash commands.

What you will learn

  • Understand the basic concepts of TestCafe and how it differs from classic Selenium
  • Find out how to set up a TestCafe test environment
  • Run TestCafe with command-line settings
  • Verify and execute TestCafe code in the browser
  • Automate end-to-end testing with TestCafe using expert techniques
  • Discover best practices in TestCafe development and learn about the future roadmap of TestCafe

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 30, 2020
Length: 168 pages
Edition : 1st
Language : English
ISBN-13 : 9781800205963
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Sep 30, 2020
Length: 168 pages
Edition : 1st
Language : English
ISBN-13 : 9781800205963
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 94.97
Node.js Web Development
€32.99
Modern Web Testing with TestCafe
€24.99
End-to-End Web Testing with Cypress
€36.99
Total 94.97 Stars icon
Banner background image

Table of Contents

8 Chapters
Chapter 1: Why TestCafe? Chevron down icon Chevron up icon
Chapter 2: Exploring TestCafe Under the Hood Chevron down icon Chevron up icon
Chapter 3: Setting Up the Environment Chevron down icon Chevron up icon
Chapter 4: Building a Test Suite with TestCafe Chevron down icon Chevron up icon
Chapter 5: Improving the Tests Chevron down icon Chevron up icon
Chapter 6: Refactoring with PageObjects Chevron down icon Chevron up icon
Chapter 7: Findings from TestCafe Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(5 Ratings)
5 star 80%
4 star 20%
3 star 0%
2 star 0%
1 star 0%
Jesse L. Palmer III Feb 19, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Loaded with detailed, current examples, Modern Web Testing with TestCafe gives you everything you need to know to quickly get up-to-speed. The book takes you from learning about the framework itself, how to set up your environment, building your test suite, and then refactoring your tests. If you are an SDET or an engineer who wants to level up their TestCafe skills, I couldn't recommend it more!
Amazon Verified review Amazon
Suja Jan 24, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a very good book for- Beginners who are looking for step by step clear instructions to use TestCafe right from setting up the environment all the way to writing expert level e2e automated tests- Current TestCafe users to learn TestCafe internals and best practices.The other aspect I like about this book is, it also provides compares between Selenium and TestCafe. This is very helpful for current Selenium users trying to switch to TestCafe and best use the benefits TestCafe provides.
Amazon Verified review Amazon
vijay krishna May 04, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Dmytro did a great job of putting together a clear and simple guide for beginners to learn everything about testcafe. It is surprisingly easy to follow along and build end-to-end tests utilizing the best capabilities of testcafe. It also serves as a great reference for optimizing the tests you have already written in testcafe.
Amazon Verified review Amazon
Sam Dec 08, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book has a great way of giving you the step by step guide on how to use testcafe to your web automation. It doesn't matter if you are a beginner or an expect in web automation, this book gives you the tools and tips to get you started and setup to be successful in your projects
Amazon Verified review Amazon
Client Kindle Jun 05, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Très bonne ouvrage avec de bons exemples, seul bémol si vous lisez sur Kindle le code source n'est pas forcément très lisible, il a les fichiers sur github qui compense.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.