NodeJs テスト フレームワーク Mocha のインストールと使用方法の詳細な紹介

黄舟
リリース: 2017-03-28 14:18:52
オリジナル
1631 人が閲覧しました

この記事では、簡単に始められるように、Mocha の使い方を包括的に紹介します。これまでテストについて何も知らなかった場合でも、この記事は JavaScript での単体テストの入門として使用できます インストールと公式ドキュメントの順序で暫定的に使用します
コンソールウィンドウで次のコマンドを実行します:

$ npm install -g mocha
$ mk
dir
 test
$ $EDITOR test/test.js
ログイン後にコピー

次のコードを記述できます:

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));
    });
  });
});
ログイン後にコピー

コンソールに戻ります:

$  mocha
  .
  ✔ 1 test complete (1ms)
ログイン後にコピー

ここでmochaはテストの内容を検索します

ライブラリを判定します

これは、デフォルトでは、nodejs ライブラリを使用することができますが、同時に Mocha は別のライブラリを使用することをサポートします。アサーション ライブラリ。次のアサーション ライブラリをサポートできるようになりました。各アサーション ライブラリの使用方法にはいくつかの違いがあります。これらのドキュメント全体で should.js BDD スタイルを参照してください。このアサーション ライブラリを使用します)

2 better-assert) C スタイルの自己文書化された Assert() (C-

model

の下のアサーション ライブラリ)

3 Expect.js Expect( ) スタイルのアサーション (expect モード アサーション ライブラリ)

4 予期しない拡張可能な BDD アサーション ツールキット

5 chai Expect()、assert()、および should スタイル アサーション


同期コード同期コードは、テストが同期関数であることを意味し、上記の配列の関連するコード例はこれを理解するのが簡単です。

非同期コード

非同期コードのテストしかないのは、次のコードなど、nodejs 上の多くの非同期関数では、ユースケースが完了した後でのみテストが完了するためです。
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(); // 只有执行完此函数后,该测试用例算是完成。
      });
    });
  });
});
ログイン後にコピー

describe と it を詳しく説明します

上記のコード例は比較的単純ですが、describe と it とは何ですか? 一般的に、describe は TestSuit (テスト コレクション) を宣言する必要があり、テスト コレクションはネストして管理できることがわかります。 、そして it ステートメントは特定のテスト ケースを定義します。 bdd インターフェイスを例に取ると、具体的なソース コードは次のとおりです:

  /**
     * 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 (フック)

実際、これは単体テストを作成するときに非常に一般的な関数です。つまり、実行前または実行後に特定の

が必要です。テスト ケースとテスト ケース コレクション

(フック)。 Mocha は、before()、after()、before

Each

() および aftetEach() を提供します。 サンプル コードは次のとおりです。

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
});
ログイン後にコピー

フックには、次のような他の用途もあります。良いレビューの質問

非同期フック (非同期フック): フック関数は同期または非同期にすることができます。 非同期フックのサンプル コードを見てみましょう:

ルートレベル フック。 (グローバル フック) - 記述の外側 (テスト ケース コレクションの外側) で実行されます。これは通常、すべてのテスト ケースの前または後に実行されます。 保留中のテスト (保留中のテスト)

次のコードのような、TODO に少し似た、まだ完了していないテストがいくつかあります:

describe('Array', function() {
  describe('#indexOf()', function() {
    // pending test below 暂时不写回调函数
    it('should return -1 when the value is not present');
  });
});
ログイン後にコピー

排他的なテスト (排他的なテスト)


排他的なテストでは、テスト セットまたは1 つのテスト ケースのみが実行され、他のテスト ケースはスキップされます。たとえば、次のテスト ケース集:

describe('Array', function() {
  describe.only('#indexOf()', function() {
    // ...
  });
     // 测试集合不会被执行
    describe('#ingored()', function() {
    // ...
  });
});
ログイン後にコピー

以下はテスト ケースです:

describe('Array', function() {
  describe('#indexOf()', function() {
    it.only('should return -1 unless present', function() {
      // ...
    });
     // 测试用例不会执行
    it('should return the index when present', function() {
      // ...
    });
  });
});
ログイン後にコピー

フック (コールバック関数) が実行されることに注意してください。

包括的テスト (テストを含む)

only 関数とは対照的に、skip 関数を使用すると、mocha システムは現在のテスト ケース コレクションを無視し、スキップされたすべてのテスト ケースは保留中として報告されます。

以下はテスト ケースのコレクションのサンプル コードです:

describe('Array', function() {
   //该测试用例会被ingore掉 
  describe.skip('#indexOf()', function() {
    // ...
  });
   // 该测试会被执行
   describe('#indexOf()', function() {
    // ...
  });
});
ログイン後にコピー

次の例は特定のテスト ケース用です:

describe('Array', function() {
  describe('#indexOf()', function() {
     // 测试用例会被ingore掉
    it.skip('should return -1 unless present', function() {
      // ...
    });
     // 测试用例会被执行
    it('should return the index when present', function() {
      // ...
    });
  });
});
ログイン後にコピー

テストの動的生成 (動的に生成されるテスト ケース)

実際、これは多くのテスト ケースでも使用されます。 NUnit などの他のテスト ツール はい、テスト ケースのパラメーターをセットに置き換えて、さまざまなテスト ケースを生成します。以下は具体的な例です:

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);
    });
  });
});
ログイン後にコピー

インターフェース (

インターフェース
)

Mocha のインターフェース システムを使用すると、ユーザーは、さまざまなスタイルの関数またはスタイルを使用してテスト ケース コレクションと特定のテスト ケースを作成できます。スタイルインターフェイスが必要です。

BDD - これは mocha のデフォルトのスタイルであり、この記事のサンプル コードはこの形式です。

describe()、context()、it()、before()、after()、beforeEach()、および afterEach() 関数が提供されます。サンプル コードは次のとおりです。
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的测试用例了。

以上がNodeJs テスト フレームワーク Mocha のインストールと使用方法の詳細な紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!