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 22 2018 20:30:24 GMT + 0800 (CST)
module.exports = function (config) {
config.set ({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: ‘‘,
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: [‘jasmine’],
// list of files / patterns to load in the browser
files: [
‘./Unit/**/*.js’,
‘./Unit/**/*.spec.js’
],
// list of files / patterns 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: https://npmjs.org/browse/keyword/karma-reporter
reporters: [‘progress’, ‘coverage’],
coverageReporter: {
type: ‘html’,
dir: ‘coverage /’
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of 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,
// start these browsers
// available browser launchers: https://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
concurrency: Infinity
})
}
Unit Test Demo:
// index.js
window.test = function (num) {
if (num == 1) {
return 1
} else {
return num + 1;
}
}
// index.spec.js
describe ("Test basic function API", function () {
it ("Application of +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 Builder (). forBrowser (‘firefox‘). build ();
try {
await driver.get (‘https://www.baidu.com/‘);
await driver.findElement (By.name (‘wd‘)). sendKeys (‘node’, Key.RETURN);
await driver.wait (until.titleIs (‘node_Baidu search’), 1000);
} finally {
await driver.quit ();
}
}) ();
Using the Rize framework, the wording is more concise:
const Rize = require(‘rize‘);
const rize = new Rize();
rize
.goto(‘https://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": "Tianjiao",
"viewports": [
{
"label": "phone",
"width": 375,
"height": 667
},
{
"label": "tablet",
"width": 1024,
"height": 768
}
],
"onBeforeScript": "chromy / onBefore.js",
"onReadyScript": "chromy / 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",
"bitmaps_test": "backstop_data / bitmaps_test", // put the UI design here
"engine_scripts": "backstop_data / engine_scripts",
"html_report": "backstop_data / html_report",
"ci_report": "backstop_data / ci_report"
},
"report": ["browser"], // The way to report, here is the browser
"engine": "chrome",
"engineFlags": [],
"asyncCaptureLimit": 5,
"asyncCompareLimit": 50,
"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 (‘Find using string’, function () {
‘Hello World!’. IndexOf (‘o’)> -1;
})
// Add listener
.on (‘cycle’, function (event) {
console.log (String (event.target));
})
//Results of the
.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 a QPS. Failed requests indicates the number of requests that failed this request the higher the value of the test. Connection times Connection time, which includes the process of establishing a client connection to the server, processing requests from the server, and waiting for a 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.
"Big Front siege Lion Road • Two" Javascript&qa