


Detailed introduction to the installation and use of NodeJs testing framework Mocha
This article comprehensively introduces how to use Mocha so that you can get started easily. If you know nothing about testing before, this article can also be used as an introduction to unit testing JavaScript .
Mocha is a unit testing framework for Javascript that runs under nodejs and browsers. It is quite easy to get started and easy to use. The unit testing frameworks are actually similar and basically include the following content:
Macro, attribute or function
assertion library used to write test cases, used to test whether it can pass
auxiliary libraries, such as hook libraries (calling certain functions or methods before and after testing), exception checks (some functions are In the case of certain parameters, throws an exception), input combination (supports multiple permutations of parameter input combinations), etc.
Supports IDE integration
The following is concise and to the point in the order of the official documents.
Installation and preliminary use
Execute the following commands in the console window:
$ npm install -g mocha $ mk dir test $ $EDITOR test/test.js
You can write the following code:
var assert = require('assert'); describe('Array', function() { describe('#indexOf()', function () { it('should return -1 when the value is not present', function () { assert.equal(-1, [1,2,3].indexOf(5)); assert.equal(-1, [1,2,3].indexOf(0)); }); }); });
Return to the console :
$ mocha . ✔ 1 test complete (1ms)
Here mocha will search the contents of the test folder in the current file directory and execute it automatically
Judgement library
This is to determine whether the test case passes, by default. You can use the assert library of nodejs. At the same time, Mocha supports us to use different assertion libraries. Now it can support the following assertion libraries. There are some differences in the usage of each assertion library. You can refer to the corresponding documentation.
1 should.js BDD style shown throughout these docs (BDD mode, this document uses this assertion library)
2 better-assert) c-style self-documenting assert() (C-modelAssertion library under ##)
3 expect.js expect() style assertions (expect mode assertion library)
4 unexpected the extensible BDD assertion toolkit
5 chai expect(), assert() and should style assertions
Synchronous code
Synchronous code means that the test is a synchronous function, and the above Array-related example code is easier to understand.
Asynchronous code
There are only asynchronous code tests because there are many asynchronous functions on nodejs, such as the following code. The test case is not completed until the done() function is executed.
describe('User', function() { describe('#save()', function() { it('should save without error', function(done) { var user = new User('Luna'); user.saveAsync(function(err) { if (err) throw err; done(); // 只有执行完此函数后,该测试用例算是完成。 }); }); }); });
Detailed explanation of describe and it
The example code above is relatively simple, so what are describe and it? Generally speaking, we can see that describe should declare a TestSuit (test collection), and the test collection can be nested and managed, while the it statement defines a specific test case. Taking bdd interface as an example, the specific source code is as follows:
/** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ context.describe = context.context = function(title, fn) { var suite = Suite.create(suites[0], title); suite.file = file; suites.unshift(suite); fn.call(suite); suites.shift(); return suite; }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.it = context.specify = function(title, fn) { var suite = suites[0]; if (suite.pending) { fn = null; } var test = new Test(title, fn); test.file = file; suite.addTest(test); return test; };
Hooks
In fact, this is a very common function when writing unit tests, which is to execute test cases and test cases A certain callback function (hook) is required before or after the collection. Mocha provides before(), after(), beforeEach() and aftetEach(). The sample code is as follows:
describe('hooks', function() { before(function() { // runs before all tests in this block // 在执行所有的测试用例前 函数会被调用一次 }); after(function() { // runs after all tests in this block // 在执行完所有的测试用例后 函数会被调用一次 }); beforeEach(function() { // runs before each test in this block // 在执行每个测试用例前 函数会被调用一次 }); afterEach(function() { // runs after each test in this block // 在执行每个测试用例后 函数会被调用一次 }); // test cases });
hooks also have the following other uses:
Describing Hooks - You can add a description to the hook function to better view the problem
Asynchronous Hooks (asynchronous hooks): The hook function can be synchronous or asynchronous. Let’s look at the test case. The following is a sample code for an asynchronous hook. :
beforeEach(function(done) { // 异步函数 db. clear (function(err) { if (err) return done(err); db.save([tobi, loki, jane], done); }); });
Root-Level Hooks (global hooks) - are executed outside describe (outside the test case collection). This is usually executed before or after all test cases.
Pending Tests (Pending Tests)
There are some tests that have not been completed yet, a bit similar to TODO, such as the following code:
describe('Array', function() { describe('#indexOf()', function() { // pending test below 暂时不写回调函数 it('should return -1 when the value is not present'); }); });
Exclusive Tests (Exclusive Tests)
Exclusive testing allows a set of tests or test cases, only one to be executed, and the others to be skipped. For example, the following test case collection:
describe('Array', function() { describe.only('#indexOf()', function() { // ... }); // 测试集合不会被执行 describe('#ingored()', function() { // ... }); });
The following is the test case:
describe('Array', function() { describe('#indexOf()', function() { it.only('should return -1 unless present', function() { // ... }); // 测试用例不会执行 it('should return the index when present', function() { // ... }); }); });
It should be noted that Hooks (callback functions) will be executed.
Inclusive Tests (including tests)
Contrary to the only function, the skip function will cause the mocha system to ignore the current test case collection or test cases, and all skipped test cases will be reported for Pending.
The following is an example code for a collection of test cases:
describe('Array', function() { //该测试用例会被ingore掉 describe.skip('#indexOf()', function() { // ... }); // 该测试会被执行 describe('#indexOf()', function() { // ... }); });
The following example is for a specific test case:
describe('Array', function() { describe('#indexOf()', function() { // 测试用例会被ingore掉 it.skip('should return -1 unless present', function() { // ... }); // 测试用例会被执行 it('should return the index when present', function() { // ... }); }); });
Dynamically Generating Tests(dynamically generated test cases)
In fact, this is also available in many other testing tools, such as NUnit, which replaces the test case parameters with a set to generate different test cases. The following are specific examples:
var assert = require('assert'); function add() { return Array.prototype.slice.call(arguments).reduce(function(prev, curr) { return prev + curr; }, 0); } describe('add()', function() { var tests = [ {args: [1, 2], expected: 3}, {args: [1, 2, 3], expected: 6}, {args: [1, 2, 3, 4], expected: 10} ]; // 下面就会生成三个不同的测试用例,相当于写了三个it函数的测试用例。 tests.forEach(function(test) { it('correctly adds ' + test.args.length + ' args', function() { var res = add.apply(null, test.args); assert.equal(res, test.expected); }); }); });
Interfaces (Interface)
Mocha’s interface system allows users to write their test case collections and specifics using different styles of functions or styles. For test cases, mocha has BDD, TDD, Exports, QUnit and Require style interfaces.
BDD - This is the default style of mocha, and our sample code in this article is in this format.
It provides describe(), context(), it(), before(), after(), beforeEach(), and afterEach() functions. The sample code is as follows:
describe('Array', function() { before(function() { // ... }); describe('#indexOf()', function() { context('when not present', function() { it('should not throw an error', function() { (function() { [1,2,3].indexOf(4); }).should.not.throw(); }); it('should return -1', function() { [1,2,3].indexOf(4).should.equal(-1); }); }); context('when present', function() { it('should return the index where the element first appears in the array', function() { [1,2,3].indexOf(3).should.equal(2); }); }); }); });
TDD - 提供了 suite(), test(), suiteSetup(), suiteTeardown(), setup(), 和 teardown()的函数,其实和BDD风格的接口类似(suite相当于describe,test相当于it),示例代码如下:
suite('Array', function() { setup(function() { // ... }); suite('#indexOf()', function() { test('should return -1 when not present', function() { assert.equal(-1, [1,2,3].indexOf(4)); }); }); });
Exports - 对象的值都是测试用例集合,函数值都是测试用例。 关键字before, after, beforeEach, and afterEach 需要特别定义。
具体的示例代码如下:
module.exports = { before: function() { // ... }, 'Array': { '#indexOf()': { 'should return -1 when not present': function() { [1,2,3].indexOf(4).should.equal(-1); } } } };
QUnit - 有点像TDD,用suit和test函数,也包含before(), after(), beforeEach()和afterEach(),但是用法稍微有点不一样, 可以参考下面的代码:
function ok(expr, msg) { if (!expr) throw new Error(msg); } suite('Array'); test('#length', function() { var arr = [1,2,3]; ok(arr.length == 3); }); test('#indexOf()', function() { var arr = [1,2,3]; ok(arr.indexOf(1) == 0); ok(arr.indexOf(2) == 1); ok(arr.indexOf(3) == 2); }); suite('String'); test('#length', function() { ok('foo'.length == 3); });
Require - 该接口允许我们利用require关键字去重新封装定义 describe ,it等关键字,这样可以避免全局变量。
如下列代码:
var testCase = require('mocha').describe; var pre = require('mocha').before; var assertions = require('mocha').it; var assert = require('assert'); testCase('Array', function() { pre(function() { // ... }); testCase('#indexOf()', function() { assertions('should return -1 when not present', function() { assert.equal([1,2,3].indexOf(4), -1); }); }); }); 上述默认的接口是BDD, 如果想
上述默认的接口是BDD, 如果想使用其他的接口,可以使用下面的命令行:
mocha -ui 接口(TDD|Exports|QUnit...)
Reporters (测试报告/结果样式)
Mocha 支持不同格式的测试结果暂时,其支持 Spec, Dot Matrix,Nyan,TAP…等等,默认的样式为Spec,如果需要其他的样式,可以用下列命令行实现:
mocha --reporter 具体的样式(Dot Matrix|TAP|Nyan...)
Editor Plugins
mocha 能很好的集成到TextMate,Wallaby.js,JetBrains(IntelliJ IDEA, WebStorm) 中,这里就用WebStorm作为例子。 JetBrains提供了NodeJS的plugin让我们很好的使用mocha和nodeJs。 添加mocha 的相关的菜单,
这里就可以直接在WebStorm中运行,调试mocha的测试用例了。
The above is the detailed content of Detailed introduction to the installation and use of NodeJs testing framework Mocha. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.