文章出處

 

參考:

http://www.cnblogs.com/wushangjue/p/4541209.html

http://keenwon.com/1191.html

http://jasmine.github.io/2.0/introduction.html

/*
Created by laixiangran on 2015/12/15.
jasmine測試腳本
 */
(function() {
    /*
     jasmine基本語法介紹:
     describe(string, function):可以理解為是一個測試集或者測試包(官方稱之為suite),主要功能是用來劃分單元測試的,describe是可以嵌套使用的
     參數string:描述測試包的信息
     參數function:測試集的具體實現,可包含任意代碼

     it(string, function):測試用例(官方稱之為spec)
     參數string:描述測試用例的信息
     參數function:測試用例的具體實現,可包含任意代碼

     expect:斷言表達式

     從以下例子可知:
     1、每個測試文件中可以包含多個describe
     2、每個describe中可以包含多個it
     3、每個it中可以包含多個expect
     4、describe可嵌套使用
     */
    describe("Jasmine Test 1", function() {
        it("a spec with an expectation", function() {
            expect(1).toBe(1);
            expect(1===1).toBe(true);
            expect("a").not.toBe("b");
        });

        it("an other spec in current suite", function() {
            expect(true).toBe(true);
        });
    });
    describe("Jasmine Test 2", function() {
        it("nothing", function() {

        });
    });
    describe("Jasmine Test 3", function() {
        describe("Jasmine Test 4", function() {
            it("b等于b", function() {
                expect("b").toBe("b");
            });

            it("1===1是正確的", function() {
                expect(1===1).toBe(true);
            });
        });
    });

    /*
     * expect的匹配器
     * */
    describe("Included matchers:", function() {
        //"toBe"基本類型判斷
        it("The 'toBe' matcher compares with ===", function() {
            var a = 12;
            var b = a;
            expect(a).toBe(b);
            expect(a).not.toBe(null);
        });
        //"toEqual"除了能判斷基本類型(相當于"toBe"),還能判斷對象
        describe("The 'toEqual' matcher", function() {
            //基本類型判斷
            it("works for simple literals and variables", function() {
                var a = 12;
                expect(a).toEqual(12);
            });
            //對象判斷
            it("should work for objects", function() {
                var foo = {
                    a: 12,
                    b: 34
                };
                var bar = {
                    a: 12,
                    b: 34
                };
                expect(foo).toEqual(bar);
            });
        });
        //"toMatch"使用正則表達式判斷
        it("The 'toMatch' matcher is for regular expressions", function() {
            var message = "foo bar baz";
            expect(message).toMatch(/bar/);
            expect(message).toMatch("bar");
            expect(message).not.toMatch(/quux/);
        });
        //"toBeDefined"判斷是否定義
        it("The 'toBeDefined' matcher compares against 'undefined'", function() {
            var a = {
                foo: "foo"
            };
            expect(a.foo).toBeDefined();
            expect(a.bar).not.toBeDefined();
        });
        //"toBeUndefined"判斷是否是undefined,與"toBeDefined"相反
        it("The 'toBeUndefined' matcher compares against 'undefined'", function() {
            var a = {
                foo: "foo"
            };
            expect(a.foo).not.toBeUndefined();
            expect(a.bar).toBeUndefined();
        });
        //"toBeNull"判斷是否為null
        it("The 'toBeNull' matcher compares against null", function() {
            var a = null;
            var foo = "foo";
            expect(null).toBeNull();
            expect(a).toBeNull();
            expect(foo).not.toBeNull();
        });
        //"toBeTruthy"判斷是否是true
        it("The 'toBeTruthy' matcher is for boolean casting testing", function() {
            var a, foo = "foo";
            expect(foo).toBeTruthy();
            expect(a).not.toBeTruthy();
            expect(true).toBeTruthy();
        });
        //"toBeFalsy"判斷是否是false
        it("The 'toBeFalsy' matcher is for boolean casting testing", function() {
            var a, foo = "foo";
            expect(a).toBeFalsy();
            expect(foo).not.toBeFalsy();
            expect(false).toBeFalsy();
        });
        //"toContain"判斷數組是否包含(可判斷基本類型和對象)
        it("The 'toContain' matcher is for finding an item in an Array", function() {
            var a = ["foo", "bar", "baz"];
            var b = [{foo: "foo", bar: "bar"}, {baz: "baz", bar: "bar"}];
            expect(a).toContain("bar");
            expect(a).not.toContain("quux");
            expect(b).toContain({foo: "foo", bar: "bar"});
            expect(b).not.toContain({foo: "foo", baz: "baz"});
        });
        //"toBeLessThan"判斷值類型的大小,結果若小則為True(也可以判斷字符及字符串,以ascii碼的大小為判斷依據)
        it("The 'toBeLessThan' matcher is for mathematical comparisons", function() {
            var pi = 3.1415926,
                e = 2.78;
            expect(e).toBeLessThan(pi);
            expect(pi).not.toBeLessThan(e);
            expect("a").toBeLessThan("b");
            expect("b").not.toBeLessThan("a");
        });
        //"toBeGreaterThan"判斷值類型的大小,結果若大則為True,與toBeLessThan相反(也可以判斷字符及字符串,以ascii碼的大小為判斷依據)
        it("The 'toBeGreaterThan' matcher is for mathematical comparisons", function() {
            var pi = 3.1415926,
                e = 2.78;
            expect(pi).toBeGreaterThan(e);
            expect(e).not.toBeGreaterThan(pi);
            expect("a").not.toBeGreaterThan("b");
            expect("b").toBeGreaterThan("a");
        });
        //"toBeCloseTo"判斷數字是否相似(第二個參數為小數精度,默認為2位)
        it("The 'toBeCloseTo' matcher is for precision math comparison", function() {
            var a = 1.1;
            var b = 1.5;
            var c = 1.455;
            var d = 1.459;
            expect(a).toBeCloseTo(b, 0);
            expect(a).not.toBeCloseTo(c, 1);
            expect(c).toBeCloseTo(d);
        });
        //"toThrow"判斷是否拋出異常
        it("The 'toThrow' matcher is for testing if a function throws an exception", function() {
            var foo = function() {
                return 1 + 2;
            };
            var bar = function() {
                return a + 1;
            };
            expect(foo).not.toThrow();
            expect(bar).toThrow();
        });
        //"toThrowError"判斷是否拋出了指定的錯誤
        it("The 'toThrowError' matcher is for testing a specific thrown exception", function() {
            var foo = function() {
                throw new TypeError("foo bar baz");
            };
            expect(foo).toThrowError("foo bar baz");
            expect(foo).toThrowError(/bar/);
            expect(foo).toThrowError(TypeError);
            expect(foo).toThrowError(TypeError, "foo bar baz");
        });
    });

    /*
     * "fail"函數能使一個測試用例失敗,參數為自定義的失敗信息
     * */
    describe("A spec using the fail function", function() {
        var foo = function(x, callBack) {
            if (x) {
                callBack();
            }
        };

        it("should not call the callBack", function() {
            foo(false, function() {
                fail("Callback has been called");
            });
        });
    });

    /*
     Jasmine允許在執行測試集/測試用例的開始前/結束后做一些初始化/銷毀的操作。

     Setup方法:
     beforeAll:每個suite(即describe)中所有spec(即it)運行之前運行
     beforeEach:每個spec(即it)運行之前運行

     Teardown方法:
     afterAll:每個suite(即describe)中所有spec(即it)運行之后運行
     afterEach:每個spec(即it)運行之后運行
     * */
    var globalCount;
    describe("Setup and Teardown suite 1", function() {
        var suiteGlobalCount;
        var eachTestCount;

        beforeAll(function() {
            globalCount = 0;
            suiteGlobalCount = 0;
            eachTestCount = 0;
        });

        afterAll(function() {
            suiteGlobalCount = 0;
        });

        beforeEach(function() {
            globalCount++;
            suiteGlobalCount++;
            eachTestCount++;
        });

        afterEach(function() {
            eachTestCount = 0;
        });

        it("Spec 1", function() {
            expect(globalCount).toBe(1);
            expect(suiteGlobalCount).toBe(1);
            expect(eachTestCount).toBe(1);
        });

        it("Spec 2", function() {
            expect(globalCount).toBe(2);
            expect(suiteGlobalCount).toBe(2);
            expect(eachTestCount).toBe(1);
        });
    });

    describe("Setup and Teardown suite 2", function() {
        beforeEach(function() {
            globalCount += 2;
        });

        it("Spec 1", function() {
            expect(globalCount).toBe(4);
        });
    });

    /*
     * 在beforeEach - it - afterEach中,還可以使用this關鍵字定義變量。需要注意的是,使用this關鍵字聲明的變量,僅在beforeEach - it - afterEach這個過程中傳遞
     * */
    describe("Test 'this'", function() {
        beforeEach(function() {
            this.testCount = this.testCount || 0;
            this.testCount++;
        });

        afterEach(function() {
            //this.testCount = 0; //無論是否有這行,結果是一樣的,因為this指定的變量只能在每個spec的beforeEach/it/afterEach過程中傳遞
        });

        it("Spec 1", function() {
            expect(this.testCount).toBe(1);
        });

        it("Spec 2", function() {
            expect(this.testCount).toBe(1);
        });
    });

    /*
    在實際項目中,需要由于發布的版本需要選擇測試用例包,xdescribe和xit能很方便的將不包含在版本中的測試用例排除在外。
    不過xdescribe和xit略有不同:
    xdescribe:該describe下的所有it將被忽略,Jasmine將直接忽略這些it,因此不會被運行
    xit:運行到該it時,掛起它不執行
    * */
    xdescribe("Test xdescribe", function() {
        it("Spec 1", function() {
            expect(1).toBe(1);
        });

        it("Spec 2", function() {
            expect(2).toBe(2);
        });
    });

    describe("Test xit", function() {
        it("Spec 1", function() {
            expect(1).toBe(1);
        });

        xit("Spec 2", function() {
            expect(2).toBe(1);
        });

        xit("Spec 3", function() {
            expect(3).toBe(3);
        });
    });

    /*
    * Spy用來追蹤函數的調用歷史信息(是否被調用、調用參數列表、被請求次數等)。Spy僅存在于定義它的describe和it方法塊中,并且每次在spec執行完之后被銷毀。
    * 當在一個對象上使用spyOn方法后即可模擬調用對象上的函數,此時對所有函數的調用是不會執行實際代碼的。
    * 兩個Spy常用的expect:
    *   toHaveBeenCalled: 函數是否被調用
    *   toHaveBeenCalledWith: 調用函數時的參數
    * */
    describe("A spy", function() {
        var foo, bar = null;

        beforeEach(function() {
            foo = {
                setBar: function(value) {
                    bar = value;
                }
            };
            spyOn(foo, "setBar"); // 在foo對象上添加spy
            // 此時調用foo對象上的方法,均為模擬調用,因此不會執行實際的代碼
            foo.setBar(123); // 調用foo的setBar方法
            foo.setBar(456, "another param");
        });

        it("tracks that the spy was called", function() {
            expect(foo.setBar).toHaveBeenCalled(); //判斷foo的setBar是否被調用
        });

        it("tracks all the arguments of its calls", function() {
            expect(foo.setBar).toHaveBeenCalledWith(123); //判斷被調用時的參數
            expect(foo.setBar).toHaveBeenCalledWith(456, "another param");
        });

        it("stops all execution on a function", function() {
            expect(bar).toBeNull();  // 由于是模擬調用,因此bar值并沒有改變
        });
    });

    /*
    * spyOn().and.callThrough(),告訴Jasmine我們除了要完成對函數調用的跟蹤,同時也需要執行實際的代碼。
    * */
    describe("A spy, when configured to call through", function() {
        var foo, bar, fetchedBar;

        beforeEach(function() {
            foo = {
                setBar: function(value) {
                    bar = value;
                },
                getBar: function() {
                    return bar;
                }
            };
            spyOn(foo, "getBar").and.callThrough(); // 這里使用了callThrough,這時所有的函數調用為真實的執行
            spyOn(foo, "setBar").and.callThrough();
            foo.setBar(123);
            fetchedBar = foo.getBar();
        });

        it("tracks that the spy was called", function() {
            expect(foo.getBar).toHaveBeenCalled();
        });

        it("should not effect other functions", function() {
            expect(foo.setBar).toHaveBeenCalledWith(123);
            expect(bar).toEqual(123); // 由于是真實調用,因此bar有了真實的值
        });

        it("when called returns the requested value", function() {
            expect(fetchedBar).toEqual(123); // 由于是真實調用,fetchedBar也有了真實的值
        });
    });

    /*
    * spyOn().and.returnValue(),由于Spy是模擬函數的調用,因此我們也可以強制指定函數的返回值。
    * */
    describe("A spy, when configured to fake a return value", function() {
        var foo, bar, fetchedBar;

        beforeEach(function() {
            foo = {
                setBar: function(value) {
                    bar = value;
                },
                getBar: function() {
                    return bar;
                }
            };
            spyOn(foo, "getBar").and.returnValue(745); // 這將指定getBar方法返回值為745
            foo.setBar(123);
            fetchedBar = foo.getBar();
        });

        it("tracks that the spy was called", function() {
            expect(foo.getBar).toHaveBeenCalled();
        });

        it("should not effect other functions", function() {
            expect(bar).toEqual(123);
        });

        it("when called returns the requested value", function() {
            expect(fetchedBar).toEqual(745);
        });
    });

    /*
     * spyOn().and.callFake(),
     * 與returnValue相似,callFake則更進一步,直接通過指定一個假的自定義函數來執行。這種方式比returnValue更靈活,我們可以任意捏造一個函數來達到我們的測試要求。
     * */
    describe("A spy, when configured with an alternate implementation", function() {
        var foo, bar, fetchedBar;

        beforeEach(function() {
            foo = {
                setBar: function(value) {
                    bar = value;
                },
                getBar: function() {
                    return bar;
                }
            };
            spyOn(foo, "getBar").and.callFake(function() {
                return 1001;
            });
            foo.setBar(123);
            fetchedBar = foo.getBar();
        });

        it("tracks that the spy was called", function() {
            expect(foo.getBar).toHaveBeenCalled();
        });

        it("should not effect other functions", function() {
            expect(bar).toEqual(123);
        });

        it("when called returns the requested value", function() {
            expect(fetchedBar).toEqual(1001);
        });
    });

    /*
     * spyOn().and.throwError(),模擬異常的拋出
     * */
    describe("A spy, when configured to throw an error", function() {
        var foo, bar;

        beforeEach(function() {
            foo = {
                setBar: function(value) {
                    bar = value;
                }
            };
            spyOn(foo, "setBar").and.throwError("quux");
        });

        it("throws the value", function() {
            expect(function() {
                foo.setBar(123)
            }).toThrowError("quux");
        });
    });

    /*
     * spyOn().and.stub(),回復到原始的spyOn()方法
     * */
    describe("A spy", function() {
        var foo, bar = null;

        beforeEach(function() {
            foo = {
                setBar: function(value) {
                    bar = value;
                },
                getBar: function(){
                    return bar;
                }
            };
            spyOn(foo, "setBar").and.callThrough(); // 標記1
            spyOn(foo, "getBar").and.returnValue(999); // 標記2
        });

        it("can call through and then stub in the same spec", function() {
            foo.setBar(123);
            expect(bar).toEqual(123);

            var getValue = foo.getBar();
            expect(getValue).toEqual(999);

            foo.setBar.and.stub(); // 相當于"標記1"中的代碼變為了spyOn(foo, "setBar")
            foo.getBar.and.stub(); // 相當于"標記2"中的代碼變為了spyOn(foo, "getBar")
            bar = null;

            foo.setBar(123);
            expect(bar).toBe(null);
            expect(foo.setBar).toHaveBeenCalled(); // 函數調用追蹤并沒有被重置

            getValue = foo.getBar();
            expect(getValue).toEqual(undefined);
            expect(foo.getBar).toHaveBeenCalled(); // 函數調用追蹤并沒有被重置
        });
    });

    /*
    * 其他追蹤屬性:
     calls:對于被Spy的函數的調用,都可以在calls屬性中跟蹤。
     .calls.any(): 被Spy的函數一旦被調用過,則返回true,否則為false;
     .calls.count(): 返回被Spy的函數的被調用次數;
     .calls.argsFor(index): 返回被Spy的函數的調用參數,以index來指定參數;
     .calls.allArgs():返回被Spy的函數的所有調用參數;
     .calls.all(): 返回calls的上下文,這將返回當前calls的整個實例數據;
     .calls.mostRecent(): 返回calls中追蹤的最近一次的請求數據;
     .calls.first(): 返回calls中追蹤的第一次請求的數據;
     .object: 當調用all(),mostRecent(),first()方法時,返回對象的object屬性返回的是當前上下文對象;
     .calls.reset(): 重置Spy的所有追蹤數據;
    * */
    describe("A spy", function() {
        var foo, bar = null;

        beforeEach(function() {
            foo = {
                setBar: function(value) {
                    bar = value;
                }
            };
            spyOn(foo, "setBar");
        });

        //.calls.any(): 被Spy的函數一旦被調用過,則返回true,否則為false;
        it("tracks if it was called at all", function() {
            expect(foo.setBar.calls.any()).toEqual(false);
            foo.setBar();
            expect(foo.setBar.calls.any()).toEqual(true);
        });

        //.calls.count(): 返回被Spy的函數的被調用次數;
        it("tracks the number of times it was called", function() {
            expect(foo.setBar.calls.count()).toEqual(0);
            foo.setBar();
            foo.setBar();
            expect(foo.setBar.calls.count()).toEqual(2);
        });

        //.calls.argsFor(index): 返回被Spy的函數的調用參數,以index來指定參數;
        it("tracks the arguments of each call", function() {
            foo.setBar(123);
            foo.setBar(456, "baz");
            expect(foo.setBar.calls.argsFor(0)).toEqual([123]);
            expect(foo.setBar.calls.argsFor(1)).toEqual([456, "baz"]);
        });

        //.calls.allArgs():返回被Spy的函數的所有調用參數;
        it("tracks the arguments of all calls", function() {
            foo.setBar(123);
            foo.setBar(456, "baz");
            expect(foo.setBar.calls.allArgs()).toEqual([[123],[456, "baz"]]);
        });

        //.calls.all(): 返回calls的上下文,這將返回當前calls的整個實例數據;
        it("can provide the context and arguments to all calls", function() {
            foo.setBar(123);
            expect(foo.setBar.calls.all()).toEqual([{object: foo, args: [123], returnValue: undefined}]);
        });

        //.calls.mostRecent(): 返回calls中追蹤的最近一次的請求數據;
        it("has a shortcut to the most recent call", function() {
            foo.setBar(123);
            foo.setBar(456, "baz");
            expect(foo.setBar.calls.mostRecent()).toEqual({object: foo, args: [456, "baz"], returnValue: undefined});
        });

        //.calls.first(): 返回calls中追蹤的第一次請求的數據;
        it("has a shortcut to the first call", function() {
            foo.setBar(123);
            foo.setBar(456, "baz");
            expect(foo.setBar.calls.first()).toEqual({object: foo, args: [123], returnValue: undefined});
        });

        //.object: 當調用all(),mostRecent(),first()方法時,返回對象的object屬性返回的是當前上下文對象;
        it("tracks the context", function() {
            var spy = jasmine.createSpy("spy");
            var baz = {
                fn: spy
            };
            var quux = {
                fn: spy
            };
            baz.fn(123);
            quux.fn(456);
            expect(spy.calls.first().object).toBe(baz);
            expect(spy.calls.mostRecent().object).toBe(quux);
        });

        //.calls.reset(): 重置Spy的所有追蹤數據;
        it("can be reset", function() {
            foo.setBar(123);
            foo.setBar(456, "baz");
            expect(foo.setBar.calls.any()).toBe(true);
            foo.setBar.calls.reset();
            expect(foo.setBar.calls.any()).toBe(false);
        });
    });

    /*
     jasmine.createSpy()
    * 假如沒有函數可以追蹤,我們可以自己創建一個空的Spy。
    * 創建后的Spy功能與其他的Spy一樣:跟蹤調用、參數等,但該Spy沒有實際的代碼實現,這種方式經常會用在對JavaScript中的對象的測試。
    * */
    describe("A spy, when created manually", function() {
        var whatAmI;

        beforeEach(function() {
            whatAmI = jasmine.createSpy("whatAmI");
            whatAmI("I", "am", "a", "spy");
        });

        it("is named, which helps in error reporting", function() {
            expect(whatAmI.and.identity()).toEqual("whatAmI");
        });

        it("tracks that the spy was called", function() {
            expect(whatAmI).toHaveBeenCalled();
        });

        it("tracks its number of calls", function() {
            expect(whatAmI.calls.count()).toEqual(1);
        });

        it("tracks all the arguments of its calls", function() {
            expect(whatAmI).toHaveBeenCalledWith("I", "am", "a", "spy");
        });

        it("allows access to the most recent call", function() {
            expect(whatAmI.calls.mostRecent().args[0]).toEqual("I");
        });
    });

    /*
     jasmine.createSpyObj()
     * 如果需要spy模擬多個函數調用,可以向jasmine.createSpyObj中傳入一個字符串數組,它將返回一個對象,
     * 你所傳入的所有字符串都將對應一個屬性,每個屬性即為一個Spy。
     * */
    describe("Multiple spies, when created manually", function() {
        var tape;

        beforeEach(function() {
            tape = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']);
            tape.play();
            tape.pause();
            tape.rewind(0);
        });

        it("creates spies for each requested function", function() {
            expect(tape.play).toBeDefined();
            expect(tape.pause).toBeDefined();
            expect(tape.stop).toBeDefined();
            expect(tape.rewind).toBeDefined();
        });

        it("tracks that the spies were called", function() {
            expect(tape.play).toHaveBeenCalled();
            expect(tape.pause).toHaveBeenCalled();
            expect(tape.rewind).toHaveBeenCalled();
            expect(tape.stop).not.toHaveBeenCalled();
        });

        it("tracks all the arguments of its calls", function() {
            expect(tape.rewind).toHaveBeenCalledWith(0);
        });
    });

    /*
    *  jasmine.any()
    * 以構造器或者類名作為參數,Jasmine將判斷期望值和真實值的構造器是否相同,若相同則返回true。
    * */
    describe("jasmine.any", function() {
        it("matches any value", function() {
            expect({}).toEqual(jasmine.any(Object));
            expect(12).toEqual(jasmine.any(Number));
        });

        describe("when used with a spy", function() {
            it("is useful for comparing arguments", function() {
                var foo = jasmine.createSpy("foo");
                foo(12, function() {
                    return true;
                });
                expect(foo).toHaveBeenCalledWith(jasmine.any(Number), jasmine.any(Function));
            });
        });
    });

    /*
    * jasmine.anything()
    * 判斷只要不是null或undefined的值,若不是則返回true。
    * */
    describe("jasmine.anything", function() {
        it("matches anything", function() {
            expect(1).toEqual(jasmine.anything());
        });

        describe("when used with a spy", function() {
            it("is useful when the argument can be ignored", function() {
                var foo = jasmine.createSpy('foo');
                foo(12, function() {
                    return false;
                });
                expect(foo).toHaveBeenCalledWith(12, jasmine.anything());
            });
        });
    });

    /*
    * jasmine.objectContaining()
    * 用來判斷對象中是否存在指定的鍵值屬性對。
    * */
    describe("jasmine.objectContaining", function() {
        var foo;

        beforeEach(function() {
            foo = {
                a: 1,
                b: 2,
                bar: "baz"
            };
        });

        it("matches objects with the expect key/value pairs", function() {
            expect(foo).toEqual(jasmine.objectContaining({
                bar: "baz"
            }));
            expect(foo).not.toEqual(jasmine.objectContaining({
                c: 37
            }));
        });

        describe("when used with a spy", function() {
            it("is useful for comparing arguments", function() {
                var callback = jasmine.createSpy("callback");
                callback({
                    bar: "baz"
                });
                expect(callback).toHaveBeenCalledWith(jasmine.objectContaining({
                    bar: "baz"
                }));
                expect(callback).not.toHaveBeenCalledWith(jasmine.objectContaining({
                    c: 37
                }));
            });
        });
    });

    /*
    * jasmine.arrayContaining()
    * 可以用來判斷數組中是否有期望的值。
    * */
    describe("jasmine.arrayContaining", function() {
        var foo;

        beforeEach(function() {
            foo = [1, 2, 3, 4];
        });

        it("matches arrays with some of the values", function() {
            expect(foo).toEqual(jasmine.arrayContaining([3, 1]));  // 直接在期望值中使用jasmine.arrayContaining達到目的
            expect(foo).not.toEqual(jasmine.arrayContaining([6]));
        });

        describe("when used with a spy", function() {
            it("is useful when comparing arguments", function() {
                var callback = jasmine.createSpy("callback"); // 創建一個空的Spy
                callback([1, 2, 3, 4]); // 將數組內容作為參數傳入Spy中
                expect(callback).toHaveBeenCalledWith(jasmine.arrayContaining([4, 2, 3]));
                expect(callback).not.toHaveBeenCalledWith(jasmine.arrayContaining([5, 2]));
            });
        });
    });

    /*
    * jasmine.stringMatching()
    * 用來模糊匹配字符串,在jasmine.stringMatching中也可以使用正則表達式進行匹配,使用起來非常靈活。
    * */
    describe("jasmine.stringMatching", function() {
        it("matches as a regexp", function() {
            expect({foo: "bar"}).toEqual({foo: jasmine.stringMatching(/^bar$/)});
            expect({foo: "foobarbaz"}).toEqual({foo: jasmine.stringMatching("bar")});
        });

        describe("when used with a spy", function() {
            it("is useful for comparing arguments", function() {
                var callback = jasmine.createSpy("callback");
                callback("foobarbaz");
                expect(callback).toHaveBeenCalledWith(jasmine.stringMatching("bar"));
                expect(callback).not.toHaveBeenCalledWith(jasmine.stringMatching(/^bar$/));
            });
        });
    });

    /*
    * 不規則匹配(自定義匹配):asymmetricMatch
    * 某些場景下,我們希望能按照自己設計的規則進行匹配,此時我們可以自定義一個對象,該對象只要包含一個名為asymmetricMatch的方法即可。
    * */
    describe("custom asymmetry", function() {
        var tester = {
            asymmetricMatch: function(actual) {
                var secondValue = actual.split(",")[1];
                return secondValue === "bar";
            }
        };

        it("dives in deep", function() {
            expect("foo,bar,baz,quux").toEqual(tester);
        });

        describe("when used with a spy", function() {
            it("is useful for comparing arguments", function() {
                var callback = jasmine.createSpy("callback");
                callback("foo,bar,baz");
                expect(callback).toHaveBeenCalledWith(tester);
            });
        });
    });

    /*
    * jasmine.clock()用來模擬操縱時間。
    * 要想使用jasmine.clock(),先調用jasmine.clock().install告訴Jasmine你想要在spec或者suite操作時間,當你不需要使用時,務必調用jasmine.clock().uninstall來恢復時間狀態。
    *
    * 示例中使用jasmine.clock().tick(milliseconds)來控制時間前進,本例中出現了三種時間控制方式:
    * setTimeout: 定期執行一次,當jasmine.clock().tick()的時間超過了timeout設置的時間時觸發
    * setInterval: 定期循環執行,每當jasmine.clock().tick()的時間超過了timeout設置的時間時觸發
    * mockDate: 模擬一個指定日期(當不提供基準時間參數時,以當前時間為基準時間)
    * */
    describe("Manually ticking the Jasmine Clock", function() {
        var timerCallback;

        beforeEach(function() {
            timerCallback = jasmine.createSpy("timerCallback");
            jasmine.clock().install();
        });

        afterEach(function() {
            jasmine.clock().uninstall();
        });

        it("causes a timeout to be called synchronously", function() {
            setTimeout(function() {
                timerCallback();
            }, 100);
            expect(timerCallback).not.toHaveBeenCalled();
            jasmine.clock().tick(101);
            expect(timerCallback).toHaveBeenCalled();
        });

        it("causes an interval to be called synchronously", function() {
            setInterval(function() {
                timerCallback();
            }, 100);
            expect(timerCallback).not.toHaveBeenCalled();
            jasmine.clock().tick(101);
            expect(timerCallback.calls.count()).toEqual(1);
            jasmine.clock().tick(50);
            expect(timerCallback.calls.count()).toEqual(1);
            jasmine.clock().tick(50);
            expect(timerCallback.calls.count()).toEqual(2);
        });

        describe("Mocking the Date object", function(){
            it("mocks the Date object and sets it to a given time", function() {
                var baseTime = new Date();
                jasmine.clock().mockDate(baseTime);
                jasmine.clock().tick(50);
                expect(new Date().getTime()).toEqual(baseTime.getTime() + 50);
            });
        });
    });

    /*
    * Jasmine可以支持spec中執行異步操作。
    * 當調用beforeEach, it和afterEach時,函數可以包含一個可選參數done,當spec執行完畢之后,調用done通知Jasmine異步操作已執行完畢。
    *
    * 另外補充一點,如果需要設置全局的默認超時時間,可以設置jasmine.DEFAULT_TIMEOUT_INTERVAL的值,
    * 當異步執行時間超過設置的執行超時時間js將會報錯。
    * */
    describe("Asynchronous specs", function() {
        var value;

        beforeEach(function(done) {
            setTimeout(function() {
                value = 0;
                done();
            }, 1);
        });

        // 在上面beforeEach的done()被執行之前,這個測試用例不會被執行
        it("should support async execution of test preparation and expectations", function(done) {
            value++;
            expect(value).toBeGreaterThan(0);
            done(); // 執行完done()之后,該測試用例真正執行完成
        });

        // Jasmine異步執行超時時間默認為5秒,超過后將報錯
        describe("long asynchronous specs", function() {
            var originalTimeout;

            beforeEach(function() {
                originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
                // 設置全局的默認超時時間
                jasmine.DEFAULT_TIMEOUT_INTERVAL = 6000;
            });

            it("takes a long time", function(done) {
                setTimeout(function() {
                    done();
                }, 4000);
            });

            // 如果要調整指定用例的默認的超時時間,可以在beforeEach,it和afterEach中傳入一個時間參數
            //it("takes a long time for this spec", function(done) {
            //    setTimeout(function() {
            //        done();
            //    }, 6000);
            //}, 7000);

            afterEach(function() {
                jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
            });
        });
    });
}());

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jasmine Spec Runner v2.4.1</title>
    <link rel="shortcut icon" type="image/png" href="../jasmine-2.4.1/images/jasmine_favicon.png">
    <link rel="stylesheet" type="text/css" href="../jasmine-2.4.1/lib/jasmine-core/jasmine.css">

    <script type="text/javascript" src="../jasmine-2.4.1/lib/jasmine-core/jasmine.js"></script>
    <script type="text/javascript" src="../jasmine-2.4.1/lib/jasmine-core/jasmine-html.js"></script>
    <script type="text/javascript" src="../jasmine-2.4.1/lib/jasmine-core/boot.js"></script>

    <!-- 需要測試的js文件及jasmine測試腳本 -->
    <script type="text/javascript" src="myFirstJasmineTest.js"></script>
</head>
<body>

</body>
</html>

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜

    大師兄 發表在 痞客邦 留言(0) 人氣()