Web automation testing, 8 core knowledge points that you must master!

Using cypress for end-to-end testing is significantly different from some other frameworks in that it uses JavaScript as the programming language. The traditional mainstream selenium framework supports multiple languages. Most QA students can write selenium code in python and Java. When I encountered cypress, which required writing js code, I thought I had to learn another programming language, so I slowly gave up.

In fact, learning cypress only requires mastering some basic syntax.

1. Variables

Use the let keyword to define variables in js. When a line of code ends, it can be separated by a semicolon;

let name = 'yuz' // ; or not 

Browsers have built-in js interpreters, and the above code can be run directly in the browser. Press F12 to open the browser's developer tools, click the console tab, and then enter the js code.

728 x 313 805 x 346

In addition to the browser environment, you can also run code through the node.js environment. We can save the above code to the demo.js file, and then enter the node command in the command line tool to run the code.

node /path/to/demo.js

2. Conditional branch

The main thing to note about the conditional branch of js is that the conditional expression must be wrapped in parentheses.

let age = 17
  
  if (age > 18) {
      canSmoke = true
  }
  else {
      canSmoke = false
  }
  
  console.log("can i smoke? " + canSmoke)

In the conditional branch code of js, if the code logic is relatively simple, the ternary operator is often used to simplify the code. How is it used? express. The above code can be changed to the ternary operator form:

let age = 17
 let canSmoke = (age > 18) ? true : false // false
现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:110685036

 

3. Function

When defining a function, use the function keyword, then the function name, fill in the parameters in the brackets, separate the parameters with commas, and finally the code between curly braces (i.e., the "function body"). The return value of the function uses the return key. Character.

function add (a, b) {
      return a + b
  }
  
  let res = add(3, 4)

4. Arrow function

Arrow functions are very common in js. They can simplify the writing of ordinary functions. The above ordinary function is changed to an arrow function

 add = (a, b) => {
     return a + b
 }
 add(3, 4)

5. Callback function (Callback)

In js code writing, callback functions are often used. It allows us to program in an asynchronous manner. After executing a task, another task is triggered through a callback.

function print(string, callback) {
     let wait =  Math.random() * 5000;
     setTimeout(() => {
         console.log(string);
         callback();
     }, wait);
  }

In the above example, the print function allows the program to wait randomly for 5 seconds before printing the string and finally triggering the callback function. When calling this function, you can specify a callback function through an arrow function, such as printing "finished".

print("hello", () => console.log("finished") )

Callback functions are a very good tool if they are not nested. But once the calls are nested, you will fall into "callback hell". After adding try catch and exception capture to the code that falls into callback hell, the hierarchy is very unclear, seriously affecting reading.

print("first", () => {
     print("second", () => {
         print("last", () => console.log("finished"))
     })
 })

6、Promise

Promise is a programming method that replaces callback functions in asynchronous programming. We can create a Promise object in a function. This object needs to pass a function as a parameter, which can usually be written in the form of an arrow function.

The arrow function has two specific parameters, resolve and reject. Resolve is responsible for returning the normal results of the program, and reject is responsible for returning the abnormal situation when an exception occurs in the program.

function print (string) {
     let promise = new Promise( (resolve, reject) => {
         let wait =  Math.random() * 5000;
         setTimeout(() => {}, wait);
         resolve(string);
         reject(new Error());
     })
     return promise;
 }
 
 let promise = print("some thing");
 promise.then( result => console.log('first'), err => {} )
        .then( result => console.log('second'), err => {} )
        .then( result => console.log('last'), err => {} )

7、Async / Await

Promise is easier to write than ordinary callback functions, but it also involves many concepts such as resolve, reject and then. If there are many then, the code will not look good. Async/Await is a special syntax for using promises in a more comfortable way, and it is also very easy to understand and use. We only need to add the async keyword in front of the ordinary function, then the return value of this function will be a promise object.

async function print() {
     return 8;
 }
 print() // Promise {: 8}

Although the return value of the function is determined to be 8 when it is defined, when the print function is called, a Promise is obtained instead of 8. If you need to get the return value, you can use the then method:

let promise = print()
 promise.then( (result) => console.log(result) )

If you don’t like the way then is written, you can change it to await to get the return value:

let promise = print()
 console.log(await promise)
 // or
 let result = await print()

The previous callback function example can be rewritten into async / await form:

async function print (string) {
     let wait =  Math.random() * 5000;
     setTimeout(() => {}, wait);
     return string;
 }
 
 console.log(await print("first"))
 console.log(await print("second"))
 console.log(await print("last"))

8、Mocha & Chai

After writing some js code, you need to test the code to ensure that the code executes as expected and obtains the expected results. While mocha is an excellent js unit testing framework, chai specializes in handling assertions. When you need to use these two frameworks, install them through npm first:

npm install mocha chai

Then you can write the use case. It is best to write the use case in a directory named test. Each js file is a specification (spec), which indicates what the tested function should look like. This specification document contains a description of the function (describe), test cases (it), and assertions (assert). After writing the test code, enter the file directory and run it through npx mocha on the command line.

// test/mocha.spec.js
 const assert = require('assert');
 
 // the function to be tested
 function pow(a, b) {return a ** b};
 
 // tests
 describe("pow", () => {
     it('pow of 2 and 3', () => {
         let actual = pow(2, 3);
         assert.equal(actual, 8);
     })
     
     it('pow of string and 3', () => {
         let actual = pow("a", 3);
         assert.equal(actual, 8);
     })
 })

As you can see, a specification consists of three parts:

  1. describe

Indicates what function we are describing. In our case we are describing the function pow. The function of description is to organize test cases (IT). In a description, multiple IT use cases are usually included.

  1. it

The use case that needs to be executed, the second parameter is the code used to test the pow function, usually a function.

  1. assert

Assertion indicates whether the test results are as expected.

The cypress framework has integrated mocha, and the test code is written using the mocha representation method. Therefore, if you learn mocha well, you will learn half of cypress. The following example is the code for cypress to perform browser testing. It can be seen that it is no different from mocha, except that in cypress, assert, an explicit assertion method, cannot be used directly.

describe("go to the home page", () => {
     it('title contains', () => {
         cy.visit("http://www.testingpai.com")
         cy.title().should('include', '测试派')
     });
 })

9. Summary

To conduct automated testing on the browser side, it is essential to master the core js usage. The 8 knowledge points mentioned in this article will be used frequently.

  • Variables are named using the let keyword.
  • Control conditions through if and ternary expressions.
  • Ordinary function form function definition.
  • Arrow functions are also often used, somewhat similar to anonymous functions.
  • Callback functions are very common in js, but they will encounter the problem of callback hell.
  • Promise is an effective way to solve callback hell. The usage of promise and then is often encountered.
  • Async/Await is another more elegant way of using promises and is more recommended.

Finally, I would like to thank everyone who read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!

Software Testing Interview Document

We must study to find a high-paying job. The following interview questions are from the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.
 

Insert image description here

Guess you like

Origin blog.csdn.net/jiangjunsss/article/details/133031245