Home Web Front-end JS Tutorial JavaScript unit testing ABC_javascript tips

JavaScript unit testing ABC_javascript tips

May 16, 2016 pm 05:54 PM

Foreword
Currently, unit testing is receiving more and more attention from developers in software development. It can improve the efficiency of software development and ensure the quality of development. In the past, unit testing was often seen in server-side development, but as the division of labor in the field of Web programming gradually becomes clearer, relevant unit testing can also be carried out in the field of front-end Javascript development to ensure the quality of front-end development.
In server-side unit testing, there are various testing frameworks. There are also some excellent frameworks in JavaScript. But in this article, we will implement a simple unit testing framework step by step. .
JS unit testing has many aspects, the most common ones are method function checking and browser compatibility checking. This article mainly talks about the first type.

The JS code examined in this article is a JS date formatting method I wrote before. The original text is here (javascript date formatting function, similar to the usage in C#). The code is as follows:

Copy code The code is as follows:

Date.prototype.toString=function(format){
var time ={};
time.Year=this.getFullYear();
time.TYear=("" time.Year).substr(2);
time.Month=this.getMonth() 1 ;
time.TMonth=time.Month<10?"0" time.Month:time.Month;
time.Day=this.getDate();
time.TDay=time.Day<10 ?"0" time.Day:time.Day;
time.Hour=this.getHours();
time.THour=time.Hour<10?"0" time.Hour:time.Hour;
time.hour=time.Hour<13?time.Hour:time.Hour-12;
time.Thour=time.hour<10?"0" time.hour:time.hour;
time .Minute=this.getMinutes();
time.TMinute=time.Minute<10?"0" time.Minute:time.Minute;
time.Second=this.getSeconds();
time .TSecond=time.Second<10?"0" time.Second:time.Second;
time.Millisecond=this.getMilliseconds();
var oNumber=time.Millisecond/1000;
if( format!=undefined && format.replace(/s/g,"").length>0){
format=format
.replace(/yyyy/ig,time.Year)
.replace( /yyy/ig,time.Year)
.replace(/yy/ig,time.TYear)
.replace(/y/ig,time.TYear)
.replace(/MM/g, time.TMonth)
.replace(/M/g,time.Month)
.replace(/dd/ig,time.TDay)
.replace(/d/ig,time.Day)
.replace(/HH/g,time.THour)
.replace(/H/g,time.Hour)
.replace(/hh/g,time.Thour)
.replace( /h/g,time.hour)
.replace(/mm/g,time.TMinute)
.replace(/m/g,time.Minute)
.replace(/ss/ig, time.TSecond)
.replace(/s/ig,time.Second)
.replace(/fff/ig,time.Millisecond)
.replace(/ff/ig,oNumber.toFixed(2 )*100)
.replace(/f/ig,oNumber.toFixed(1)*10);
}
else{
format=time.Year "-" time.Month "- " time.Day " " time.Hour ":" time.Minute ":" time.Second;
}
return format;
}

This code currently does not exist A serious bug was found. For testing in this article, we changed .replace(/MM/g,time.TMonth) to .replace(/MM/g,time.Month). This error is useless when the month is less than 10. Two digits represent the month.
There is a saying now that good designs are refactored. It is the same in this article. Let’s start with the simplest one.
First version: Use the original alert
As the first version, we are very lazy and directly use alert to check. The complete code is as follows:
Copy Code The code is as follows:




Demo







运行后会弹出 2012 和 4 ,观察结果我们知道 date.toString("MM")方法是有问题的。
  这种方式很不方便,最大的问题是它只弹出了结果,并没有给出正确或错误的信息,除非对代码非常熟悉,否则很难知道弹出的结果是正是误,下面,我们写一个断言(assert)方法来进行测试,明确给出是正是误的信息。
第二版:用assert进行检查
  断言是表达程序设计人员对于系统应该达到状态的一种预期,比如有一个方法用于把两个数字加起来,对于3 2,我们预期这个方法返回的结果是5,如果确实返回5那么就通过,否则给出错误提示。
  断言是单元测试的核心,在各种单元测试的框架中都提供了断言功能,这里我们写一个简单的断言(assert)方法:
复制代码 代码如下:

function assert(message,result){
if(!result){
throw new Error(message);
}
return true;
}

这个方法接受两个参数,第一个是错误后的提示信息,第二个是断言结果
  用断言测试代码如下:
复制代码 代码如下:

var date=new Date(2012,3,9);
try{
assert("yyyy should return full year",date.toString("yyyy")==="2012");
}catch(e){
alert("Test failed:" e.message);
}
try{
assert("MM should return full month",date.toString("MM")==="04");
}
catch(e){
alert("Test failed:" e.message);
}

  运行后会弹出如下窗口:

第三版:进行批量测试

  在第二版中,assert方法可以给出明确的结果,但如果想进行一系列的测试,每个测试都要进行异常捕获,还是不够方便。另外,在一般的测试框架中都可以给出成功的个数,失败的个数,及失败的错误信息。

  为了可以方便在看到测试结果,这里我们把结果用有颜色的文字显示的页面上,所以这里要写一个小的输出方法PrintMessage:
复制代码 代码如下:

function PrintMessage(text,color){
var div=document.createElement("div");
div.innerHTML=text;
div.style.color=color;
document.body.appendChild(div);
delete div;
}

Next, we will write a TestCase method similar to jsTestDriver to perform batch testing:
Copy code The code is as follows:

function testCase(name,tests){
var successCount= 0;
var testCount=0;
for(var test in tests){
testCount ;
try{
tests[test]();
PrintMessage(test " success" ,"#080");
successCount ;
}
catch(e){
PrintMessage(test " failed:" e.message,"#800");
}
}
PrintMessage("Test result: " testCount " tests," successCount " success, " (testCount-successCount) " failures","#800");
}

Test code:
Copy code The code is as follows:

var date=new Date(2012,3 ,9);
testCase("date toString test",{
yyyy:function(){
assert("yyyy should return 2012",date.toString("yyyy")==="2012 ");
},
MM:function(){
assert("MM should return 04",date.toString("MM")==="04");
},
dd:function(){
assert("dd should return 09",date.toString("dd")==="09");
}
});

The result is:

This way we can see at a glance which one is wrong. But is this perfect? ​​We can see that in the last test, var date=new Date(2012,3,9) is defined outside testCase, and date is shared in the entire testCase test code. Because of the various The date value is not modified in the method, so there is no problem. If the date value is modified in a test method, the test results will be inaccurate, so many test frameworks provide setUp and tearDown methods. , used to provide and destroy test data uniformly. Next, we will add the setUp and tearDown methods to our testCase.
Version 4: Batch testing that provides test data uniformly

First we add the setUp and tearDown methods:
Copy code The code is as follows:

testCase("date toString",{
setUp:function(){
this.date=new Date(2012,3,9);
},
tearDown:function(){
delete this.date;
},
yyyy:function(){
assert("yyyy should return 2012",this. date.toString("yyyy")==="2012");
},
MM:function(){
assert("MM should return 04",this.date.toString("MM ")==="04");
},
dd:function(){
assert("dd should return 09",this.date.toString("dd")===" 09");
}
});

Since the setUp and tearDown methods do not participate in the test, we need to modify the testCase code:
Copy code The code is as follows:

function testCase(name,tests){
var successCount=0;
var testCount=0 ;
var hasSetUp=typeof tests.setUp == "function";
var hasTearDown=typeof tests.tearDown == "function";
for(var test in tests){
if(test ==="setUp"||test==="tearDown"){
continue;
}
testCount;
try{
if(hasSetUp){
tests.setUp ();
}
tests[test]();
PrintMessage(test " success","#080");

if(hasTearDown){
tests.tearDown ();
}

successCount ;
}
catch(e){
PrintMessage(test " failed:" e.message,"#800");
}
}
PrintMessage("Test result: " testCount " tests," successCount " success, " (testCount-successCount) " failures","#800");
}

The result after running is the same as the third version.
Summary and reference articles

As mentioned above, good design is the result of continuous reconstruction. Is the fourth version above perfect? ​​It is far from it. Here is just an example. If you need knowledge in this area, I can write about the use of each testing framework later.

This article is just an entry-level example of JS unit testing. It allows beginners to have a preliminary concept of JS unit testing. It is an introduction to the topic. Experts are welcome to add their suggestions.

This article refers to the first chapter of the book "Test-Driven JavaScript Development" (I think it is pretty good, I recommend it). The test case in the book is also a time function, but it is more complicated to write and is not suitable for beginners. Too easy to understand.
Author: Artwl
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins 10 jQuery Fun and Games Plugins Mar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header Background jQuery Parallax Tutorial - Animated Header Background Mar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

Load Box Content Dynamically using AJAX Load Box Content Dynamically using AJAX Mar 06, 2025 am 01:07 AM

This tutorial demonstrates creating dynamic page boxes loaded via AJAX, enabling instant refresh without full page reloads. It leverages jQuery and JavaScript. Think of it as a custom Facebook-style content box loader. Key Concepts: AJAX and jQuery

How to Write a Cookie-less Session Library for JavaScript How to Write a Cookie-less Session Library for JavaScript Mar 06, 2025 am 01:18 AM

This JavaScript library leverages the window.name property to manage session data without relying on cookies. It offers a robust solution for storing and retrieving session variables across browsers. The library provides three core methods: Session

See all articles