编程知识 cdmana.com

Front end automation test (effect test / interaction test / unit test)

Automated test development

When it comes to automation, you will not be unfamiliar with it , industrial automation 、 Office automation 、 test automation , After all, freeing hands is a tradition inherited from the ancients . For example, the Ancient Papermaking 、 Typography , And all kinds of agricultural production tools , No matter the ancients or us now , Are constantly looking for tools to free their hands .

What is automated testing

Baidu Encyclopedia will tell you

Generally refers to the automation of software testing , Software testing is to run a system or application program under preset conditions , Evaluate the operation results , Preconditions should include normal and abnormal conditions .

Simply understand , Automation is to simulate human operation as much as possible to detect the application , For example, you build a computer , Then the automatic test will try to see if it works , Whether the program can run .

Front end automated testing

About the front-end automated testing, we are divided into three parts : effect (UI Interface ) test 、 Interactive testing 、 unit testing .

  1. effect (UI Interface ) test

The effect test refers to whether the current page effect is consistent with the effect picture , By calculating the difference between the two , And then we get the similarity , Obviously, if there's a difference 70%, That's not going to qualify , As for how much can pass , You can specify it by yourself .

  1. Interactive testing

There is frequent interaction between the front end and the user , For example, users click and move the mouse , Press and lift the keyboard and so on , It's with smooth and high-frequency interaction , To give users a better experience . And what interaction testing does , Is to simulate the user's operation to click or move and so on . And then judge whether the result of the interaction is in line with the expectations of the website developers .

  1. unit testing

Unit testing is an essential part of every language testing framework , Unit testing is the smallest testable unit in a program , obviously , The less code coupling your project has , The smaller the particle size , So the more units you can test , It's the same as the answer , More checking , The more accurate each step is , The more correct it is , That's what unit testing is all about .

effect (UI Interface ) test

Want to achieve the effect of the page test can be divided into the following steps :

  1. Prepare renderings for comparison
  2. Take a screenshot of the page to be detected
  3. Through the pixel ratio, we can get the difference proportion between the screen capture and the effect picture
  4. Custom pass scale , Give friendly tips

Preparation

We go through puppeteer Take a screenshot of the page to be detected , adopt blink-diff To compare the differences between the two pictures , Before starting to use , The following installation is required :( Of course , All of these require that you have installed them locally Node.js Environmental Science )

npm install -g puppeteer
npm install -g blink-diff

Use steps

  1. Bring in installed Libraries

    const puppeteer = require('puppeteer'),
        BlinkDiff = require('blink-diff')
  2. adopt puppeteer Take a screenshot of the page to be detected

    const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] });
    const page = await browser.newPage();
    await page.setViewport({ width: 1920, height: 945 });
    await page.goto('http://www.baidu.com');
    await page.screenshot({ path: imgUrl + 'Screenshots.png', fullPage: true });
    // close puppeteer
    browser.close();  
  3. adopt blink-diff To compare the differences between the two pictures

     const diff = new BlinkDiff({
                imageAPath: imgUrl + 'example.png', //  The design 
                imageBPath: imgUrl + 'Screenshots.png',// Screenshot of the page 
                threshold: 0.02, // 1% threshold
                imageOutputPath: imgUrl + 'Diff.png'//Diff route 
            });
    
            diff.run(function (error, result) {
                if (error) {
                    throw error;
                } else {
                    let rel = Math.round((result.differences / result.dimension) * 100)
                    console.log(diff.hasPassed(result.code) ? ' adopt ' : ' Failure ');
                    console.log(' Total pixels :' + result.dimension);
                    console.log(' Find out :' + result.differences + '  differences , The proportion of difference ' + rel + "%");
                    if (rel > 20) {
                        process.exit(1);
                    }
                }
            });

After the comparison , Will be in images Create contrast difference pictures in the folder , however , We can't use it for the time being .

Selenium-webdriver Interactive testing

If you want to realize the interaction test of the page, it can be divided into the following steps :

  1. Prepare the page to be tested
  2. Plan the interactions to be tested , For example, the mouse hovering effect of simple navigation bar
  3. Write test scripts
  4. Download browser driver
  5. Start the test with friendly tips

