node. JS Test Summary

Source: Internet
Author: User
Tags benchmark
This article is a recent summary of the learning of node. JS testing, including unit testing, integration testing, benchmarking, and code coverage testing, among many other things. For medium-to large-scale projects, complete test cases help ensure the continuous integration of projects and the robustness of the code.Unit TestUnit test, also known as Module test, is the correctness test for the smallest execution unit in the program. Common development patterns include the two classes of TDD and BDD. TDD (Test-driven development, test-driven development), writes test cases first, then develops modules for test cases, complements test cases when the test case is insufficient, and continuously updates the module code when the module fails to pass the test until it passes through the test case completely. Its development core revolves around the test case, that is, the integrity of the test case determines the robustness and correctness of the development module, which is prone to the problem of insufficient coverage of the unit test by boundary conditions. BDD (Behavior-driven development, behavior-driven development), the Semantic programming language develops test cases that are close to the business requirements, and then drives the development of related modules. AVA is the most trendy test framework in the JavaScript ecosystem, with built-in Babel that can be used directly with ES6 syntax, with the advantages of lightweight, efficient, concurrent execution, forced isolation, and installation methods:
NPM Install--save-dev Ava

Set the Scripts field in Package.json:
{
"Scripts": {
"Test": "Ava",
"Test:watch": "Ava--watch"
}
}

Run:
NPM Test

# or
NPM Test:watch

The following is a basic test code:
Import test from ' Ava ';

Const Fibonacci = (N) = = {
if (n = = = 0 | | n = = 1) {
return n;
}
Return Fibonacci (n-1) + Fibonacci (n-2);
}

Test (' Test Fibonacci (0) ', t = = {
T.is (Fibonacci (0), 0);
});

Test (' Test Fibonacci (1) ', t = = {
T.is (Fibonacci (1), 1);
});

HOOK CALLS
Test.before (' before ', t + = {
Console.log (' before ');
});

Test.after (' after ', t + = {
Console.log (' after ');
});

Test.beforeeach (' Beforeeach ', t + = {
Console.log (' Beforeeach ');
});

Test.aftereach (' Aftereach ', t + = {
Console.log (' Aftereach ');
});

In the above code, we first introduced the AVA module, then created the Fibonacci function to be tested, followed by two test cases, and finally four hook methods: before ()/after ()/Beforeeach ()/Aftereach (). AVA provides a cosmetic method to specify how tests are performed:
1. Skip (), skip the test case with Skip () added, 2, only (), execute only Test cases with only () added, 3, Todo (), placeholder identifiers, represent test cases to be added in the future, 4, serial (), serial execution of test cases, AVA by default Test cases are executed in a parallel manner.
Test (' Test Fibonacci (0) ', t = = {
T.is (Fibonacci (0), 0);
});

In the above code callback function, T, called the assertion execution object, contains the following methods:
·T.end (), end test, only valid in TEST.CB ()·T.plan (count), specifying the number of executions·T.pass ([message]), tested by·T.fail ([message]), test failed·T.ok (value, [message]), asserting that value is true·T.notok (value, [message]), which asserts that value is a false value·T.true (value, [message]), asserts that value is true·T.false (value, [message]), asserts that value is False·T.is (value, expected, [message]), asserts value = = = Expected·T.not (value, expected, [message]), asserts that the value!== expected·T.same (value, expected, [message]), asserting that value and expected depth are equal·T.notsame (value, expected, [message]), asserting value and expected depth range·T.throws (function | promise, [ERROR, [message]]), assertion function throws an exception or Promisereject error·T.notthrows (function | promise, [message]), asserting that function is not unusual or promise resolve·T.regex (contents, regex, [message]), Assert contents matches regex·T.iferror (Error, [message]), assertion error is false value
Integration Testing
In contrast to unit tests that focus on micro-modules, integration testing is a macro-holistic approach to identifying problems, so also known as assembly testing and joint testing. Travis CI is an excellent continuous integration tool that listens to updates on Github projects and facilitates integration testing of open source software. Using Travis CI requires creating a. travis.yml configuration file in the root directory of the project (for example, node. js):
Language:node_js

NODE_JS:
-"6"
-"5"

Before_script:

Script
-NPM Test
-Node Benchmark/index.js

After_script:

By default, Travis CI automatically installs dependencies and executes the NPM Test command, and the Script field allows you to customize the commands that need to be executed, with the complete life cycle including:
·Install apt Addons·Before_install·Install·Before_script·Script·After_success or After_failure·OPTIONAL Before_deploy·OPTIONAL Deploy·OPTIONAL After_deploy·After_script
Benchmark TestBenchmark tests use rigorous testing methods, test tools, or test systems to evaluate the performance of the target module, which is often used to observe the performance of the software and hardware environment after the change, and the results are reproducible. The most commonly used benchmark tool in the node. JS Environment is Benchmark.js, which is installed as follows:
NPM Install--save-dev Benchmark

Basic example:
Const Benchmark = require (' Benchmark ');
Const SUITE = new Benchmark.suite;

Suite.add (' Regexp#test ', function () {
/o/.test (' Hello world! ');
})
. Add (' String#indexof ', function () {
' Hello world! '. IndexOf (' O ') >-1;
})
. On (' Cycle ', function (event) {
Console.log (String (event.target));
})
. On (' Complete ', function () {
Console.log (' fastest is ' + this.filter (' fastest '). Map (' name '));
})
Run Async
. Run ({' Async ': true});

Code CoverageThe Code coverage tool determines the integrity of a module based on the number of lines of code and number of branches covered by the test case. AVA recommends using the NYC test code coverage to install NYC:
NPM Install NYC--save-dev

Modify. Gitignore Ignore related files:
Node_modules
Coverage
. nyc_output

Modify the Test field in Package.json:
{
"Scripts": {
"Test": "NYC Ava"
}
}

Execute NPM Test and get:
➜test-in-action (master) ✔npm test

> test-in-action@1.0.0 test/users/sean/desktop/test-in-action
> NYC AVA

2 passed
----------|----------|----------|----------|----------|----------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Lines |
----------|----------|----------|----------|----------|----------------|
----------|----------|----------|----------|----------|----------------|
All Files | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|----------------|

Due to uploading attachments and text restrictions, sometimes some pictures, text may not display, details see: http://mp.weixin.qq.com/s?__biz=MzI5ODI3NzY2MA==&mid=100000510&idx=2 &sn=8339d4fca5f54ab3a9ec305eae756436#rd welcome everybody to exchange together. Scan the following two-dimensional code for more beautiful articles! (scan the code to pay attention to the unexpected surprise!!) )

subscription number QR code. jpg (39.39 KB, download number: 0)

Download attachments

2016-5-18 16:44 Upload

Follow us on our subscription number (UNIGUYTECH100) and service number (Uniguytech) for more beautiful articles! Also welcome to join the "Everyone Technical network discussion QQ Group", group number: 256175955, please note your personal introduction! Let's talk about it!

  • 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.