关于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风格的测试;



本文转自 念槐聚 博客园博客,原文链接:http://www.cnblogs.com/haochuang/p/5714745.html,如需转载请自行联系原作者

相关文章
|
29天前
|
数据采集 人工智能 自然语言处理
Midscene.js:AI 驱动的 UI 自动化测试框架,支持自然语言交互,生成可视化报告
Midscene.js 是一款基于 AI 技术的 UI 自动化测试框架,通过自然语言交互简化测试流程,支持动作执行、数据查询和页面断言,提供可视化报告,适用于多种应用场景。
271 1
Midscene.js:AI 驱动的 UI 自动化测试框架,支持自然语言交互,生成可视化报告
|
4月前
|
Web App开发 JavaScript 前端开发
添加浮动按钮点击滚动到网页底部的纯JavaScript演示代码 IE9、11,Maxthon 1.6.7,Firefox30、31,360极速浏览器7.5.3.308下测试正常
添加浮动按钮点击滚动到网页底部的纯JavaScript演示代码 IE9、11,Maxthon 1.6.7,Firefox30、31,360极速浏览器7.5.3.308下测试正常
|
2月前
|
机器学习/深度学习 自然语言处理 前端开发
前端神经网络入门:Brain.js - 详细介绍和对比不同的实现 - CNN、RNN、DNN、FFNN -无需准备环境打开浏览器即可测试运行-支持WebGPU加速
本文介绍了如何使用 JavaScript 神经网络库 **Brain.js** 实现不同类型的神经网络,包括前馈神经网络(FFNN)、深度神经网络(DNN)和循环神经网络(RNN)。通过简单的示例和代码,帮助前端开发者快速入门并理解神经网络的基本概念。文章还对比了各类神经网络的特点和适用场景,并简要介绍了卷积神经网络(CNN)的替代方案。
407 1
|
8月前
|
Web App开发 JavaScript 前端开发
《手把手教你》系列技巧篇(三十九)-java+ selenium自动化测试-JavaScript的调用执行-上篇(详解教程)
【5月更文挑战第3天】本文介绍了如何在Web自动化测试中使用JavaScript执行器(JavascriptExecutor)来完成Selenium API无法处理的任务。首先,需要将WebDriver转换为JavascriptExecutor对象,然后通过executeScript方法执行JavaScript代码。示例用法包括设置JS代码字符串并调用executeScript。文章提供了两个实战场景:一是当时间插件限制输入时,用JS去除元素的readonly属性;二是处理需滚动才能显示的元素,利用JS滚动页面。还给出了一个滚动到底部的代码示例,并提供了详细步骤和解释。
121 10
|
3月前
|
人工智能 监控 JavaScript
模拟依赖关系和 AI 是Vue.js测试的下一个前沿领域
模拟依赖关系和 AI 是Vue.js测试的下一个前沿领域
42 1
|
3月前
|
JavaScript 前端开发
JavaScript - 测试 Prototype
JavaScript - 测试 Prototype
21 0
|
3月前
|
JavaScript 前端开发
JavaScript - 测试 jQuery
JavaScript - 测试 jQuery
28 0
|
5月前
|
Web App开发 应用服务中间件 定位技术
three.js:三维模型加载量测试
three.js:三维模型加载量测试
236 4
|
5月前
|
JavaScript 前端开发 测试技术
Vue.js开发者必看!Vue Test Utils携手端到端测试,打造无懈可击的应用体验,引领前端测试新风尚!
【8月更文挑战第30天】随着Vue.js的普及,构建可靠的Vue应用至关重要。测试不仅能确保应用质量,还能提升开发效率。Vue Test Utils作为官方测试库,方便进行单元测试,而结合端到端(E2E)测试,则能构建全面的测试体系,保障应用稳定性。本文将带你深入了解如何使用Vue Test Utils进行单元测试,通过具体示例展示如何测试组件行为;并通过Cypress进行E2E测试,确保整个应用流程的正确性。无论是单元测试还是E2E测试,都能显著提高Vue应用的质量,让你更加自信地交付高质量的应用。
98 0
|
5月前
|
JavaScript 前端开发 应用服务中间件
【qkl】JavaScript连接web3钱包,实现测试网络中的 Sepolia ETH余额查询、转账功能
【区块链】JavaScript连接web3钱包,实现测试网络中的 Sepolia ETH余额查询、转账功能
170 0