关于JavaScript测试工具:QUnit, Jasmine, MoCha

在进行前端开发过程中,在某些场景下,需要通过编写单元测试来提高代码质量。而JavaScript常用的单元测试框架有这几个:QUnit, Jasmine, MoCha.下面就基于这三个工具,简单做一比较:

1. QUnit

QUnit是一个JavaScript单元测试框架. 它是个强大,容易使用和上手的JavaScript单元测试框架.它被用于进行 jQuery, jQuery UI and jQuery 移动工程的测试,以及其他通用的JavaScript代码测试.

Features:
- Similar to server-side frameworks(JUnit, Nunit)
- Built by the jQuery team
- Used to test jQuery‘s features
- No dependencies
- Can test server-side JavaScript

使用方法:

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>QUnit Example</title>
    <link rel="stylesheet" href="/resources/qunit.css">
  </head>
  <body>
    <div id="qunit"></div>
    <div id="qunit-fixture"></div>
    <script src="/resources/qunit.js"></script>
    <script src="/resources/tests.js"></script>
  </body>
</html>

tests.js:
test( "hello test", function() {
  ok( 1 == "1", "Passed!" );
});

断言方法:

- ok(state, message) 
- equal(actual, expected, message) 
- notEqual (actual, expected, message) 
- deepEqual (actual, expected, message) 
- notDeepEqual(actual, expected, message) 
- strictEqual (actual, expected, message) 
- notStrictEqual(actual, expected, message) 
- raises (actual, expected, message)

2. Jasmine

asmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.

Since describe and it blocks are functions, they can contain any executable code necessary to implement the test. JavaScript scoping rules apply, so variables declared in a describe are available to any it block inside the suite.

Features:
- Open Source Framework
- Behavior Driven Development framework
- Supports both client-side and server-side testing

行为驱动开发:Behavior Driven Development:
Write a failing acceptance test <--> Write a failing unit test <--> Write code to pass the test

基本用法:
Using the default model SpecRunner.html which referenced jasmine.css, jasmine.js, and jasmine-html.js. Write your own spec as below:

MySpec.js

describe("MyClass", function() {

  it("should be true", function() {
    expect(true).toBeTruthy();
  });

  it("should be false", function() {
    expect(true).toBeFalsy();
  });
});

Built-in Matchers (not):
- expect(x).(not.)toEqual(y); 
- expect(x).(not.)toBe(y); 
- expect(x ).(not.)toMatch(pattern); 
- expect(x ).(not.)toBeDefined(); 
- Expect(x).(not.)toBeUndefined(); 
- expect(x ).(not.)toBeNull(); 
- expect(x ).(not.)toBeTruthy(); 
- expect(x ).(not.)toBeFalsy(); 
- expect(x ).(not.)toContain(y); 
- expect(x ).(not.)toBeLessThan(y); 
- expect(x ).(not.)toBeGreaterThan(y); 
- expect(function(){ fn ();}).(not.)toThrow(ex);

Creating Custom Matcher:

steps:
1. Typically created in a beforeEach 
2. this.addMatchers ()

Example:

beforeEach(function() {
  this.addMatchers ({
    toBeFive: function() {
      return this.actual === 5;
    }
  });
});

Skipping tests:

Add an “x” in front of the describe or the it function

3. Mocha

Mocha is a feature-rich JavaScript test framework running on node and the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.

Features:

- Open Source Framework 
- Started in Node 
- Supports both client-side and server-side testing 
- Supports both BDD and TDD style tests 
- Supports both command line and browser 
- Supports any JavaScript assertion library (YUI Port, expect.js, should.js, jshould.js, assert.js, chai.js) 
- Supports asynchronous testing 
- Requires an assertion library

Usage:

html

<!DOCTYPE html>
<html>
  <head>
    <title>Mocha</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="mocha.css" />
  </head>
  <body>
    <div id="mocha"></div>
    <script src="mocha.js"></script>
    <script src="chai.js"></script>
    <script>mocha.setup(‘tdd‘)</script>
    <script>expect = chai.expect;</script>
    <script src="test.js"></script>
    <script>
      mocha.run();
    </script>
  </body>
</html>

(QUnit style)test.js

suite(‘my first suite‘);

beforeEach(function() {
  console.log(‘setup‘);
});

afterEach(function() {
  console.log(‘teardown‘);
});

