Programing

TDD 용 JavaScript 단위 테스트 도구

lottogame 2020. 9. 30. 08:37
반응형

TDD 용 JavaScript 단위 테스트 도구


많은 JavaScript 단위 테스트 및 테스트 도구를 조사하고 고려했지만 TDD를 완전히 준수하는 데 적합한 옵션을 찾지 못했습니다. 그렇다면 TDD를 완전히 준수하는 JavaScript 단위 테스트 도구가 있습니까?


카르마 또는 각도기

Karma는 Node.js로 빌드되고 단위 테스트를위한 JavaScript 테스트 실행기입니다.

Protractor는 종단 간 테스트 용이며 Selenium Web Driver를 사용하여 테스트를 진행합니다.

둘 다 Angular 팀에서 만들었습니다. 원하는 어설 션 라이브러리를 사용할 수 있습니다.

Screencast : Karma 시작하기

관련 :

장점 :

  • node.js를 사용하므로 Win / OS X / Linux와 호환됩니다.
  • PhantomJS로 브라우저 또는 헤드리스에서 테스트 실행
  • 한 번에 여러 클라이언트에서 실행
  • 브라우저 실행, 캡처 및 자동 종료 옵션
  • 개발 컴퓨터에서 또는 개별적으로 서버 / 클라이언트를 실행하는 옵션
  • 명령 줄에서 테스트 실행 (ant / maven에 통합 가능)
  • 테스트 xUnit 또는 BDD 스타일 작성
  • 여러 JavaScript 테스트 프레임 워크 지원
  • 저장시 자동 실행 테스트
  • 프록시 요청 교차 도메인
  • 사용자 정의 가능 :
    • 다른 테스트 프레임 워크를 래핑하도록 확장합니다 (Jasmine, Mocha, QUnit 내장).
    • 자신의 주장 / 반박
    • 기자
    • 브라우저 실행기
  • WebStorm 용 플러그인
  • Netbeans IDE에서 지원

단점 :

mocha.js

mocha.js의 기능, 강점 및 약점에 대해 언급 할 자격이 전혀 없습니다.하지만 JS 커뮤니티에서 제가 신뢰하는 사람이 추천 한 것뿐입니다.

웹 사이트에서보고 한 기능 목록 :

  • 브라우저 지원
  • 약속을 포함한 간단한 비동기 지원
  • 테스트 커버리지보고
  • 문자열 차이 지원
  • 테스트 실행을위한 javascript # API
  • CI 지원 등을위한 적절한 종료 상태
  • non-ttys에 대한 색상을 자동 감지하고 비활성화합니다.
  • 포착되지 않은 예외를 올바른 테스트 케이스에 매핑
  • 비동기 테스트 시간 초과 지원
  • 테스트 별 제한 시간
  • 으르렁 거리는 알림 지원
  • 테스트 기간보고
  • 느린 테스트를 강조
  • 파일 감시자 지원
  • 전역 변수 누출 감지
  • 선택적으로 정규 표현식과 일치하는 테스트 실행
  • 활성 루프에서 "중단"을 방지하기위한 자동 종료
  • 쉽게 메타 생성 도구 모음 및 테스트 케이스
  • mocha.opts 파일 지원
  • 테스트 실행을 필터링하기위한 클릭 가능한 제품군 제목
  • 노드 디버거 지원
  • done ()에 대한 여러 호출을 감지합니다.
  • 원하는 어설 션 라이브러리 사용
  • 9 명 이상의 리포터와 번들로 제공되는 확장 가능한보고
  • 확장 가능한 테스트 DSL 또는 "인터페이스"
  • 전, 후, 각 전, 각 후크 후
  • 임의의 트랜스 파일러 지원 (커피 스크립트 등)
  • TextMate 번들

Yolpo

Yolpo

더 이상 존재하지 않으며 대신 sequential.js로 리디렉션 됩니다.

Yolpo는 자바 스크립트 실행을 시각화하는 도구입니다. Javascript API 개발자는 API를 보여주고 알리는 사용 사례를 작성하는 것이 좋습니다. 이러한 사용 사례는 회귀 테스트의 기초를 형성합니다.

AVA

AVA 로고

ES2015를 기본적으로 지원하는 미래형 테스트 실행기. JavaScript는 단일 스레드이지만 Node.js의 IO는 비동기 특성으로 인해 병렬로 발생할 수 있습니다. AVA는이를 활용하고 테스트를 동시에 실행하므로 IO가 많은 테스트에 특히 유용합니다. 또한 테스트 파일은 별도의 프로세스로 병렬로 실행되므로 각 테스트 파일에 대해 더 나은 성능과 격리 된 환경을 제공합니다.

  • 최소 및 빠름
  • 간단한 테스트 구문
  • 동시에 테스트 실행
  • 원자 테스트 작성 강제
  • 암시 적 전역 없음
  • 각 테스트 파일에 대한 격리 된 환경
  • ES2015로 테스트 작성
  • 약속 지원
  • 생성기 기능 지원
  • 비동기 기능 지원
  • 관찰 가능한 지원
  • 향상된 어설 션
  • 선택적 TAP 출력
  • 스택 추적 정리

