In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article will give you a detailed explanation about the preparation of testable JavaScript code, the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.
1. Testable JavaScript
a. Existing technology
1. Agile development
The fact that ① uses agile development does not necessarily mean that applications are completed faster and of higher quality. the biggest advantage of agile development is the way it handles changes in requirements.
② rapid iteration and continuous interaction can speed up the delivery of high-quality software.
two。 Test-driven development
Write tests before writing code, which provide code that must follow the expected functionality, and then start writing code after a failure to ensure that the test passes. Keep testing ahead of development, and there will never be untested code.
3. Behavior-driven development
It provides developers and non-developers with a useful language to describe the correct application behavior and module behavior, which is a common language.
b. The code is for people to use.
1. The code we write is not for computers, but for people to use.
two。 Why write testable code
Testable code is easier to test, which means it is easier to maintain, and easy maintenance means that it makes it easier for people (including themselves) to understand and maintain, which in turn makes testing easier.
3. If there is no testable, maintainable, and understandable code, it is rubbish
4. What is testable code
What is testable: short but not too complex code, complete comments, and check coupling.
What is maintainable: it can exist in a complete product cycle: when a product is transferred from one person to another, it does not need to be partially or completely rewritten.
What is understandable: simple, small, annotated code is easier to understand
5. How to write testable code: write isolatable blocks of code that are short, least dependent, and least complex
Second, complexity
a. Code size
One way to keep the function to a minimum is to keep the command (Command) and the query (Query) separate. The command function indicates what to do (do something), while the query function indicates what is returned (return something). That is, the command represents setter and the query represents getter. Command functions are tested with mock, while query functions are tested with stub. Keep these concepts separate and improve testability, and good scalability can be achieved by ensuring the separation of read and write.
B.JSLint
Http://www.jslint.com/
c. Cyclical complexity
1. Cyclomatic complexity is the number of independent current paths in the code. In other words, it is the minimum number of unit tests that need to be written to temper all the code.
two。 The cyclomatic complexity of generating code can be achieved using a simple command-line tool like jsmeter
3. In order to achieve rationality and maintainability, it is a good idea to maintain a low cyclomatic complexity.
4. Code with high cyclomatic complexity is usually caused by many if/then/else statements, and the simplest fix is to break the method into smaller methods
5. Use jscheckstyle to calculate cyclomatic complexity
d. Reuse
1. The best way to reduce the size of the code is to reduce the amount of code written. The theory is to use third parties (external or internal code) that can be used in a production environment maintained by others, which can reduce a significant amount of code maintenance costs.
two。 A typical application consists of 20% of common components and up to 65% of domain-specific reusable components. The rest of the program is composed of customized code related to the specific application system and utilities used in some places.
① program specific: we write our own code
② domain specific: third-party modules used in programs
③ domain independence: frameworks like YUI or Node.js
3. If you find that the code has been written twice, it's time to extract it into a function.
e. Fan out
1. Fan-out measures the number of modules or objects that the function depends on directly or indirectly.
two。 Fan out:
The fan-out of process An is the sum of the number of internal processes of process An and the number of data structures updated by process A.
In this definition, any of the following operations are counted as an internal process (take methods B and C as an example):
① if A calls B
② if B calls An and A returns a value that B can then take advantage of
③ if C calls An and B, and the return value of An is passed to B.
So, add all the internal processes of function A, plus the global structure updated by A (relative to the outside of A), and the resulting number is the fan out of function A.
3. For all functions, calculate the fan-out value and the fan-in value corresponding to the value, multiply the two numbers, and square them, and the resulting number is the complexity of a function. (fan_in * fan_out) ²
4. For highly complex code:
High fan-in and fan-out code may indicate that a function is trying to do too much and should be avoided
High fan in and fan out can determine the pressure point of the system, and it will be very difficult to maintain these functions because they are associated with too many other parts of the system.
They're not fine enough.
5. The problems caused by high fan out: the code is more complex, harder to understand, all more difficult to test; and during testing, each direct dependency must be simulated (mock or stub), thus increasing the complexity of creating tests; and fan out symbolizes tight coupling, making functions and modules too fragile.
f. Fan in
1. The fan-in of process An is the sum of the number of internal processes of process An and the number of data structures that want to obtain information from process A.
g. Coupling: six-stage coupling
1. Content coupling: content coupling is the tightest form of coupling, including calling methods or functions on external objects, or directly changing the state of objects by modifying the properties of external objects.
two。 Common coupling: if two objects share another global variable, the two objects have a common coupling.
3. Control coupling: this coupling controls external objects based on tags or parameter settings.
4. Imprint coupling: by passing a record to an external object, using only a portion of that record
5. Data coupling: occurs when one object is passed to another object message data without passing parameters that control the external object.
6. No coupling: absolute zero coupling between any two objects.
* although not part of the formal coupling, instantiating the behavior of a non-singleton global object is also a very tight coupling, which is close to the content coupling, but closer than the public coupling.
h. Coupling measure
1. Code review and code review are a very good way to find code coupling, rather than relying on tools to discover coupling metrics
i. Dependency injection
1. Injection and simulation are loosely related, and injection is responsible for constructing objects and injecting them into code, while impersonation replaces objects or methods when called for testing. Factory dependencies, or manual injection of dependencies into constructors or method calls, help reduce the complexity of the code, but also add some overhead: if an object's dependencies need to be injected, another object is now responsible for building the object.
two。 The dependency injector can build and inject fully formed objects into the code.
j. Annotation
1. For testable JavaScript, all functions or methods to be tested are preceded by comments. Based on these comments, we (or others) can know how to test and what to test.
2.YUIDoc and JSDoc can convert all comments to HTML.
3.Docco/Rocco, parsing Markdown-style comments from the code.
III. Event-based architecture
a. Benefits of event-based programming
1. From a core point of view, all applications are related to messaging. Tight coupling may occur because the code requires a reference to another object so that it can send or receive messages to the object.
two。 Global dependencies are dangerous: any part of the system that touches them makes BUG difficult to track; if we have local variables of the same name or similar, we accidentally change these global dependencies; and due to ubiquitous features, it can also lead to data encapsulation errors, making debugging very difficult. The declaration and use of JS global variables is simple, and the hosting environment usually provides multiple global variables, global functions, and global objects. This means that you have to be careful when saving variables to the global scope, because there are already many global objects in the global scope.
3. Event-based programming boils down to two main parts: invocation and return. Converts the call to a parameterized event and returns a parameterized callback.
b. Event hub
1. The idea behind the event is simple: register the method with the event center and specify some of the events it can handle. Methods using the independent CPU of the wire stopper, it is responsible for the event request and waits for the response.
two。 This architecture takes advantage of the JS function and encourages the use of small coupled code with minimal dependencies. Encouraging developers to write small chunks of code that use minimal dependencies and using events instead of method calls can greatly improve testability and maintainability.
3. Event-based architecture helps implement the separation of concerns and modularization advocated by MVC. The difference is that event-based architecture models are disrupted, eliminated, or separated, depending on how we view them. Data based on the event schema is not stored in the object. There are no modifiers, everything is private, and the only communication with the "outside" world is through event-based API.
c. Test the event-based architecture
1. Based on the nature of the event architecture: register event listening, and no (or very few) objects are instantiated
d. Description based on event architecture
1. Scalability: the event hub creates a super single point of failure. If the hub fails, the program should be down.
two。 Broadcast: using broadcasts to broadcast many events to all clients may bring a lot of traffic
3. Runtime detection: the compiler has no way to check for spelling errors in event names in the form of strings, and it is strongly recommended to use enumerations or hashes for event names instead of checking them over and over again when typing
4. Security.
5. Status: usually provided by the Web server to the business module from the Web server through the session cookie
IV. Unit testing
a. Unit testing framework
1. The most important part of the test framework is to aggregate tests into test suites and test cases. Test suites and test cases are scattered in many files, and each test file usually contains only tests for a single module. The best way is to categorize all the tests for a module into a separate test suite.
two。 An assertion is a practical application of comparing the expected value with the actual value.
b. Start writing tests
1.YUI test
Https://github.com/zhangyue0503/html5js/blob/master/testablejs/1.html
c. Written unit tests
1. How to write a good unit test? Code coverage.
two。 Isolation: unit tests should be tested by loading only the minimum code that needs to be tested. Any additional code can affect the test or the code being tested, and can also cause problems.
3. Scope: it must be small, and a completely isolated method can make the scope of the test as small as possible.
4. Writing unit tests using test-driven development before coding does not avoid the annotations required by the function. If you write the test case first, it can also be used for the specification function (or the code under test) function
5. Forward testing: unit tests that are written first according to the correct data tests, because they provide basic expected functionality before building negative and boundary tests.
6. Negative testing: pass in unexpected functions or parameters that the function does not want to test to ensure that the function being tested can handle them. The BUG found by negative testing is usually a difficult BUG to deal with.
7. Code coverage: a measure, usually the percentage of executed and unexecuted lines of code, that is another key part of an effective unit test
d. Real scene testing
1. Unit testers can use mock and stub to extract dependencies, mock for commands and sub for finding
two。 Test stand-in: describes using sub or mock to simulate dependent objects for testing.
e. Run the client JavaScript unit test
1.PhantomJS
2.Selenium
f. Run the server-side JavaScript unit test
1.jasmine
5. Code coverage
Build appropriate JS files for code coverage information, deploy or practice these files, and push and persist the coverage results to a local file, or you can combine the coverage results of different tests to produce beautiful html output, or just get the appropriate coverage numbers and percentages for upstream tools or reports
a. Basic theory of coverage
1. In theory, the more lines of code "covered", the more complete the test. However, the link between code coverage and test integrity is fragile.
b. Code coverage data
1. Code coverage data is divided into two parts, line coverage and function coverage.
VI. Integration testing, performance testing, load testing
a. Integration testing
1.Selenium: you usually need to run a lot of java code on the same sandboxie in your browser to run tests, as well as a client-side API to control remote browsers, and you can write Selenium serenades in various languages.
2.CasperJS: provides functionality similar to Selenium, but does not restrict the environment at all.
b. Performance testing
1.HAR file: an json format object that can be viewed using many tools. To monitor the performance of a web application, you need to generate an HAR file of the application profile, then examine the data and find problems.
c. Load testing
1.nodeload, (node.js version of Apache Bench)
VII. Debugging
a. In-browser debugging
1.firebug
2.chrome
B.Node.js debugging
1. Command line debugger
Node debug myscript.js
c. Remote debugging
1.chrome remote debugging
2.PhantomJS
3.firefox remote debugging: Crossfire extension
d. Mobile debugging
1. Native support: after Android4 and ios6
e. Production environment debugging
1. Source image file
VIII. Automation
a. Automate what content?
Automate everything, and any content that operates more than once should be automated.
b. When to automate
Three opportunities: coding phase, construction phase, and deployment phase.
About the preparation of testable JavaScript code to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.