SlideShare a Scribd company logo
李亚飞 louie/185421
1.Qunit

2.Jasmine

3.YUITest
Jörn Zaefferer : QUnit是一个JavaScript
单元测试框架,主要用于在浏览器中运行单
元测试。虽然这个项目从属于jQuery,但却
不依赖于jQuery,也不依赖于浏览器DOM。
因此你也可以在node.js或Rhino上使用。
QUnit很容易学习,你只需在html页面中包
含两个文件,不需要安装或者构建任何其他
东西。最短的测试集只需要一个11行的html
文件。

特点:
1.使用方便,界面美观
2.支持异步
3.手工加载
4.对html文件有约束
4.适合开发调试阶段使用
Davis Frank: Jasmine是一个 JavaScript
测试框架,目的是将BDD风格引入
JavaScript测试之中。至于区别嘛,我们的
目标是BDD(相比标准的TDD),因此我们尽
力帮助开发人员编写比一般xUnit框架表达
性更强,组织更好的代码。此外我们还力图
减少依赖,这样你可以在node.js上使用
Jasmine,也可以在浏览器或移动程序中使
用。

特点:
1.语法简洁,describe ,it
2.Browsers,servers,phones,etc
3.支持自定义Matchers
4.beforeEach()、afterEach()、
Single-spec After functions
5.spies,mock
6.异步,runs(),waits(),waitsFor()
YUI Test features:
Rapid creation of test cases through simple syntax.
Advanced failure detection for methods that throw errors.
Grouping of related test cases using test suites.
Mock objects for writing tests without external dependencies.
Asynchronous tests for testing events and Ajax communication.
DOM Event simulation in all A-grade browsers (through Event).
引入测试框架



 YUITest Standalone Library
 <script src="http://192.168.194.159/test/yuitest/yuitest.js"></script>




 YUI Test for YUI 3.x
 <script src="http://192.168.194.159/test/yui/build/yui/yui.js"></script>

 // Create a new YUI instance and populate it with the required modules.
 YUI().use('test', function (Y) {
     // Test is available and ready for use. Add implementation
     // code here.
 });
Using Test Cases

YUITest Standalone Library
var testCase = new YUITest.TestCase({
    name: "TestCase Name",
    //traditional test names
    testSomething : function () {
       //...
    },
    testSomethingElse : function () {
       //...
    }
});

var testCase = new YUITest.TestCase({
    name: "TestCase Name",
    //friendly test names
    "Something should happen here" : function () {
       //...
    },
    "Something else should happen here" : function () {
       //...
    }
});
Using Test Cases

YUI Test for YUI 3.x
var testCase = new Y.Test.Case({
    name: "TestCase Name",
    //traditional test names
    testSomething : function () {
       //...
    },
    testSomethingElse : function () {
       //...
    }
});

var testCase = new Y.Test.Case({
    name: "TestCase Name",
    //friendly test names
    "Something should happen here" : function () {
       //...
    },
    "Something else should happen here" : function () {
       //...
    }
});
setUp() and tearDown()

   var testCase = new YUITest.TestCase({
       name: "TestCase Name",
       //---------------------------------------------
       // Setup and tear down
       //---------------------------------------------
       setUp : function () {
          this.data = { name : "Nicholas", age : 28 };
       },
       tearDown : function () {
          delete this.data;
       },
       //---------------------------------------------
       // Tests
       //---------------------------------------------
       testName: function () {
          YUITest.Assert.areEqual("Nicholas", this.data.name, "Name should be 'Nicholas'");
       },
       testAge: function () {
          YUITest.Assert.areEqual(28, this.data.age, "Age should be 28");
       }
   });
init() and destroy()

    var testCase = new YUITest.TestCase({
        name: "TestCase Name",
        //---------------------------------------------
        // init and destroy
        //---------------------------------------------
        init : function () {
           this.data = { name : "Nicholas", age : 28 };
        },
        destroy : function () {
           delete this.data;
        },
        //---------------------------------------------
        // Tests
        //---------------------------------------------
        testName: function () {
           YUITest.Assert.areEqual("Nicholas", this.data.name, "Name should be 'Nicholas'");
        },
        testAge: function () {
           YUITest.Assert.areEqual(28, this.data.age, "Age should be 28");
        }
    });
Ignoring Tests

    var testCase = new YUITest.TestCase({
        name: "TestCase Name",
        //---------------------------------------------
        // Special instructions
        //---------------------------------------------
        _should: {
           ignore: {
             testName: true //ignore this test
           }
        },
    //---------------------------------------------
        // Tests
        //---------------------------------------------
        testName: function () {
           YUITest.Assert.areEqual("Nicholas", this.data.name, "Name should be 'Nicholas'");
        },
        testAge: function () {
           YUITest.Assert.areEqual(28, this.data.age, "Age should be 28");
        }
    });
