Web automated testing, also known as UI automated testing, foreign called end-to-end Test (E2E, end-to-end testing), can make repetitive and tedious manual testing (commonly known as dot dot) through the automatic execution of the program, can greatly improve the efficiency of testers (imagine the regression Test to Test for a day, Using automated tests can take less than an hour).

TestCafe is an upstart test automation tool. It has great features and a great development team, but it has always been relatively low-key so it is not as well known as other tools. If you are interested in automated testing, please join me to learn more about it.

The installation

The installation mode can be selected according to the application scenario:

  • Global installation:npm i -g testcafeThen execute the commandtestcafe chrome e2e.test.js
  • Project Installation:npm i --dev testcafeAnd, inpackage.jsonTo configure the following command, which means to use TestCafe through the Chrome browsere2eTest cases under directory.
1
2
3
Copy the code
"scripts": {
  "test:e2e": "testcafe chrome e2e/*"
}
Copy the code

A simple example

Here’s a sample file from the official documentation, with some code added:

12 3 4 5 6 7 8 10 11 12 13 14 15 16 17 18Copy the code
Import {Selector} from 'TestCafe '; import {Selector} from' TestCafe '; // Fixtures can be interpreted as test sets, similar to 'describe' in other test frameworks, Fixture can contain more than one test test cases fixture ` Getting Started ` / / specified initial page. The page ` https://devexpress.github.io/testcafe/example `; // test('My first test', async t => {await t TypeText ('#developer-name', Click ('#submit-button') // verify that the result is as expected .expect(Selector('#article-header').innerText).eql('Thank you, John Smith! '); });Copy the code

The running results are as follows:

Used to introduce

Web test automation is the manual test behavior through the program or script automatically run, recall our usual test work, nothing more than the following steps:

  • Enter the url to open the web page
  • Manipulating page elements
  • Verify that the result is correct

One of the most important steps is to find the page element to work on, and TestCafe provides powerful selectors to find.

The Selector Selector

Creating a Selector is very simple. Here is the sample code:

1
2
3
Copy the code
import { Selector } from 'testcafe';

const usernameInput = Selector('#username');
Copy the code

The Selector API, like document.querySelector(), can be used to query page elements in a variety of ways:

  • The Selector (‘ # id) : according toidLook for the element
  • Selector(‘.class ‘) : Finds elements by style name
  • Selector(‘ div ‘) : Finds elements based on HTML tags
  • Selector(‘ # id.class span ‘) : Finds elements based on multiple combinations

Functional selector

Selector not only implements regular selection, but also other types of queries through the built-in API:

  • Selector(‘ li ‘).nth(1) : Finds the first li element
  • Selector(‘ label ‘).withtext (‘ foo ‘) : Finds the contains in the labelfooElements of text
  • Selector(‘ div ‘).withattribute (‘ attrName ‘, ‘attrValue’) : Finds the contains in the divattrNameProperty and the value isattrValueThe elements of the
  • See the official documentation for more apis

PS: WithAttribute is very useful, In many testing frameworks, you are advised to add a testId (react-native testing-library) or data-testid (react-testing-library) to a page element to find it.

Using testid has the following benefits:

  • Avoid adding on page elementsidThis contaminates the properties of the page
  • Improve the efficiency of finding page elements becausetestidandidYou can also get unique elements directly

So if you want to find an element by testid, you can:

1
Copy the code
Selector('div').withAttribute('testId', 'foo');
Copy the code

React Selector

If your page is developed with React, you can also use React Selector, the React Selector extension, to find page elements.

React Selector lets you look up elements by component name:

1
2
3
4
Copy the code
import { ReactSelector } from 'testcafe-react-selectors'; const todoInput = ReactSelector('TodoInput'); Const todoItem = ReactSelector('TodoInput todoItem '); // Find nested child componentsCopy the code

It’s important to note that you can’t use ReactSelector with a component name plus an HTML Selector, like ReactSelector(‘TodoInput div’), which doesn’t look for div elements under TodoInput. Instead, the Selector(‘.todoInput > div’) automatically converts the component name to a class and then queries it.

React Selector also validates the props and state parameters of the component. See the React Selector documentation for more information.

Events and Assertions

Once you have found a page element, you can perform operations and validation on it. The events and assertions section is relatively simple, and you can check the official documentation. Here are some simple examples:

One, two, three, four, five, six, sevenCopy the code
// test('My test ', async t => {// click "await" button. Lick ('#submit-button'); // Text type await t.typetext ('#foo-input', 'Peter'); });Copy the code

More details about the event can be found in the official documentation.

One, two, three, four, five, sixCopy the code
// assert test('My test ', async t => {await t. expect({a: 'bar'}).eql({a: }) // check whether two objects are equal. Expect (a === b).ok(); // check whether the result is true});Copy the code

More details on assertions can be found in the official documentation.

TestCafe also provides apis for accessing page node properties. Common apis include the following:

  • ChildElementCount: Gets the number of child elements
  • HasChildElements: Whether there are child elements
  • TextContent: gets the textContent of a page element
  • HasClass (className) : Whether there is a class style
1
2
3
Copy the code
Test ('My test ', async t => {// check if an element has a class style.Copy the code

More information can be found in the official documentation.

The mock request

Web automation tests run in an integrated test environment can affect the data in that environment. If you don’t want to “contaminate” the data in that environment, you can mock out server requests to isolate the server environment.

TestCafe provides mock server apis that you can use to implement the functionality of the mock server API. Let’s look at code examples to see how the mock API is used.

12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22Copy the code
Import {RequestMock} from 'testcafe'; Const mockData = [{name: 'Foo', age: 18,},]; / / the mock request const mock = RequestMock () onRequestTo ({/ / assumes that the interface of a service is a http://server.com/api/user url: 'http://server.com/api/user', method: 'GET', isAjax: true, }) .respond({ data: mockData }); // Integrate mock service fixtures' Getting Started '. Page 'http://localhost:3000/'. RequestHooks (mock) in the test set using hooks methods;Copy the code

When the tests are running, the tests executed by the test set do not request data from the actual server, but instead go through the Mock API and render the page with mock data. Once the test is executed, there is no impact on the data on the server.

Competing goods contrast

There are many Web automation tools, such as selenium and Rebot, as well as Nightwatch and Cypress. Cypress and TestCafe have similar features and are competing directly with each other, but TestCafe has the advantage of supporting a wide variety of browsers, including other browsers besides Chrome and Internet Explorer.

TestCafe supports the following browsers, more information can be found here:

The browser The alias
Chromium chromium
Google Chrome chrome
Google Chrome Canary chrome-canary
Internet Explorer ie
Microsoft Edge edge
Mozilla Firefox firefox
Opera opera
Safari safari

Also check out the following articles to see how TestCafe compares to other automated testing frameworks:

  • An Overview of JavaScript Testing in 2018
  • Evaluating Cypress and TestCafe for end to end testing

conclusion

Web test automation is at the top of the testing pyramid, and is expensive to develop and maintain, so it can be used to test the core process of a project, but it doesn’t have to cover all the details, which makes it the most cost-effective. Hope the students who are interested in automated testing leave a message for discussion, thank you.