"Big Front siege Lion Road • Two" Javascript&qa⼯ engineers

Source: Internet
Author: User
Tags benchmark server port

The topic that we share today is Javascript&qa⼯. See this topic, may be asked: the front end of the development is OK, the rest of the test on the line, where still need to care about these? But in fact, testing is a very important aspect of front-end development, but also the way to advanced front-end engineers!

This article is mainly divided into four parts:

· Unit Test

· Performance testing

· Functional Testing

· Security testing

  I. Unit Testing

Unit testing refers to checking and validating the smallest testable unit in a program . For unit testing in the meaning of the unit, in general, according to the actual situation to determine its specific meaning, such as the C language unit refers to a function, Java unit refers to a class, graphical software can refer to a window or a menu. In general, the unit is the minimum measured function module that is artificially defined. Unit testing is the lowest level of test activity to be performed during the software development process, and the independent unit of the software will be tested in isolation from other parts of the program.

In a traditional structured programming language, such as C, the unit to be tested is usually a function or a sub-process. In an object-oriented language like C + +, the basic unit to test is the class. For the ADA language, developers can choose whether to perform unit tests on separate processes and functions or at the level of the ADA package. The principle of unit testing is also extended to the development of the fourth generation language (4GL), where the basic unit is typically divided into a menu or display interface.

Other development activities that are often associated with unit tests include code review, static analysis, and dynamic analysis. Static analysis is to read the source code of the software, look for errors or collect some metric data, do not need to compile and execute the code. Dynamic analysis provides information on execution tracking, time analysis, and testing coverage by observing the action of the Software runtime.

is a function for the front end.

 (1) Why does the front end do unit testing ?

I think the main reason is 5 points:

1. Correctness

Test can verify the correctness of the code, before the line to achieve the heart.

2. Automation

Of course, manual can also be tested, through the console can print out internal information, but this is a one-time thing, the next test will need to start over, efficiency can not be guaranteed. by writing test cases, you can to write once, run multiple times .

3. Explanatory

Test cases are used to test the importance of interfaces and modules, so the use of these APIs is covered in test cases. If other developers want to use these APIs, reading the test case is a good way, sometimes clearer than the document description.

4. Drive development, guide the design

The code is tested on the premise that the code itself testability, then to ensure the testability of the code, you need to pay attention to the design of the API in development, TDD will test forward is to play such a role.

  5. Guaranteed Refactoring

The Internet industry product iteration speed quickly, after iteration inevitably exists the process of code reconstruction, how can guarantee the quality of the reconstructed code? With test cases backed up, you can refactor boldly.

(2) unit Test principle & test Style

The purpose of unit testing is to give developers a clear idea of the results of the code with three points: single duty, interface abstraction, hierarchical separation . The prerequisite for unit testing is the assertion library, which is a detection method that ensures that the smallest unit can function properly.

Testing style: test-driven Development (Test-driven DEVELOPMENT,TDD), (Behaviordriven development,bdd) behavior-driven development are agile development methodologies.

TDD focuses on whether all features are implemented (each feature must have a corresponding test case), and suite Mate Test uses the assert (' tobi ' = = User.Name);

BDD focuses on whether the overall behavior is consistent with overall expectations, and each line of code written has a purpose of providing a comprehensive set of test cases. Expect/should,describe with it uses natural language expect (1). Toequal (FN ()) to execute the result.

  

  (3) Unit Test framework

  The main framework for unit testing :

  

(3) unit test run flow

  

Each test case group is set by describe

1.before Single test case (IT) before you start
2.beforeEach before each test case starts
3.it define test cases and leverage the assertion library for
Set Chai such as: Expect (x). To.equal (true); asynchronous Mocha.
4. The above terminology is called mock

  

(4) Automated Unit Test Karma

  Karma is Testacular's new name, in 2012 Google Open source testacular,2013 year testacular renamed Karma. Karma is a very mysterious name, representing the fate of Buddhism. The name is the same as the fan mom in lol--compare Buddha.

On the AngularJS team, we rely on testing and we always seek better tools to make our life easier. That's why we created KARMA-A Test Runner This fits all our needs.

Karma is a node. JS-based JavaScript test Execution Process management tool (test Runner). The tool can be used to test all major web browsers, to be integrated into CI (continuous integration) tools, and to work with other code editors.

You can generate reports and single-test coverage checks.

Karma.conf.js

  