Intentional Errors

    testGenericError : function() {
       YUITest.Assert.throwsError(Error, function() {
           throw new Error("Generic error");
       });
    },
    testStringError : function() {
       YUITest.Assert.throwsError("I'm a specific error message.", function() {
           throw new Error("I'm a specific error message.");
       });
    },
    testObjectError : function() {
       YUITest.Assert.throwsError(new TypeError("Number expected."), function() {
           throw new TypeError("Number expected.");
       });
    },
Assertions



 Equality Assertions      Sameness Assertions    Forced Failures
 areEqual()               areNotSame()           fail()
 areNotEqual()            areSame()



      Special Value Assertions        Data Type Assertions
      isFalse()                       isArray()
      isTrue()                        isBoolean()
      isNaN()                         isFunction()
      isNotNaN()                      isNumber()
      isNull()                        isObject()
      isNotNull()                     isString()
      isUndefined()                   isTypeOf()
      isNotUndefined()
ArrayAssert


       contains()
       containsItems()
       containsMatch()
       doesNotContain()
       doesNotContainItems()
       doesNotContainMatch()
       indexOf()
       isEmpty()
       isNotEmpty()
       itemsAreEqual()
       itemsAreEquivalent()
       itemsAreSame()
       lastIndexOf()
DateAssert


       datesAreEqual()
       timesAreEqual()
ObjectAssert


       hasKey()
       hasKeys()
       ownsKey()
       ownsKeys()
       ownsNoKeys()
       areEqual()
       inheritsKey()
       inheritsKeys()
       ownsOrInheritsKey()
       ownsOrInheritsKeys()
Mock Objects
//code being tested
function logToServer(message, xhr){
    xhr.open("get", "/log.php?msg=" + encodeURIComponent(message), true);
    xhr.send(null);
}
//test case for testing the above function
var testCase = new YUITest.TestCase({
    name: "logToServer Tests",
    testPassingDataToXhr : function () {
      var mockXhr = YUITest.Mock();
      //I expect the open() method to be called with the given arguments
      YUITest.Mock.expect(mockXhr, {
          method: "open",
          args: ["get", "/log.php?msg=hi", true]
      });
      //I expect the send() method to be called with the given arguments
      YUITest.Mock.expect(mockXhr, {
          method: "send",
          args: [null]
      });
      //now call the function
      logToServer("hi", mockXhr);
      //verify the expectations were met
      YUITest.Mock.verify(mockXhr);
    }
});
Special Argument Values


YUITest.Mock.Value.Any - any value is valid regardless of type.
YUITest.Mock.Value.String - any string value is valid.
YUITest.Mock.Value.Number - any number value is valid.
YUITest.Mock.Value.Boolean - any Boolean value is valid.
YUITest.Mock.Value.Object - any non-null object value is valid.
YUITest.Mock.Value.Function - any function value is valid.