before(function() {
  console.log(‘before‘);
});

after(function() {
  console.log(‘after‘);
});

test(‘test 1‘, function() {
  expect(1).to.equal(1);
  console.log(‘test‘);
});

(TDD style)test.js

suite(‘my first suite‘, function() {

setup(function() {
  console.log(‘setup‘);
});

teardown(function() {
  console.log(‘teardown‘);
});

before(function() {
  console.log(‘before‘);
});

after(function() {
  console.log(‘after‘);
});

test(‘test 1‘, function() {
  expect(1).to.equal(1);
  console.log(‘test‘);
});

});

(BDD style)test.js

describe(‘my first suite‘, function() {

  beforeEach(function() {
    console.log(‘setup‘);
  });

  afterEach(function() {
    console.log(‘teardown‘);
  });

  before(function() {
    console.log(‘before‘);
  });

  after(function() {
    console.log(‘after‘);
  });

  it(‘should be my first test‘, function() {
    expect(1).to.equal(1);
    console.log(‘test‘);
  });

  describe(‘inner suite‘, function() {

    it(‘should be my second test‘, function() {
      expect(2).to.equal(2);
      console.log(‘test 2‘);
    });

  });

});

Three different assertion syntaxes in Chai js
Assert: var assert = chai.assert;
Expect: var expect = chai.expect;
Should: var should = chai.should(); // notice should is a function

Writing & Running Mocha Tests

TDD and BDD style tests:
(see above usage part)

Filtering: 
In the test url, add ?grep=keyword can filter tests.

View source code:
Click on the test, the source code should display.

Exclusive Tests:
Only display one test: it.only(‘...‘, function(){...})
Only display one block tests: describe.only(‘...‘, function(){...})

Skipping Tests:
Skip one test: it.skip(‘...‘, function(){...})
Skip one block test: describe.skip(‘...‘, function(){...})

Pending Test:
Only have the description no function: it(‘...‘);

Global Leaks:
Newer version does not have this problem.

Slow Test:
Debug source code in developer tool, set break point to one test, you will see the time of the test spent.

Asynchronous Tests with Mocha

it(‘should be something‘, function(done){
  ...
  done();
})

Timeout:

The default timeout is 2 seconds for each test.  

mocha.setup({timeout:3000}); // set timeout for all tests

describe(‘Outer Describe‘, function() {
  it(‘should be asynchronous‘, function(done) {
    this.timeout(2500); // setup timeout only for this test
    setTimeout(function() {
      expect(1).to.equal(1);
      done();
    }, 2400);
  })
});

Comparison

QUnit is very easy to get started with, as you only need to include two files(qunit.css and qunit.js) and a little bit of markup, then you can start writing tests. QUnit is TDD style tests.

QUnit 是非常容易上手,你仅仅需要包含两个文件(qunit.css and qunit.js)和一些很少的标记,然后就可以开始编写测试了。QUnit是一种TDD风格的测试;

Jasmine is easier to get started – it’s all-in-one package will generally get you and a team up and testing much faster, and you’ll be in good hands with it. Jasmine is BDD style tests.

jasmine 是很容易开始---它是 all-in-one package ,可以让你和一个组测试起来很快速,并且你可以很快的上手,Jasmine是一种BDD风格的测试;

Mocha is significantly more flexible, but you have to piece it together yourself. There is no spy framework built in to Mocha, so most people use sinon.js. There’s no assertion framework built in to Mocha either, so you’ll have to pick one. Chai is the popular one, but there are many, many others available. You can also configure Mocha for BDD (jasmine style) or TDD (QUnit style) easily. But you have to pick and choose how you want Mocha to work. This flexibility is great because you can build the test environment that you really want. But it means you have more work to do, more individual pieces to maintain /  keep up to date, etc.

时间: 2024-10-06 21:15:16

关于JavaScript测试工具:QUnit, Jasmine, MoCha的相关文章

JS-009-单元测试工具 Qunit 初识

后续更新,敬请期待...非常感谢! 至此, JS-009-单元测试工具 Qunit 初识 顺利完结,希望此文能够给初学 JavaScript 的您一份参考. 最后,非常感谢亲的驻足,希望此文能对亲有所帮助.热烈欢迎亲一起探讨,共同进步.非常感谢! ^_^

前端技术之:JavaScript测试工具

