Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Puppeteer Front-end Automation Test

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you the "sample Analysis of Puppeteer Front-end Automation testing", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let the editor lead you to study and study the "sample Analysis of Puppeteer Front-end Automation Test".

cause

At present, we are continuing to develop a project with dozens of pages and 100,000 + lines of code, and this problem will always occur with the change of products. When adding or modifying certain business logic or functions (especially general logic), these general logic or components often involve problems elsewhere. Due to the limited testers, it is difficult to retest all the functions after completing a module unit.

At the same time, due to the difference between environment and data, and the neglect of code completeness in the development process, the code will have problems in the parsing and display of some special data, which is difficult to find in development and testing. Generally speaking, we hope to have such a tool to help us solve the above problems:

After making code and function changes, you can automatically access the pages of each function to detect problems.

Batch access is carried out for a large number of data content to detect whether there are problems in the display of different data.

Test and code functions are not coupled as much as possible to avoid the need to modify the test case every time a new function is added, and the maintenance cost is too high.

Regular testing tasks to find out the completeness of the data platform for the display of new data in a timely manner

Among them, the most important problem is to decouple the test code from the function to avoid the need to add new test cases to each iteration and modification. How do we do this? First of all, let's sort out the functions of the test platform.

Function setting

Because our platform is mainly for data display, so in the testing process, we mainly focus on the daily display data, and do not deal with some complex form operations. In view of the above problems, the functions of our automated testing tools are as follows:

Visit each page in turn

Access the specific content of each page, such as time switch, tab switch, paging switch, table expansion row, etc.

Select the first 100 links to access the details in the data table, and continue the test on the drill-down page.

Error requests captured on the page

Capture, count and report error messages

According to the above, we can divide the whole application into several test units.

Page unit to test the stability of page access for each function

The details page unit performs a batch of details page jumps according to the data list of the page to detect the stability of the details page under different parameters

Function unit, which is used to detect whether errors occur after clicking and switching of various display types on the page and the details page.

Through this division, we write the test cases according to the specific test logic for each unit, so that we can avoid frequently modifying the test cases when adding new functions and pages.

Puppeteer

With our requirements above, let's take a look at whether the functions and features of Puppeteer can meet our requirements.

Document address

Puppeteer is a Node library that provides a high-level API to control Chromium or Chrome through the DevTools protocol. Puppeteer runs in headless mode by default, but you can run header mode by modifying the configuration file.

We can use Puppeteer to do the following:

Visit the page and take screenshots

Automatic keyboard input and form submission

Simulate user actions such as clicks

Wait, wait, wait.

Let's introduce their basic functions through some small cases:

Visit a website with ba certification

Puppeteer can create an page instance and use the goto method to access the page. Page contains a series of methods that can perform various operations on the page.

(async () = > {const browser = await puppeteer.launch (); const page = await browser.newPage (); / / ba authentication await page.authenticate ({username, password}); / / visit the page await page.goto ('https://example.com'); / / take screenshots await page.screenshot ({path:' example.png'}); await browser.close ();}) ()

Visit the login page and log in

First of all, for SPA (single page application), we all know that when the page is entered, the client code begins to render. We need to wait until the rendering of the page content is complete, and then do the corresponding operation. We have the following ways to use

WaitUntil

Puppeteer provides waitUntil parameters for page access, switching, etc., to determine what conditions are met before the page jump is considered complete. Include the following events:

Load-when the load event of the page is triggered

Domcontentloaded-when the DOMContentLoaded event of the page is triggered

Networkidle0-triggered when there is no longer a network connection (at least 500ms later)

Networkidle2-triggered when there are only 2 network connections (at least 500ms later)

With waitUnitl, we can make sure that the page has been accessed after the page request has been completed.

WaitFor

The waitFor method can resolve only after the specified action is completed.

/ / wait for selectorawait page.waitFor ('.foo'); / / wait for 1 secondawait page.waitFor (1000); / / wait for predicateawait page.waitFor (() = >! document.querySelector ('.foo'))

We can use the waitForSelector method to log in when the login box is rendered successfully.

/ wait for the password input box to render await page.waitFor ('# password'); / enter the user name await page.type ('input#username', "username"); / / enter the password await page.type (' input#password', "testpass") / / Click the login button await Promise.all ([page.waitForNavigation (), / / resolve page.click ('button.login-button') after the jump is completed, / / click this link will indirectly cause navigation (jump)]); await page.waitFor (2000) / / get cookiesconst cookies = await page.cookies ()

Batch access to links in the list content

Mainly make use of the selector function of page instance

Const table = await page.$ ('.table') const links = await table.$$eval ('a. Linkink detailing, links = > links.map (link = > link.href)); / / Loop access links...

Perform error and access snooping

Puppeteer can listen for errors and requests during page access, so that we can catch page access errors and report them. This is also the basic function we need for testing.

/ / triggered when an exception occurs that the page js code does not catch. Page.on ('pagerror', () = > {}) / / triggered when the page crashes. Page.on ('error', () = > {}) / / triggers page.on (' request') / / when a request on the page receives the corresponding response. Page.on ('response')

Through the above several small cases, we found that the function of Puppeteer is very powerful, which can fully meet our above needs for automatic access to the page. Next, we write a unit use case for our test unit.

Final function

Through our previous planning of the test unit, we can plan our test path.

Visit website-> Log in-> visit Page 1-> perform basic Unit Test-> get details Page Jump Link-> visit details Page in turn-> perform basic Unit Test

-> visit page 2.

So, we can split into several major categories, and several test units, to carry out various tests.

/ / including basic test methods, class Base {} / / details page units such as log output, do some basic unit tests of class PageDetal extends Base {} / / page units, do basic unit tests, and access the details page class Page extends PageDetal {} / / to log in and other operations, and visit the page units in turn to test class Root extends Base {}

At the same time, how do we track the changes of the test when the function page changes? we can add a custom tag test-role for the function we tested, and write the test logic according to the custom tag during the test.

For example, for the time switching unit, let's make a brief introduction:

/ / 1. Get the element of the test unit const timeSwitch = await page.$ ('[test-role= "time-switch"]'); / / if the page does not have timeSwitch, you do not need to test if (! timeSwitch) return// 2. Time switch's toggle button const buttons = timeSwitch.$$ ('.time-switch-button') / / 3. Cycle through the button and click for (let I = 0; I < buttons.length; iTunes +) {const button = buttons [I] / / Click the button await button.click () / / highlight! Wait for the corresponding content to appear before confirming that the page visited successfully try {await page.waitFor ('[test-role= "time-switch-content"]')} catch (error) {reportError (error)} / / screenshot await page.screenshot ()}

The above is just a simple access content test, we can write their own test logic according to our use case unit, in our daily development, we only need to test the content, plus the corresponding test-role.

The above is all the content of the article "sample Analysis of Puppeteer Front-end Automation Test". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report