Detailed introduction to the installation and use of NodeJs testing framework Mocha

黄舟
Release: 2017-03-28 14:18:52
Original
1597 people have browsed it

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

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
Copy after login

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)); }); }); });
Copy after login

Return to the console :

$ mocha . ✔ 1 test complete (1ms)
Copy after login

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(); // 只有执行完此函数后,该测试用例算是完成。 }); }); }); });
Copy after login

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; };
Copy after login

Hooks

In fact, this is a very common function when writing unit tests, which is to execute test cases and test cases A certaincallback 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 });
Copy after login

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); }); });
Copy after login

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'); }); });
Copy after login

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() { // ... }); });
Copy after login

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() { // ... }); }); });
Copy after login

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() { // ... }); });
Copy after login

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() { // ... }); }); });
Copy after login

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); }); }); });
Copy after login

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); }); }); }); });
Copy after login

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)); }); }); });
Copy after login

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); } } } };
Copy after login

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); });
Copy after login

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, 如果想
Copy after login

上述默认的接口是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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!