NodeJs 테스트 프레임워크 Mocha의 설치 및 사용에 대한 자세한 소개

黄舟
풀어 주다: 2017-03-28 14:18:52
원래의
1631명이 탐색했습니다.

이 글에서는 Mocha를 쉽게 시작할 수 있도록 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의 Assert 라이브러리를 사용할 수 있습니다. 동시에 Mocha는 다양한 주장 라이브러리를 사용할 수 있도록 지원합니다. 각 주장 라이브러리의 사용법에는 약간의 차이가 있습니다.

1. 이 문서 전반에 걸쳐 표시된 .js BDD 스타일(BDD 모드, 이 문서는 이 어설션 라이브러리를 사용합니다.)

2 better-assert) c 스타일 자체 문서화 Assert() (C-

Model<

3 예상. js Expect() 스타일 어설션(예상 모드 어설션 라이브러리)
4 확장 가능한 BDD 어설션 툴킷 예상치 못한 5 chai Expect(), Assert() 및 should 스타일 어설션
동기 코드

동기 코드는 테스트가 동기 함수라는 뜻입니다.

비동기 코드

비동기 코드가 많아서 테스트가 더 쉽습니다. 예를 들어 아래 코드에서는 done() 함수가 실행될 때까지 테스트 케이스가 완료되지 않습니다.

describe(&#39;User&#39;, function() {
  describe(&#39;#save()&#39;, function() {
    it(&#39;should save without error&#39;, function(done) {
      var user = 
new
 User(&#39;Luna&#39;);
      user.saveAsync(function(err) {
        
if
 (err) throw err;
        done(); // 只有执行完此函数后,该测试用例算是完成。
      });
    });
  });
});
로그인 후 복사

설명과 설명

위의 예제 코드는 상대적입니다. 간단합니다. 설명과 설명은 무엇입니까? 일반적으로 말하면, explain은 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(hook)

사실 이는 단위 테스트를 작성할 때 매우 흔히 사용하는 함수입니다. 테스트 케이스 및 테스트 케이스 컬렉션 전후에 특정

콜백 함수

(후크)가 필요합니다. Mocha는 before(), after(), before

Each

() 및 aftetEach()를 제공합니다. 샘플 코드는 다음과 같습니다.

훅은 다음과 같은 용도로도 사용됩니다. Hooks 설명 - 문제를 더 잘 보기 위해 Hook 함수에 설명을 추가할 수 있습니다.

Asynchronous Hooks: Hook 함수는 동기식 또는 비동기식일 수 있습니다. 다음은 테스트 사례를 살펴보겠습니다. 비동기 후크:

  beforeEach(function(done) {
    // 异步函数
    db.
clear
(function(err) {
      if (err) return done(err);
      db.save([tobi, loki, jane], done);
    });
  });
로그인 후 복사

루트 수준 후크(전역 후크) - 설명 외부(테스트 케이스 컬렉션 외부)에서 실행됩니다. 이는 일반적으로 모든 테스트 케이스 전후에 실행됩니다.
Pending Tests(보류 중인 테스트)

다음 코드와 같이 TODO와 약간 유사한 아직 완료되지 않은 테스트가 있습니다.

describe(&#39;Array&#39;, function() {
  describe(&#39;#indexOf()&#39;, function() {
    // pending test below 暂时不写回调函数
    it(&#39;should return -1 when the value is not present&#39;);
  });
});
로그인 후 복사

Exclusive Tests(독점 테스트) )

독점 테스트에서는 테스트 또는 테스트 케이스 세트 중 하나만 실행하고 나머지는 건너뛸 수 있습니다. 예를 들어, 다음과 같은 테스트 케이스 모음:

describe(&#39;Array&#39;, function() {
  describe.only(&#39;#indexOf()&#39;, function() {
    // ...
  });
     // 测试集合不会被执行
    describe(&#39;#ingored()&#39;, function() {
    // ...
  });
});
로그인 후 복사

다음은 테스트 케이스입니다:

describe(&#39;Array&#39;, function() {
  describe(&#39;#indexOf()&#39;, function() {
    it.only(&#39;should return -1 unless present&#39;, function() {
      // ...
    });
     // 测试用例不会执行
    it(&#39;should return the index when present&#39;, function() {
      // ...
    });
  });
});
로그인 후 복사

Hooks(콜백 함수)가 실행된다는 점에 유의해야 합니다.

포괄적 테스트(테스트 포함)

유일한 기능과 달리 건너뛰기 기능은 Mocha 시스템이 현재 테스트 케이스 모음 또는 테스트 케이스를 무시하도록 하며, 건너뛴 모든 테스트 케이스는 보류 중으로 보고되었습니다.