Buster.js

A JavaScript test-runner built with Node.js. Very modular and flexible. It comes with its own assertion library, but you can add your own if you like. The assertions library is decoupled, so you can also use it with other test-runners. Instead of using assert(!...) or expect(...).not..., it uses refute(...) which is a nice twist imho.

A browser JavaScript testing toolkit. It does browser testing with browser automation (think JsTestDriver), QUnit style static HTML page testing, testing in headless browsers (PhantomJS, jsdom, ...), and more. Take a look at the overview!

A Node.js testing toolkit. You get the same test case library, assertion library, etc. This is also great for hybrid browser and Node.js code. Write your test case with Buster.JS and run it both in Node.js and in a real browser.

Screencast: Buster.js Getting started (2:45)

pros:

  • Uses node.js, so compatible with Win/OS X/Linux
  • Run tests from a browser or headless with PhantomJS (soon)
  • Run on multiple clients at once
  • Supports NodeJS testing
  • Don't need to run server/clients on development computer (no need for IE)
  • Run tests from a command line (can be integrated into ant/maven)
  • Write tests xUnit or BDD style
  • Supports multiple JavaScript test frameworks
  • Defer tests instead of commenting them out
  • SinonJS built-in
  • Auto-run tests on save
  • Proxies requests cross-domain
  • Possible to customize:
    • Extend it to wrap other test-frameworks (JsTestDriver built in)
    • Your own assertions/refutes
    • Reporters (xUnit XML, traditional dots, specification, tap, TeamCity and more built-in)
    • Customize/replace the HTML that is used to run the browser-tests
  • TextMate and Emacs integration

Cons:

  • Stil in beta so can be buggy
  • No plugin for Eclipse/IntelliJ (yet)
  • Doesn't group results by os/browser/version like TestSwarm *. It does, however, print out the browser name and version in the test results.
  • No history of previous test results like TestSwarm *
  • Doesn't fully work on windows as of May 2014

* TestSwarm is also a Continuous Integration server, while you need a separate CI server for Buster.js. It does, however, output xUnit XML reports, so it should be easy to integrate with Hudson, Bamboo or other CI servers.

TestSwarm

https://github.com/jquery/testswarm

TestSwarm is officially no longer under active development as stated on their GitHub webpage. They recommend Karma, browserstack-runner, or Intern.

Jasmine

재스민 속

This is a behavior-driven framework (as stated in quote below) that might interest developers familiar with Ruby or Ruby on Rails. The syntax is based on RSpec that are used for testing in Rails projects.

Jasmine specs can be run from an html page (in qUnit fashion) or from a test runner (as Karma).

Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM.

If you have experience with this testing framework, please contribute with more info :)

Project home: http://jasmine.github.io/

QUnit

QUnit focuses on testing JavaScript in the browser while providing as much convenience to the developer as possible. Blurb from the site:

QUnit is a powerful, easy-to-use JavaScript unit test suite. It's used by the jQuery, jQuery UI, and jQuery Mobile projects and is capable of testing any generic JavaScript code

QUnit shares some history with TestSwarm (above):

QUnit was originally developed by John Resig as part of jQuery. In 2008 it got its own home, name and API documentation, allowing others to use it for their unit testing as well. At the time it still depended on jQuery. A rewrite in 2009 fixed that, now QUnit runs completely standalone. QUnit's assertion methods follow the CommonJS Unit Testing specification, which was to some degree influenced by QUnit.

Project home: http://qunitjs.com/

Sinon

Another great tool is sinon.js by Christian Johansen, the author of Test-Driven JavaScript Development. Best described by himself:

Standalone test spies, stubs and mocks for JavaScript. No dependencies works with any unit testing framework.

Intern

The Intern Web site provides a direct feature comparison to the other testing frameworks on this list. It offers more features out of the box than any other JavaScript-based testing system.

JEST

A new but yet very powerful testing framework. It allows snapshot based testing as well this increases the testing speed and creates a new dynamic in terms of testing

Check out one of their talks: https://www.youtube.com/watch?v=cAKYQpTC7MA

Better yet: Getting Started


Take a look at the Dojo Object Harness (DOH) unit test framework which is pretty much framework independent harness for JavaScript unit testing and doesn't have any Dojo dependencies. There is a very good description of it at Unit testing Web 2.0 applications using the Dojo Objective Harness.