YUITest.Mock.expect(mockXhr, {
    method: "open",
    args: [YUITest.Mock.Value.String, "/log.php?msg=hi“, YUITest.Mock.Value.Boolean]
});
Property Expectations

var testCase = new YUITest.TestCase({
  name : "TestCase Name",

      testMock : function() {
        var mockMyObject = YUITest.Mock();
        YUITest.Mock.expect(mockMyObject,{
            method: "add",
            args: [1,2],
            returns: 3,
            property: "status",
            value: 404
        });
        var result = mockMyObject.add(1,2);
        mockMyObject.status = 100;
        Assert.areEqual(3,result,"1 + 2 = 3");
        YUITest.Mock.verify(mockMyObject);
      }
});
Asynchronous Tests

var testCase = new YUITest.TestCase({
  name: "TestCase Name",

       setUp : function () {
         this.data = { name : "Nicholas", age : 29 };
      },
      tearDown : function () {
         delete this.data;
      },
      testAsync: function () {
         YUITest.Assert.areEqual("Nicholas", this.data.name, "Name should be 'Nicholas'");

          //wait 1000 milliseconds and then run this function
          this.wait(function(){
            YUITest.Assert.areEqual(29, this.data.age, "Age should be 29");

          }, 1000);
      }
});
Asynchronous Tests
var testCase = new YUITest.TestCase({
    name: "TestCase Name",
    testAnimation : function (){
      //animate width to 400px
      var myAnim = new Y.Anim({
         node: '#testDiv',
         to: {width: 400},
         duration: 3});
      var test = this;
      //assign oncomplete handler
      myAnim.on("end", function(){
         //tell the TestRunner to resume
         test.resume(function(){
            YUITest.Assert.areEqual(myAnim.get("node").get("offsetWidth"), 400, "Width of the
DIV should be 400.");
         });
      });
      //start the animation
      myAnim.run();
      //wait until something happens
      this.wait(3000);
    }
});
Test Suites
//create the test suite
var suite = new YUITest.TestSuite("TestSuite Name");
//add test cases
suite.add(new YUITest.TestCase({
   //...
}));
suite.add(new YUITest.TestCase({
   //...
}));
//add the second suite to the first
suite.add(anotherSuite);
//create a test suite
var suite = new YUITest.TestSuite({
  name : "TestSuite Name",

      setUp : function () {
         //test-suite-level setup
      },
      tearDown: function () {
         //test-suite-level teardown
      }
});
Context Data
var testSuite = new YUITest.TestSuite({
    name: "Test Suite Name",
    setUp: function(data){
       data.topLevel = 1;}
});
testSuite.add(new YUITest.TestCase({
    name: "First Test Case",
    init: function(data){
       data.foo = "bar";},
    testValueOfFoo : function (data) {
       YUITest.Assert.areEqual("bar", data.foo); //from init
    },
    testValueOfTopLevel: function(data){
       YUITest.Assert.areEqual(1, data.topLevel); //from test suite
    }
});
testSuite.add(new YUITest.TestCase({
    name: "Second Test Case",
    testValueOfFoo : function (data) {
       YUITest.Assert.areEqual("bar", data.foo); //from init in First Test Case
    },
    testValueOfTopLevel: function(data){
       YUITest.Assert.areEqual(1, data.topLevel); //from test suite
    }
});
Running Tests



//add the test cases and suites
YUITest.TestRunner.add(testCase);
YUITest.TestRunner.add(testSuite);

//run all tests
YUITest.TestRunner.run();

YUITest.TestRunner.clear();
TestRunner Events

Test-Level Events
YUITest.TestRunner.TEST_PASS_EVENT - occurs when the test passes.
YUITest.TestRunner.TEST_FAIL_EVENT - occurs when the test fails.
YUITest.TestRunner.TEST_IGNORE_EVENT - occurs when a test is ignored.


For each of these events, the event data object has three properties:
type - indicates the type of event that occurred.
testCase - the test case that is currently being run.
testName - the name of the test that was just executed or ignored.
TestRunner Events

TestCase-Level Events
YUITest.TestRunner.TEST_CASE_BEGIN_EVENT
occurs when the test case is next to be executed but before the first test
is run.
YUITest.TestRunner.TEST_CASE_COMPLETE_EVENT
occurs when all tests in the test case have been executed or ignored.


For these two events, the event data object has three properties:
type - indicates the type of event that occurred.
testCase - the test case that is currently being run.
TestRunner Events

TestSuite-Level Events
YUITest.TestRunner.TEST_SUITE_BEGIN_EVENT
occurs when the test suite is next to be executed but before the first
test is run.
YUITest.TestRunner.TEST_SUITE_COMPLETE_EVENT
occurs when all tests in all test cases in the test suite have been
executed or ignored.


For these two events, the event data object has three properties:
type - indicates the type of event that occurred.
testSuite - the test suite that is currently being run.
TestRunner Events

TestRunner-Level Events
YUITest.TestRunner.BEGIN_EVENT
occurs when testing is about to begin but before any tests are run.
YUITest.TestRunner.COMPLETE_EVENT
occurs when all tests in all test cases and test suites have been executed or ignored.



Subscribing to Events
function handleTestFail(data){
  alert("Test named '" + data.testName + "' failed with message: '" +
data.error.message + "'.");
}

var TestRunner = YUITest.TestRunner;
TestRunner.subscribe(TestRunner.TEST_FAIL_EVENT, handleTestFail);
TestRunner.run();
Viewing Results

YUI({ logInclude: { TestRunner: true } }).use("console", function(Y){
  //tests go here

      //initialize the console
      var yconsole = new Y.Console({
         newestOnTop: false
      });
      yconsole.render('#log');
      //run the tests
      YUITest.TestRunner.run();
});
Viewing Results

YUI({ useBrowserConsole: true }).use("test", function(Y){

      //tests go here

      Y.Test.Runner.run();

});
Viewing Results


YUI({ useBrowserConsole: true }).use("test", function(Y){
  //tests go here

      //get object of results
      var resultsObject = YUITest.TestRunner.getResult();

      //get XML results
      var resultsXML = YUITest.TestRunner.getResult(YUITest.TestFormat.XML);
});



YUITest.TestFormat.XML - YUI Test XML (default)
YUITest.TestFormat.JSON - JSON
YUITest.TestFormat.JUnitXML - JUnit XML
YUITest.TestFormat.TAP - TAP
Code Coverage Data




YUITest.TestRunner.getCoverage()



YUITest.CoverageFormat.JSON - JSON
YUITest.CoverageFormat.XdebugJSON - JSON formatted Xdebug
Test Reporting


var reporter = new
YUITest.Reporter("http://www.yourserver.com/path/to/target",
YUITest.TestFormat.JSON);
reporter.report(results);

results - the serialized results object.
useragent - the user-agent string of the browser.
timestamp - the date and time that the report was sent.


reporter.addField("color", "blue");
reporter.addField("message", "Hello world!");
Yeti: YUI’s Easy Testing Interface
Yeti is a command-line tool for launching JavaScript unit tests in a
browser and reporting the results without leaving your terminal. Yeti is
designed to work with existing unmodified YUI-based tests.

Yeti is designed to help you run tests before you commit. It
compliments existing CI tools like Selenium and Hudson which run tests
post-commit. Yeti is not a replacement for those tools.
More Info




http://docs.jquery.com/Qunit
http://pivotal.github.com/jasmine/
http://developer.yahoo.com/yui/
http://yuilibrary.com/projects/yuitest
http://yuilibrary.com/yui/docs/test/
http://yuilibrary.com/theater/
http://yuilibrary.com/projects/yeti/
http://192.168.194.159/test/slide/yeti.html

More Related Content

What's hot

Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicNew Relic
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
Simon Su
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 
Mobile Fest 2018. Александр Корин. Болеутоляющее
Mobile Fest 2018. Александр Корин. БолеутоляющееMobile Fest 2018. Александр Корин. Болеутоляющее
Mobile Fest 2018. Александр Корин. Болеутоляющее
MobileFest2018
 
The Ring programming language version 1.5.3 book - Part 78 of 184
The Ring programming language version 1.5.3 book - Part 78 of 184The Ring programming language version 1.5.3 book - Part 78 of 184
The Ring programming language version 1.5.3 book - Part 78 of 184
Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202
Mahmoud Samir Fayed
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
matuura_core
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Kiyotaka Oku
 
The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 88 of 184
The Ring programming language version 1.5.3 book - Part 88 of 184The Ring programming language version 1.5.3 book - Part 88 of 184
The Ring programming language version 1.5.3 book - Part 88 of 184
Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 51 of 88
The Ring programming language version 1.3 book - Part 51 of 88The Ring programming language version 1.3 book - Part 51 of 88
The Ring programming language version 1.3 book - Part 51 of 88
Mahmoud Samir Fayed
 
Towards Reusable Components With Aspects [ICSE 2008]
Towards Reusable Components With Aspects [ICSE 2008]Towards Reusable Components With Aspects [ICSE 2008]
Towards Reusable Components With Aspects [ICSE 2008]
Kevin Hoffman
 
Wwe Management System
Wwe Management SystemWwe Management System
Wwe Management System
NeerajMudgal1
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
Sébastien Prunier
 
C++ 11 usage experience
C++ 11 usage experienceC++ 11 usage experience
C++ 11 usage experience
GlobalLogic Ukraine
 
The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210
Mahmoud Samir Fayed
 
Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkKaniska Mandal
 
The Ring programming language version 1.7 book - Part 73 of 196
The Ring programming language version 1.7 book - Part 73 of 196The Ring programming language version 1.7 book - Part 73 of 196
The Ring programming language version 1.7 book - Part 73 of 196
Mahmoud Samir Fayed
 

What's hot (20)

Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Mobile Fest 2018. Александр Корин. Болеутоляющее
Mobile Fest 2018. Александр Корин. БолеутоляющееMobile Fest 2018. Александр Корин. Болеутоляющее
Mobile Fest 2018. Александр Корин. Болеутоляющее
 
The Ring programming language version 1.5.3 book - Part 78 of 184
The Ring programming language version 1.5.3 book - Part 78 of 184The Ring programming language version 1.5.3 book - Part 78 of 184
The Ring programming language version 1.5.3 book - Part 78 of 184
 
The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
Spock and Geb
Spock and GebSpock and Geb
Spock and Geb
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
 
Spock and Geb in Action
Spock and Geb in ActionSpock and Geb in Action
Spock and Geb in Action
 
The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196
 
The Ring programming language version 1.5.3 book - Part 88 of 184
The Ring programming language version 1.5.3 book - Part 88 of 184The Ring programming language version 1.5.3 book - Part 88 of 184
The Ring programming language version 1.5.3 book - Part 88 of 184
 
The Ring programming language version 1.3 book - Part 51 of 88
The Ring programming language version 1.3 book - Part 51 of 88The Ring programming language version 1.3 book - Part 51 of 88
The Ring programming language version 1.3 book - Part 51 of 88
 
Towards Reusable Components With Aspects [ICSE 2008]
Towards Reusable Components With Aspects [ICSE 2008]Towards Reusable Components With Aspects [ICSE 2008]
Towards Reusable Components With Aspects [ICSE 2008]
 
Wwe Management System
Wwe Management SystemWwe Management System
Wwe Management System
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
C++ 11 usage experience
C++ 11 usage experienceC++ 11 usage experience
C++ 11 usage experience
 
The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210
 
Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD Framework
 
The Ring programming language version 1.7 book - Part 73 of 196
The Ring programming language version 1.7 book - Part 73 of 196The Ring programming language version 1.7 book - Part 73 of 196
The Ring programming language version 1.7 book - Part 73 of 196
 

Viewers also liked

29Oct14 - Productive Ageing - Dr Ros Altmann
29Oct14 - Productive Ageing - Dr Ros Altmann 29Oct14 - Productive Ageing - Dr Ros Altmann
29Oct14 - Productive Ageing - Dr Ros Altmann
ILC- UK
 
New week 5
New week 5New week 5
New week 5nglaze10
 
Poch dela rosa_how to use google call phone.ppt
Poch dela rosa_how to use google call phone.pptPoch dela rosa_how to use google call phone.ppt
Poch dela rosa_how to use google call phone.pptpocholo_dlr
 
Pecha kucha example
Pecha kucha examplePecha kucha example
Pecha kucha exampleBow83
 
Tema 1 i 2. el poder i control de l'electricitat
Tema 1 i 2. el poder i control de l'electricitatTema 1 i 2. el poder i control de l'electricitat
Tema 1 i 2. el poder i control de l'electricitatiolandams
 
13Mar14 - One Year On
13Mar14 - One Year On13Mar14 - One Year On
13Mar14 - One Year On
ILC- UK
 
1.6 notes 7th
1.6 notes 7th1.6 notes 7th
1.6 notes 7thnglaze10
 
Recent newsletter sample
Recent newsletter sampleRecent newsletter sample
Recent newsletter sample
Great Reach Communications
 
Incremental Wins Exponential Impact
Incremental Wins   Exponential ImpactIncremental Wins   Exponential Impact
Incremental Wins Exponential Impactburgessblc
 
Customizable marketing newsletters for printers and mailers
Customizable marketing newsletters for printers and mailersCustomizable marketing newsletters for printers and mailers
Customizable marketing newsletters for printers and mailers
Great Reach Communications
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
ben_norris124
 
Abstract for International Conference on Small Business
Abstract for International Conference on Small BusinessAbstract for International Conference on Small Business
Abstract for International Conference on Small Business
Jane Leonard
 
Parts of body
Parts of bodyParts of body
Parts of bodydianallan
 
12Jun14 - The UK Equity Bank
12Jun14 -  The UK Equity Bank12Jun14 -  The UK Equity Bank
12Jun14 - The UK Equity Bank
ILC- UK
 
U brand qr code primer™
U brand qr code primer™U brand qr code primer™
U brand qr code primer™
Great Reach Communications
 

Viewers also liked (20)

29Oct14 - Productive Ageing - Dr Ros Altmann
29Oct14 - Productive Ageing - Dr Ros Altmann 29Oct14 - Productive Ageing - Dr Ros Altmann
29Oct14 - Productive Ageing - Dr Ros Altmann
 
New week 5
New week 5New week 5
New week 5
 
Poch dela rosa_how to use google call phone.ppt
Poch dela rosa_how to use google call phone.pptPoch dela rosa_how to use google call phone.ppt
Poch dela rosa_how to use google call phone.ppt
 
Bretelle1
Bretelle1Bretelle1
Bretelle1
 
Pecha kucha example
Pecha kucha examplePecha kucha example
Pecha kucha example
 
Tema 1 i 2. el poder i control de l'electricitat
Tema 1 i 2. el poder i control de l'electricitatTema 1 i 2. el poder i control de l'electricitat
Tema 1 i 2. el poder i control de l'electricitat
 
8.2
8.28.2
8.2
 
13Mar14 - One Year On
13Mar14 - One Year On13Mar14 - One Year On
13Mar14 - One Year On
 
3.1 (8th)
3.1 (8th)3.1 (8th)
3.1 (8th)
 
1.6 notes 7th
1.6 notes 7th1.6 notes 7th
1.6 notes 7th
 
Recent newsletter sample
Recent newsletter sampleRecent newsletter sample
Recent newsletter sample
 
2.8 notes
2.8 notes2.8 notes
2.8 notes
 
Incremental Wins Exponential Impact
Incremental Wins   Exponential ImpactIncremental Wins   Exponential Impact
Incremental Wins Exponential Impact
 
Customizable marketing newsletters for printers and mailers
Customizable marketing newsletters for printers and mailersCustomizable marketing newsletters for printers and mailers
Customizable marketing newsletters for printers and mailers
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
Abstract for International Conference on Small Business
Abstract for International Conference on Small BusinessAbstract for International Conference on Small Business
Abstract for International Conference on Small Business
 
Parts of body
Parts of bodyParts of body
Parts of body
 
12Jun14 - The UK Equity Bank
12Jun14 -  The UK Equity Bank12Jun14 -  The UK Equity Bank
12Jun14 - The UK Equity Bank
 
canovaccio_app_final_crit
canovaccio_app_final_critcanovaccio_app_final_crit
canovaccio_app_final_crit
 
U brand qr code primer™
U brand qr code primer™U brand qr code primer™
U brand qr code primer™
 

Similar to Js 单元测试框架介绍

Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Js objects
Js objectsJs objects
Js objects
anubavam-techkt
 
JUnit Pioneer
JUnit PioneerJUnit Pioneer
JUnit Pioneer
Scott Leberknight
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
whitneyleman54422
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J ScriptRoman Agaev
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnitferca_sl
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
Tiago de Freitas Lima
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
David Rajah Selvaraj
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
liminescence
 
Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.js
Jay Harris
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
Bastian Feder
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
sooryasalini
 

Similar to Js 单元测试框架介绍 (20)

Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Js objects
Js objectsJs objects
Js objects
 
JUnit Pioneer
JUnit PioneerJUnit Pioneer
JUnit Pioneer
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J Script
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Java programs
Java programsJava programs
Java programs
 
Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.js
 
Unit testing with mock libs
Unit testing with mock libsUnit testing with mock libs
Unit testing with mock libs
 
JUnit
JUnitJUnit
JUnit
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
 

Recently uploaded

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 

Recently uploaded (20)

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 

Js 单元测试框架介绍

  • 3. Jörn Zaefferer : QUnit是一个JavaScript 单元测试框架,主要用于在浏览器中运行单 元测试。虽然这个项目从属于jQuery,但却 不依赖于jQuery,也不依赖于浏览器DOM。 因此你也可以在node.js或Rhino上使用。 QUnit很容易学习,你只需在html页面中包 含两个文件,不需要安装或者构建任何其他 东西。最短的测试集只需要一个11行的html 文件。 特点: 1.使用方便,界面美观 2.支持异步 3.手工加载 4.对html文件有约束 4.适合开发调试阶段使用
  • 4. Davis Frank: Jasmine是一个 JavaScript 测试框架,目的是将BDD风格引入 JavaScript测试之中。至于区别嘛,我们的 目标是BDD(相比标准的TDD),因此我们尽 力帮助开发人员编写比一般xUnit框架表达 性更强,组织更好的代码。此外我们还力图 减少依赖,这样你可以在node.js上使用 Jasmine,也可以在浏览器或移动程序中使 用。 特点: 1.语法简洁,describe ,it 2.Browsers,servers,phones,etc 3.支持自定义Matchers 4.beforeEach()、afterEach()、 Single-spec After functions 5.spies,mock 6.异步,runs(),waits(),waitsFor()
  • 5. YUI Test features: Rapid creation of test cases through simple syntax. Advanced failure detection for methods that throw errors. Grouping of related test cases using test suites. Mock objects for writing tests without external dependencies. Asynchronous tests for testing events and Ajax communication. DOM Event simulation in all A-grade browsers (through Event).
  • 6. 引入测试框架 YUITest Standalone Library <script src="http://192.168.194.159/test/yuitest/yuitest.js"></script> YUI Test for YUI 3.x <script src="http://192.168.194.159/test/yui/build/yui/yui.js"></script> // Create a new YUI instance and populate it with the required modules. YUI().use('test', function (Y) { // Test is available and ready for use. Add implementation // code here. });
  • 7. Using Test Cases YUITest Standalone Library var testCase = new YUITest.TestCase({ name: "TestCase Name", //traditional test names testSomething : function () { //... }, testSomethingElse : function () { //... } }); var testCase = new YUITest.TestCase({ name: "TestCase Name", //friendly test names "Something should happen here" : function () { //... }, "Something else should happen here" : function () { //... } });
  • 8. Using Test Cases YUI Test for YUI 3.x var testCase = new Y.Test.Case({ name: "TestCase Name", //traditional test names testSomething : function () { //... }, testSomethingElse : function () { //... } }); var testCase = new Y.Test.Case({ name: "TestCase Name", //friendly test names "Something should happen here" : function () { //... }, "Something else should happen here" : function () { //... } });
  • 9. setUp() and tearDown() var testCase = new YUITest.TestCase({ name: "TestCase Name", //--------------------------------------------- // Setup and tear down //--------------------------------------------- setUp : function () { this.data = { name : "Nicholas", age : 28 }; }, tearDown : function () { delete this.data; }, //--------------------------------------------- // Tests //--------------------------------------------- testName: function () { YUITest.Assert.areEqual("Nicholas", this.data.name, "Name should be 'Nicholas'"); }, testAge: function () { YUITest.Assert.areEqual(28, this.data.age, "Age should be 28"); } });
  • 10. init() and destroy() var testCase = new YUITest.TestCase({ name: "TestCase Name", //--------------------------------------------- // init and destroy //--------------------------------------------- init : function () { this.data = { name : "Nicholas", age : 28 }; }, destroy : function () { delete this.data; }, //--------------------------------------------- // Tests //--------------------------------------------- testName: function () { YUITest.Assert.areEqual("Nicholas", this.data.name, "Name should be 'Nicholas'"); }, testAge: function () { YUITest.Assert.areEqual(28, this.data.age, "Age should be 28"); } });
  • 11. Ignoring Tests var testCase = new YUITest.TestCase({ name: "TestCase Name", //--------------------------------------------- // Special instructions //--------------------------------------------- _should: { ignore: { testName: true //ignore this test } }, //--------------------------------------------- // Tests //--------------------------------------------- testName: function () { YUITest.Assert.areEqual("Nicholas", this.data.name, "Name should be 'Nicholas'"); }, testAge: function () { YUITest.Assert.areEqual(28, this.data.age, "Age should be 28"); } });
  • 12. Intentional Errors testGenericError : function() { YUITest.Assert.throwsError(Error, function() { throw new Error("Generic error"); }); }, testStringError : function() { YUITest.Assert.throwsError("I'm a specific error message.", function() { throw new Error("I'm a specific error message."); }); }, testObjectError : function() { YUITest.Assert.throwsError(new TypeError("Number expected."), function() { throw new TypeError("Number expected."); }); },
  • 13. Assertions Equality Assertions Sameness Assertions Forced Failures areEqual() areNotSame() fail() areNotEqual() areSame() Special Value Assertions Data Type Assertions isFalse() isArray() isTrue() isBoolean() isNaN() isFunction() isNotNaN() isNumber() isNull() isObject() isNotNull() isString() isUndefined() isTypeOf() isNotUndefined()
  • 14. ArrayAssert contains() containsItems() containsMatch() doesNotContain() doesNotContainItems() doesNotContainMatch() indexOf() isEmpty() isNotEmpty() itemsAreEqual() itemsAreEquivalent() itemsAreSame() lastIndexOf()
  • 15. DateAssert datesAreEqual() timesAreEqual()
  • 16. ObjectAssert hasKey() hasKeys() ownsKey() ownsKeys() ownsNoKeys() areEqual() inheritsKey() inheritsKeys() ownsOrInheritsKey() ownsOrInheritsKeys()
  • 17. Mock Objects //code being tested function logToServer(message, xhr){ xhr.open("get", "/log.php?msg=" + encodeURIComponent(message), true); xhr.send(null); } //test case for testing the above function var testCase = new YUITest.TestCase({ name: "logToServer Tests", testPassingDataToXhr : function () { var mockXhr = YUITest.Mock(); //I expect the open() method to be called with the given arguments YUITest.Mock.expect(mockXhr, { method: "open", args: ["get", "/log.php?msg=hi", true] }); //I expect the send() method to be called with the given arguments YUITest.Mock.expect(mockXhr, { method: "send", args: [null] }); //now call the function logToServer("hi", mockXhr); //verify the expectations were met YUITest.Mock.verify(mockXhr); } });
  • 18. Special Argument Values YUITest.Mock.Value.Any - any value is valid regardless of type. YUITest.Mock.Value.String - any string value is valid. YUITest.Mock.Value.Number - any number value is valid. YUITest.Mock.Value.Boolean - any Boolean value is valid. YUITest.Mock.Value.Object - any non-null object value is valid. YUITest.Mock.Value.Function - any function value is valid. YUITest.Mock.expect(mockXhr, { method: "open", args: [YUITest.Mock.Value.String, "/log.php?msg=hi“, YUITest.Mock.Value.Boolean] });
  • 19. Property Expectations var testCase = new YUITest.TestCase({ name : "TestCase Name", testMock : function() { var mockMyObject = YUITest.Mock(); YUITest.Mock.expect(mockMyObject,{ method: "add", args: [1,2], returns: 3, property: "status", value: 404 }); var result = mockMyObject.add(1,2); mockMyObject.status = 100; Assert.areEqual(3,result,"1 + 2 = 3"); YUITest.Mock.verify(mockMyObject); } });
  • 20. Asynchronous Tests var testCase = new YUITest.TestCase({ name: "TestCase Name", setUp : function () { this.data = { name : "Nicholas", age : 29 }; }, tearDown : function () { delete this.data; }, testAsync: function () { YUITest.Assert.areEqual("Nicholas", this.data.name, "Name should be 'Nicholas'"); //wait 1000 milliseconds and then run this function this.wait(function(){ YUITest.Assert.areEqual(29, this.data.age, "Age should be 29"); }, 1000); } });
  • 21. Asynchronous Tests var testCase = new YUITest.TestCase({ name: "TestCase Name", testAnimation : function (){ //animate width to 400px var myAnim = new Y.Anim({ node: '#testDiv', to: {width: 400}, duration: 3}); var test = this; //assign oncomplete handler myAnim.on("end", function(){ //tell the TestRunner to resume test.resume(function(){ YUITest.Assert.areEqual(myAnim.get("node").get("offsetWidth"), 400, "Width of the DIV should be 400."); }); }); //start the animation myAnim.run(); //wait until something happens this.wait(3000); } });
  • 22. Test Suites //create the test suite var suite = new YUITest.TestSuite("TestSuite Name"); //add test cases suite.add(new YUITest.TestCase({ //... })); suite.add(new YUITest.TestCase({ //... })); //add the second suite to the first suite.add(anotherSuite); //create a test suite var suite = new YUITest.TestSuite({ name : "TestSuite Name", setUp : function () { //test-suite-level setup }, tearDown: function () { //test-suite-level teardown } });
  • 23. Context Data var testSuite = new YUITest.TestSuite({ name: "Test Suite Name", setUp: function(data){ data.topLevel = 1;} }); testSuite.add(new YUITest.TestCase({ name: "First Test Case", init: function(data){ data.foo = "bar";}, testValueOfFoo : function (data) { YUITest.Assert.areEqual("bar", data.foo); //from init }, testValueOfTopLevel: function(data){ YUITest.Assert.areEqual(1, data.topLevel); //from test suite } }); testSuite.add(new YUITest.TestCase({ name: "Second Test Case", testValueOfFoo : function (data) { YUITest.Assert.areEqual("bar", data.foo); //from init in First Test Case }, testValueOfTopLevel: function(data){ YUITest.Assert.areEqual(1, data.topLevel); //from test suite } });
  • 24. Running Tests //add the test cases and suites YUITest.TestRunner.add(testCase); YUITest.TestRunner.add(testSuite); //run all tests YUITest.TestRunner.run(); YUITest.TestRunner.clear();
  • 25. TestRunner Events Test-Level Events YUITest.TestRunner.TEST_PASS_EVENT - occurs when the test passes. YUITest.TestRunner.TEST_FAIL_EVENT - occurs when the test fails. YUITest.TestRunner.TEST_IGNORE_EVENT - occurs when a test is ignored. For each of these events, the event data object has three properties: type - indicates the type of event that occurred. testCase - the test case that is currently being run. testName - the name of the test that was just executed or ignored.
  • 26. TestRunner Events TestCase-Level Events YUITest.TestRunner.TEST_CASE_BEGIN_EVENT occurs when the test case is next to be executed but before the first test is run. YUITest.TestRunner.TEST_CASE_COMPLETE_EVENT occurs when all tests in the test case have been executed or ignored. For these two events, the event data object has three properties: type - indicates the type of event that occurred. testCase - the test case that is currently being run.
  • 27. TestRunner Events TestSuite-Level Events YUITest.TestRunner.TEST_SUITE_BEGIN_EVENT occurs when the test suite is next to be executed but before the first test is run. YUITest.TestRunner.TEST_SUITE_COMPLETE_EVENT occurs when all tests in all test cases in the test suite have been executed or ignored. For these two events, the event data object has three properties: type - indicates the type of event that occurred. testSuite - the test suite that is currently being run.
  • 28. TestRunner Events TestRunner-Level Events YUITest.TestRunner.BEGIN_EVENT occurs when testing is about to begin but before any tests are run. YUITest.TestRunner.COMPLETE_EVENT occurs when all tests in all test cases and test suites have been executed or ignored. Subscribing to Events function handleTestFail(data){ alert("Test named '" + data.testName + "' failed with message: '" + data.error.message + "'."); } var TestRunner = YUITest.TestRunner; TestRunner.subscribe(TestRunner.TEST_FAIL_EVENT, handleTestFail); TestRunner.run();
  • 29. Viewing Results YUI({ logInclude: { TestRunner: true } }).use("console", function(Y){ //tests go here //initialize the console var yconsole = new Y.Console({ newestOnTop: false }); yconsole.render('#log'); //run the tests YUITest.TestRunner.run(); });
  • 30. Viewing Results YUI({ useBrowserConsole: true }).use("test", function(Y){ //tests go here Y.Test.Runner.run(); });
  • 31. Viewing Results YUI({ useBrowserConsole: true }).use("test", function(Y){ //tests go here //get object of results var resultsObject = YUITest.TestRunner.getResult(); //get XML results var resultsXML = YUITest.TestRunner.getResult(YUITest.TestFormat.XML); }); YUITest.TestFormat.XML - YUI Test XML (default) YUITest.TestFormat.JSON - JSON YUITest.TestFormat.JUnitXML - JUnit XML YUITest.TestFormat.TAP - TAP
  • 32. Code Coverage Data YUITest.TestRunner.getCoverage() YUITest.CoverageFormat.JSON - JSON YUITest.CoverageFormat.XdebugJSON - JSON formatted Xdebug
  • 33. Test Reporting var reporter = new YUITest.Reporter("http://www.yourserver.com/path/to/target", YUITest.TestFormat.JSON); reporter.report(results); results - the serialized results object. useragent - the user-agent string of the browser. timestamp - the date and time that the report was sent. reporter.addField("color", "blue"); reporter.addField("message", "Hello world!");
  • 34. Yeti: YUI’s Easy Testing Interface Yeti is a command-line tool for launching JavaScript unit tests in a browser and reporting the results without leaving your terminal. Yeti is designed to work with existing unmodified YUI-based tests. Yeti is designed to help you run tests before you commit. It compliments existing CI tools like Selenium and Hudson which run tests post-commit. Yeti is not a replacement for those tools.