다음은 테스트 사례 모음에 대한 예시 코드입니다.

describe(&#39;Array&#39;, function() {
   //该测试用例会被ingore掉 
  describe.skip(&#39;#indexOf()&#39;, function() {
    // ...
  });
   // 该测试会被执行
   describe(&#39;#indexOf()&#39;, function() {
    // ...
  });
});
로그인 후 복사

다음 예시는 특정 테스트 사례에 대한 것입니다.

describe(&#39;Array&#39;, function() {
  describe(&#39;#indexOf()&#39;, function() {
     // 测试用例会被ingore掉
    it.skip(&#39;should return -1 unless present&#39;, function() {
      // ...
    });
     // 测试用例会被执行
    it(&#39;should return the index when present&#39;, function() {
      // ...
    });
  });
});
로그인 후 복사

동적 생성 테스트(동적으로 생성된 테스트 사례)

사실 이는 테스트 케이스 매개변수를 세트로 대체하여 다양한 테스트 케이스를 생성하는 NUnit과 같은 다른 많은 테스트 도구에서도 사용할 수 있습니다. 다음은 구체적인 예입니다.

var assert = require(&#39;assert&#39;);
function add() {
  return Array.prototype.slice.call(arguments).reduce(function(prev, curr) {
    return prev + curr;
  }, 0);
}
describe(&#39;add()&#39;, 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(&#39;correctly adds &#39; + test.args.length + &#39; args&#39;, function() {
      var res = add.apply(null, test.args);
      assert.equal(res, test.expected);
    });
  });
});
로그인 후 복사

인터페이스(

인터페이스

)

Mocha의 인터페이스 시스템을 통해 사용자는 다양한 스타일의 기능이나 스타일을 사용하여 테스트 케이스 컬렉션과 세부 사항을 작성할 수 있습니다. 테스트 사례에서 mocha에는 BDD, TDD, 내보내기, QUnit 및 Require 스타일 인터페이스가 있습니다. BDD - mocha의 기본 스타일이며, 이 글의 샘플 코드는 이 형식입니다.

describe(), context(), it(), before(), after(), beforeEach(), afterEach() 함수를 제공합니다.

describe(&#39;Array&#39;, function() {
    before(function() {
      // ...
    });
    describe(&#39;#indexOf()&#39;, function() {
      context(&#39;when not present&#39;, function() {
        it(&#39;should not throw an error&#39;, function() {
          (function() {
            [1,2,3].indexOf(4);
          }).should.not.throw();
        });
        it(&#39;should return -1&#39;, function() {
          [1,2,3].indexOf(4).should.equal(-1);
        });
      });
      context(&#39;when present&#39;, function() {
        it(&#39;should return the index where the element first appears in the array&#39;, function() {
          [1,2,3].indexOf(3).should.equal(2);
        });
      });
    });
  });
로그인 후 복사

TDD - 提供了 suite(), test(), suiteSetup(), suiteTeardown(), setup(), 和 teardown()的函数,其实和BDD风格的接口类似(suite相当于describe,test相当于it),示例代码如下:

suite(&#39;Array&#39;, function() {
  setup(function() {
    // ...
  });
  suite(&#39;#indexOf()&#39;, function() {
    test(&#39;should return -1 when not present&#39;, function() { 
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});
로그인 후 복사

Exports - 对象的值都是测试用例集合,函数值都是测试用例。 关键字before, after, beforeEach, and afterEach 需要特别定义。
具体的示例代码如下:

module.exports = {
  before: function() {
    // ...
  },
  &#39;Array&#39;: {
    &#39;#indexOf()&#39;: {
      &#39;should return -1 when not present&#39;: 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(&#39;Array&#39;);
test(&#39;#length&#39;, function() {
  var arr = [1,2,3];
  ok(arr.length == 3);
});
test(&#39;#indexOf()&#39;, function() {
  var arr = [1,2,3];
  ok(arr.indexOf(1) == 0);
  ok(arr.indexOf(2) == 1);
  ok(arr.indexOf(3) == 2);
});
suite(&#39;String&#39;);
test(&#39;#length&#39;, function() {
  ok(&#39;foo&#39;.length == 3);
});
로그인 후 복사

Require - 该接口允许我们利用require关键字去重新封装定义 describe ,it等关键字,这样可以避免全局变量
如下列代码:

var testCase = require(&#39;mocha&#39;).describe;
var pre = require(&#39;mocha&#39;).before;
var assertions = require(&#39;mocha&#39;).it;
var assert = require(&#39;assert&#39;);
testCase(&#39;Array&#39;, function() {
  pre(function() {
    // ...
  });
  testCase(&#39;#indexOf()&#39;, function() {
    assertions(&#39;should return -1 when not present&#39;, 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!