Mocha一个用于Node.js与浏览器端的简单.自由.有趣的JavaScript测试框架.https://mochajs.org/https://github.com/mochajs/mocha Jest一个令人愉悦的JavaScript测试框架.https://jestjs.io/https://github.com/facebook/jest Ava测试可能是个负担,AVA帮助你摆脱它.https://github.com/avajs/ava Jasmine一个用于浏览器与Node.js开

WEB前端常用的测试工具

一.QUnit 前端测试工具 QUnit是一个强大的JavaScript单元测试框架,该框架是由jQuery团队的成员所开发,并且是jQuery的官方测试套件.Qunit是Jquery的单元测试框架,并且被广泛使用在各个项目中. 为了使用Qunit,你仅仅需要去包含2个Qunit文件在你的Html页面.Qunit 包含了qunit.js 作为运行器和测试框架,和qunit.css 文件,座位测试套件页面显示测试结果的样式. 二.Selenium 前端测试工具 Selenium 是ThoughtW

JavaScript 测试及校验工具

JavaScript 是一款强大的广泛运用于现代Web站点及应用的脚本语言.作为一个技艺精湛的 Web 开发者,掌握JavaScript可以增强用户的使用体验,提供交互及富客户端等功能. 尽管JavaScript 的语法非常简单,但对于写程序而言仍然是困难重重,就是因为它的运行环境:基于Web浏览器. 以下您可以看到收集的8个实用的 JavaScript 测试及效验工具,它们都可以在不同环境下进行单元测试及校验测试您的脚本. JSLintJSLint是基于Web的验证JavaScript错误代码

JavaScript开发工具大全

译者按: 最全的JavaScript开发工具列表,总有一款适合你! 原文: THE ULTIMATE LIST OF JAVASCRIPT TOOLS 译者: Fundebug 为了保证可读性,本文采用意译而非直译.另外,本文版权归原作者所有,翻译仅用于学习. 简介 2017年1月,Stack Overflow年度开发者调研一共访问了64000个程序员,发现JavaScript已经连续5年成为最流行的编程语言. 这篇博客将介绍一些常用的JavaScript开发工具: 构建&自动化 IDE&

12款很棒的浏览器兼容性测试工具推荐

对于前端开发工程师来说,确保代码在各种主流浏览器的各个版本中都能正常工作是件很费时的事情,幸运的是,有很多优秀的工具可以帮助测试浏览器的兼容性,让我们一起看看这些很棒的工具. Spoon Browser Sandbox 点击你需要测试的浏览器环境,安装插件就可以进行测试了.帮助你测试网页在Safari.Chrome.Firefox和Opera浏览器中是否正常,IE以前也有的,网站上说应微软的要求去掉了. Superpreview 这是为微软自己发布的跨浏览器测试工具,您可以同时查看您的网页在多个

JS-010-覆盖率测试工具 JSCoverage 初识

后续更新,敬请期待...非常感谢! 至此, JS-010-覆盖率测试工具 JSCoverage 初识 顺利完结,希望此文能够给初学 JavaScript 的您一份参考. 最后,非常感谢亲的驻足,希望此文能对亲有所帮助.热烈欢迎亲一起探讨,共同进步.非常感谢! ^_^

转:渗透测试工具实战技巧合集

转自:http://www.freebuf.com/sectool/105524.html   选择性的删了一部分内容 最好的 NMAP 扫描策略 # 适用所有大小网络最好的 nmap 扫描策略 # 主机发现,生成存活主机列表 $ nmap -sn -T4 -oG Discovery.gnmap 192.168.56.0/24 $ grep "Status: Up" Discovery.gnmap | cut -f 2 -d ' ' > LiveHosts.txt # 端口发现,

Python渗透测试工具合集

Python渗透测试工具合集 如果你热爱漏洞研究.逆向工程或者渗透测试,我强烈推荐你使用 Python 作为编程语言.它包含大量实用的库和工具, 本文会列举其中部分精华. 网络 Scapy, Scapy3k: 发送,嗅探,分析和伪造网络数据包.可用作交互式包处理程序或单独作为一个库. pypcap, Pcapy, pylibpcap: 几个不同 libpcap 捆绑的python库 libdnet: 低级网络路由,包括端口查看和以太网帧的转发 dpkt: 快速,轻量数据包创建和分析,面向基本的