If you want to automate the UI testing (a sore point of many developers) — check out doh.robot (temporary down. update: other link http://dojotoolkit.org/reference-guide/util/dohrobot.html ) and dijit.robotx (temporary down). The latter is designed for an acceptance testing. Update:

Referenced articles explain how to use them, how to emulate a user interacting with your UI using mouse and/or keyboard, and how to record a testing session, so you can "play" it later automatically.


Chutzpah - A JavaScript Test Runner

I created an open source project called Chutzpah which is a test runner for JavaScript unit tests. Chutzpah enables you to run JavaScript unit tests from the command line and from inside of Visual Studio. It also supports running in the TeamCity continuous integration server.


The JavaScript section of the Wikipedia entry, List of Unit Testing Frameworks, provides a list of available choices. It indicates whether they work client-side, server-side, or both.


BusterJS

There is also BusterJS from Christian Johansen, the author of Test Driven Javascript Development and the Sinon framework. From the site:

Buster.JS is a new JavaScript testing framework. It does browser testing by automating test runs in actual browsers (think JsTestDriver), as well as Node.js testing.


google-js-test:

JavaScript testing framework released by Google: https://github.com/google/gjstest

  • Extremely fast test startup and execution time, without having to run a browser.
  • Clean, readable output in the case of both passing and failing tests.
  • A browser-based test runner that can simply be refreshed whenever JS is changed.
  • Style and semantics that resemble Google Test for C++.
  • A built-in mocking framework that requires minimal boilerplate code (e.g. no $tearDown or $verifyAll) with style and semantics based on the Google C++ Mocking Framework.

There are currently no binaries for Windows


We are now using Qunit with Pavlov and JSTestDriver all together. This approach works well for us.

QUnit

Pavlov, source

jsTestDriver, source


You have "runs on actual browser" as a pro, but in my experience that is a con because it is slow. But what makes it valuable is the lack of sufficient JS emulation from the non-browser alternatives. It could be that if your JS is complex enough that only an in browser test will suffice, but there are a couple more options to consider:

HtmlUnit: "It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating either Firefox or Internet Explorer depending on the configuration you want to use." If its emulation is good enough for your use then it will be much faster than driving a browser.

But maybe HtmlUnit has good enough JS support but you don't like Java? Then maybe:

Celerity: Watir API running on JRuby backed by HtmlUnit.

or similarly

Schnell: another JRuby wrapper of HtmlUnit.

Of course if HtmlUnit isn't good enough and you have to drive a browser then you might consider Watir to drive your JS.


YUI has a testing framework as well. This video from Yahoo! Theater is a nice introduction, although there are a lot of basics about TDD up front.

This framework is generic and can be run against any JavaScript or JS library.


You might also be interested in the unit testing framework that is part of qooxdoo, an open source RIA framework similar to Dojo, ExtJS, etc. but with quite a comprehensive tool chain.

Try the online version of the testrunner. Hint: hit the gray arrow at the top left (should be made more obvious). It's a "play" button that runs the selected tests.

To find out more about the JS classes that let you define your unit tests, see the online API viewer.

For automated UI testing (based on Selenium RC), check out the Simulator project.


You should have a look at env.js. See my blog for an example how to write unit tests with env.js.


We added JUnit integration to our Java to Javascript code generator ST-JS (http://st-js.org). The framework generates to corresponding Javascript for both the tested code and the unit tests and sends the code to different browsers.

There is no need for a separate server as the unit test runner opens the needed http port (and closes it once the tests finished). The framework manipulates the Java stacktrace so that the failed asserts are correctly displayed by the JUnit Eclipse plugin. Here is a simple example with jQuery and Mockjax:

@RunWith(STJSTestDriverRunner.class)
@HTMLFixture("<div id='fortune'></div>")

@Scripts({ "classpath://jquery.js",
       "classpath://jquery.mockjax.js", "classpath://json2.js" })
public class MockjaxExampleTest {
  @Test
  public void myTest() {
    $.ajaxSetup($map("async", false));
    $.mockjax(new MockjaxOptions() {
      {
        url = "/restful/fortune";
        responseText = new Fortune() {
          {
            status = "success";
            fortune = "Are you a turtle?";
          }
        };
      }
    });

    $.getJSON("/restful/fortune", null, new Callback3<Fortune, String, JQueryXHR>() {
      @Override
      public void $invoke(Fortune response, String p2, JQueryXHR p3) {
        if (response.status.equals("success")) {
          $("#fortune").html("Your fortune is: " + response.fortune);
        } else {
          $("#fortune").html("Things do not look good, no fortune was told");
        }

      }
    });
    assertEquals("Your fortune is: Are you a turtle?", $("#fortune").html());
  }

  private static class Fortune {
    public String status;
    public String fortune;
  }
}

MochiKit 에는 SimpleTest라는 테스트 프레임 워크가 있습니다. 다음 은 원저자블로그 게시물입니다 .

참고 URL : https://stackoverflow.com/questions/300855/javascript-unit-test-tools-for-tdd

반응형