Preparation

We go through selenium-webdriver Realize page interaction detection ( Of course , All of these require that you have installed them locally Node.js Environmental Science )

npm install selenium-webdriver

The second very important thing in preparation is to download the browser driver , Use of this series Chrome Browser to test , The download driver address is as follows

http://chromedriver.storage.googleapis.com/index.html

Here is the special note : Guaranteed to download Chrome The browser version is the same as the downloaded browser driver version . The version used in this section is 91.0.4472.19 ( The version here doesn't have to be consistent with me , And your local Chrome The version can be unified )

Use steps

Create one ahead of time index.js file , Used to write the following code .

  1. establish WebDriver example

Whether you want to test mouse clicks or keyboard presses , The first thing you need to do is create WebDriver example

var webdriver = require('selenium-webdriver')
var driver = new webdriver.Builder()
     .forBrowser('chrome')
     .build();
  1. Open the address to be detected
driver.get('http://www.baidu.com');
  1. Operate page elements
webdriver.By.id('kw').sendKeys('webdriver');
webdriver.By.id('su').click();

Last , adopt node index.js You can execute the file , You can see a pop-up Chrome Browser window , Automatically enter... In the search box 了 webdriver And click the search button , The effect is as follows .

In this part, we have just experienced selenium-webdriver The function of , And understand its use steps . But only the above functions are far from being able to meet the actual business scenarios , That's what we need to learn more about API , Scroll the mouse , Keep looking down .

Commonly used API

selenium-webdriver Provides a wealth of API , Want to get to know more comprehensive partners , Sure Poke it here . This section is only for the commonly used API To introduce . We can use API The functions of are divided into the following categories .

  • Page operation
  • Positioning elements
  • Get element information
  • Event operations

Next , Let's get to know each other

Page operation
The name of the function describe Sample code
get() Request the specified URL driver.get("http://www.baidu.com")
getTitle() Retrieve current page title driver.getTitle().then(val => { console.log(val) });
getCurrentUrl() Retrieve... Of the current page URL driver.getCurrentUrl().then(val => { console.log(val) });
getPageSource() Retrieve the source code of the current page driver.getPageSource().then(val => { console.log(val) })
quit() Terminate browser session . Calling quit after , The instance will fail , And may no longer be used to issue commands to browsers driver.quit()
Positioning elements
  1. adopt By Class to locate elements ,By Class in selenium-webdriver Next , The general usage is as follows :
// The first one is 
var webdriver = require('selenium-webdriver')
let kw=webdriver.By.id('kw');
// The second kind 
var webdriver = require('selenium-webdriver'),
    By = webdriver.By
let kw=By.id('kw');

By Class provides static functions :

Static functions describe Sample code
By.className( name ) Locate elements with a specific class name By.className('s_ipt')
By.css( selector ) Use CSS Selector positioning elements By.css('s_ipt')
By.id( id ) Use ID Selector positioning elements By.id('kw')
By.linkText( text ) Locate the link element whose visible text matches the given string By.linkText("AboutGoogle")
By.name( name ) location name Attribute has the given value of the element By.name("btnK")
By.partialLinkText( text ) Locate the link element whose visible text contains a given substring . By.partialLinkText("About")
By.xpath( xpath ) Location and XPath The elements that the selector matches By.xpath(“//*[text()=’ sign out ’])
  1. adopt findElement Locate the elements on the page . If you can't find an element , You make a mistake .
var e1 = driver.findElement(By.id('foo'));
var e2 = driver.findElement({id:'foo'});

The above two sentences are the same , In addition, you can customize a function to locate elements , Like this .

 var link = driver.findElement(firstVisibleLink);

 function firstVisibleLink(driver) {
   var links = driver.findElements(By.tagName('a'));
   return promise.filter(links, function(link) {
     return link.isDisplayed();
   });
 }

findElement Another brother is findElements If you need to search for multiple elements on the page or test whether the elements appear on the page , Think about it .

var e1 = driver.findElements(By.tagName("input")
Get element information

After positioning to the element , A very high frequency pair operation is to get element information .

The name of the function describe Sample code
getCssValue() obtain CSS Property value element.getCssValue("background-color").then((val) => { console.log(val) }
getAttribute() Get other properties element.getAttribute("id").then((val) => { console.log(val) }
Event operations

The most important point of interaction testing is the interaction between users and pages , Like mouse events 、 Keyboard events .

event describe Sample code
click() Mouse click event element.click()
doubleClick() Double click event element.doubleClick()
keyDown() Press the keyboard element.keyDown()
keyUp() Keyboard up element.keyUp()
sendKeys() Insert a series of operations to type the key sequence provided . For each key , This will record a pair of keyDown and keyUp action element.keyUp.sendKeys('webdriver')

If the above events do not meet your needs , For example, you want to test mouse in and out events , It should be done ? I'm going to introduce a universal function , Absolutely anything , That is to say executeScript.

driver.executeScript("document.getElementById('item').onmouseover()")

The above code is executed in the context of the currently selected frame or window JavaScript code snippet . The script fragment will be executed as an anonymous function body . You can execute code snippets , Is not any operation can't help you .

Example : Detect the change of color after mouse click

The requirements are simple , First, there's a page , And then there's one on it div Elements , single click div After the element , You can change div Background color , How to use automatic detection to complete this series of steps . The key codes are as follows :

async function checkClick() {
    driver.get('http://127.0.0.1:8080');
    let item;
    await driver.findElements(By.id('item')).then(
        function(val) {
            // Determine whether an element exists 
            if (val.length == 0) {
                console.log(" No elements found , Detection failed ");
                process.exit(1);
            }
            item = val[0];
        })
    item.click();
    await item.getCssValue("background-color").then(
        function(val) {
            if (val != "rgba(255, 239, 161, 1)") {
                console.log(" Detection failed ")
                process.exit(1);
            } else {
                console.log(" Test successful ")
            }
        })
    driver.quit();
}

Jest unit testing

Unit testing is the smallest testable unit in a program , stay JavaScript The smallest testable unit in a function is a function , So let's focus on how to use the testing framework to test functions .

Preparation

We go through jest Implement function testing , The first thing you need to do is install

npm install -g jest

Use steps

  1. Let's prepare a test first cal.js file
function cal(num1, num2, type) {
  var result;
  switch (parseInt(type)) {
      case 0:
          result = num1 + num2;
          break;
      case 1:
          result = num1 - num2;
          break;
      case 2:
          result = num1 * num2;
          break;
      case 3:
          result = num1 / num2;
          break;
  }
  return result;
}
module.exports = cal;

The file contains a cal function , Realized a simple calculator

  1. Write test files ,cal.test.js , Generally, the name should follow the file to be tested test ending

    const cal = require('./cal.js');
    
    test('1 + 2 = 3', () => {
     expect(cal(1, 2, 0)).toBe(3);
    });
    test('5 - 2 = 3', () => {
     expect(cal(5, 2, 1)).toBe(3);
    });
    test('1 * 2 = 2', () => {
     expect(cal(1, 2, 2)).toBe(2);
    });
    test('4 / 2 = 2', () => {
     expect(cal(4, 2, 3)).toBe(2);
    });
  2. adopt npm init Enter all the way , initialization package.json file , Write the following
{
    "scripts": {
        "test": "jest"
    }
}
  1. adopt jest cal.test.js Start the test

Commonly used API

During the test , What we use most is expect , It provides us with a lot of matching methods , So that we can easily implement verification matching . If you need to know more , Sure Poke it here .

Method describe Sample code
.toBe(value) Use Object.is To test the exact equality of two values expect(cal(1, 2)).toBe(3)
.toBeTruthy() Match any if The statement is true expect(thirstInfo()).toBeTruthy();
.toContain(item) Check that items with a specific structure and value are included in the array expect(list).toContain('obj');

Last

It's a little long , If it helps you at the end of the day , Do you want a compliment before you leave ?

You need to get the complete sample code , Please poke here

PS: The article is not finished , Will continue to update with subsequent use , If you have any problems or want to add content to communicate with each other

版权声明
本文为[Outlying Islands]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/07/20210702084853197k.html

Scroll to Top