


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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application