Karma configuration//Generated on Thu Mar 2018 20:30:24 gmt+0800 (CST) module.exports = function (config) {Config.s ET ({//base path that would be used to resolve all patterns (eg. files, exclude) BasePath: ",//Frameworks to U SE//Available frameworks:npmjs.org/browse/keyword/karma-adapter frameworks: [' Jasmine '],//List of FILES/PA Tterns to load in the browser files: ['./unit/**/*.js ', './unit/**/*.spec.js '],//List of FILES/PA    Tterns to exclude exclude: [],//Specify the corresponding JS file to execute code coverage preprocessors: {'./unit/**/*.js ': [' coverage '] },//test results reporter to use//possible values: ' dots ', ' progress '//Available reporters:npmjs.org/brows E/keyword/karma-reporter reporters: [' progress ', ' coverage '], Coveragereporter: {type: ' html ', dir: ' Co verage/'},//Web server port port:9876,//enable/disable colors in the output (reporters and logs) CO Lors:true,//Levelof logging//possible values:config. log_disable | | Config. Log_error | | Config. Log_warn | | Config. Log_info | | Config. Log_debug Loglevel:config. Log_info,//enable/disable watching file and executing tests whenever any file changes Autowatch:false,//ST    Art these browsers//available browser launchers:npmjs.org/browse/keyword/karma-launcher browsers: [' Phantomjs '], Black window small independent operating environment singlerun:true,//Concurrency level//How many browser should be started simultaneous Concu Rrency:infinity})}

Unit Test Demo:

index.jswindow.test = function (num) {    if (num = = 1) {        return 1    }else{        return num + 1;}    } Index.spec.jsdescribe ("Test basic function API", function () {    It ("Application of the +1 function", function () {        expect (Window.test (1)). ToBe ( 1);})    ;

  

  Ii. Functional Testing

  Functional testing is primarily a e2e test. End-to-end testing is a way to test whether an application's processes are executed from start to finish. The purpose of performing end-to-end testing is to identify system dependencies and to ensure that the correct information is passed between various system components and systems.

Popular point is that the entire system as a black box, the tester simulates the real user in the browser to manipulate the UI to test.

A few common E2E testing framework, today mainly talk about selenium, because PHANTOMJS, headless browser is not maintenance, so rize with its formation management. End-to-end testing can be done at the terminal.
Nightwatch is a very powerful, configuration-rich end-to-end test framework that VUE-CLI is used for Night watch.

  (1) Selenium

  Selenium is a tool for Web application testing. The selenium test runs directly in the browser, just as the real user is doing. Supported browsers include IE (7, 8, 9, ten, one), Mozilla firefox,safari,google Chrome,opera, etc. The main features of this tool include: test and browser compatibility--test your application to see if it works well on different browsers and operating systems. Test system functions--Create regression test to verify software functionality and user requirements. Supports automatic recording of actions and automatic generation of test scripts in different languages such as. Net, Java, and Perl.

Selenium is a powerful family of open source web functional testing tools for ThoughtWorks, which uses JavaScript to manage the entire testing process, including reading test suites, performing tests, and documenting test results. It uses the JavaScript Unit test Tool Jsunit as the core to simulate real user actions, including browsing pages, clicking links, typing text, submitting forms, triggering mouse events, and so on, and being able to verify the results of the page. In other words, as long as the expected user behavior and results are described in the test case, we have a functional test suite that can be run automatically. (Selenium's core is written in JavaScript, he communicates with the browser, the test case information sent to the browser to execute, so as to achieve the purpose of automated testing.) )

I'm testing it with Firefox and need to download a driver,geckdriver first. Then NMP i selenium-webdriver--save;

Here, use the code control to open Firefox, find the element named ' WD ' and type ' node ', then press passing and finally exit Firefox. The code is as follows:

  

const {Builder, by, Key, until} = require (' selenium-webdriver ');(Async Function Example () {Let  driver = await new Bui Lder (). Forbrowser (' Firefox '). Build ();  try {    await driver.get (' www.baidu.com/');    Await Driver.findelement (by.name (' wd ')). SendKeys (' node ', key.return);    Await driver.wait (Until.titleis (' node_ Baidu Search ');  } Finally {    await driver.quit ();  }}) ();

  

Using the Rize framework, the wording is more concise:

Const RIZE = require (' Rize '); const RIZE = new Rize (); Rize  . Goto (' github.com/')  . Type (' Input.header-search-input ', ' node ').  Press (' Enter ')  . Waitfornavigation ()  . Assertsee (' node. js ')  . end ();

  

  Three . UI Test

  Front-end, as a traditional page, the style of their own writing, the heart of a bit of B-number, can not be old waiting for someone to walk the UI, said you where the difference between a few pixels.

Here we introduce a magical framework Backstopjs.

Backstopjs automates visual regression testing of your responsive web UI by comparing DOM screenshots over time.

  

    

Backstop configuration file, Backstop.json.

  

{"id": "Heroes", "viewports": [{"label": "Phone", "width": 375, "height": 667}, {"Label": "Tablet", "width": 1024x768, "height": 768}], "Onbeforescript": "Chromy/onbefore.js", "Onreadyscript": "Chro      My/onready.js "," scenarios ": [{" label ":" QQ "," Cookiepath ":" Backstop_data/engine_scripts/cookies.json ",  "url": "http://map.qq.com/m/",//Here is the UI interface URL to be tested "Referenceurl": "", "Readyevent": "", "Readyselector": "", "delay": 0, "hideselectors": [], "removeselectors": [], "Hoverselector": "", "Clickselector" : "", "postinteractionwait": "", "selectors": [], "selectorexpansion": True, "mismatchthreshold": 0.1 , "Requiresamedimensions": true}], "Paths": {"bitmaps_reference": "Backstop_data/bitmaps_reference", "b Itmaps_test ":" Backstop_data/bitmaps_test ",//The design of the UI here" engine_scripts ":" Backstop_data/engine_scripts "," Html_rep Ort ":" Backstop_data/htmL_report "," Ci_report ":" Backstop_data/ci_report "}," Report ": [" Browser "],//reporting method, here is the browser" engine ":" Chrome "," en Gineflags ": []," Asynccapturelimit ": 5," Asynccomparelimit ":" Debug ": False," Debugwindow ": false}

The results page of the test is very friendly and she will label the differences between your interface and the UI diagram:

  

  three . Performance Testing

Below is the performance test.

Front-end performance is mainly divided into two parts, the first is the page performance, such as the second open rate, and the second is the code performance. Today is mainly about code performance.

Today main code performance test Benchmarkjs,a Benchmarking library that supports high-resolution timers & returns statistically Significa NT Results

A reference library that supports a high-resolution timer and returns statistically significant results in a literal sense.

Aspect-oriented programming AOP no intrusive statistics. The benchmark benchmark method, which does not simply count the number of times the test code executes after the comparison time, it has a rigorous sampling process for testing. The number of executions depends on whether the sampled data can complete the statistics. Calculates the variance based on the number of statistics.

Talk not much, directly look at the code:

  

var Benchmark = require (' Benchmark '); var suite = new Benchmark.suite;suite.add (' use regular match string ', function () {    /o/.test (' Hello world! ');  })  . Add (' Use string Lookup ', function () {    ' Hello world! '). IndexOf (' O ') >-1;  })  Add listening  . On (' Cycle ', function (event) {    Console.log (String (Event.target));  })  Executes  the result. On (' Complete ', function () {    console.log (' Faster is-' + this.filter (' fastest '). Map (' name '));  })  Run Async  . Run ({' Async ': true});

The results of the implementation are as follows:

  

  

The following is the stress test .

Several commonly used indicators for stress testing of network interfaces are throughput, response time, and concurrency, which reflect the server concurrency processing power.

PV website Number of visitors to the day UV independent visitors. PV hundreds of thousands of or even million a day needs to consider stress testing. Conversion Formula qps=pv/t ps:1000000/10*60*60=27.7 (1 million requests are concentrated in 10 hours, the server processes 27.7 business requests per second);

Ab-c 100-n http://localhost:8001 continues to issue 28 requests per second. Request per second indicates that the server processes requests per second as QPS . Failed requests indicates the number of requests that failed this request. The higher the value of the test, the greater the Connection Times connection time, which includes the process by which the client establishes a connection to the server, processes requests from the server, and waits for the message response.

Commonly used pressure testing tools are AB, Siege, Http_load.

  Iv. Security Testing

  There are three common types of security attacks: XSS, CSRF, and SQL injection.

(1) XSS Cross-site scripting attacks

  Enter an unclosed label in input to test whether it will be executed.

><scrīpt>alert (Document.cookie) </scrīpt>

(2) Csrf,sql injection.

SQL injection. ' Or 1=1--

(3) CSRF cross-site request forgery
This is a cookie Vulnerability (authentication), after users visit the dangerous website B, B will visit secretly let the user visit the regular website A. Regular website after verifying the identity (through the cookies) that this is the same user, then the operation
No good test methods have been found at the moment.

Summary: A lot of front-end celebrities of the blog site have been attacked, many people spit trough the front ceiling low, so learning a background language for our front-end developers on the cultivation of thought is critical. It is important to be able to write a single test. This is also the way to our advanced front-end engineers.

Finally, I want to say a word: do not know the test UI is not a good front end, do not know the background of the product is not a good front end . The front road is long, I will be up and down and quest.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.