当前位置: 代码迷 >> JavaScript >> 工具分享:Jasmine(JavaScript单元测试用具)
  详细解决方案

工具分享:Jasmine(JavaScript单元测试用具)

热度:215   发布时间:2012-11-11 10:07:57.0
工具分享:Jasmine(JavaScript单元测试工具)

Jasmine SDK

 

SDK明细

////例子1
describe("A suite is just a function", function () {
    var a;

    it("and so is a spec", function () {
        a = true;

        expect(a).toBe(true);
    });

      it("and can have a negative case", function() {
    expect(false).not.toBe(true);
  });
});



//例子2
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);
    });


//支持正则表达式
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/);
});

//检测元素是否定义过
it("The 'toBeDefined' matcher compares against `undefined`", function () {
    var a = {
        foo: 'foo'
    };

    expect(a.foo).toBeDefined();
    expect(a.bar).not.toBeDefined();
});


it("The `toBeUndefined` matcher compares against `undefined`", function () {
    var a = {
        foo: 'foo'
    };

    expect(a.foo).not.toBeUndefined();
    expect(a.bar).toBeUndefined();
});

//检测元素是否为空
it("The 'toBeNull' matcher compares against null", function () {
    var a = null;
    var foo = 'foo';

    expect(null).toBeNull();
    expect(a).toBeNull();
    expect(foo).not.toBeNull();
});

  it("The 'toBeTruthy' matcher is for boolean casting testing", function() {
    var a, foo = 'foo';

    expect(foo).toBeTruthy();
    expect(a).not.toBeTruthy();
  });

  it("The 'toBeFalsy' matcher is for boolean casting testing", function() {
    var a, foo = 'foo';

    expect(a).toBeFalsy();
    expect(foo).not.toBeFalsy();
  });

  //检测是否包含某个元素
  it("The 'toContain' matcher is for finding an item in an Array", function() {
    var a = ['foo', 'bar', 'baz'];

    expect(a).toContain('bar');
    expect(a).not.toContain('quux');
  });

  //是否小于
  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);
  });

  //是否大于
  it("The 'toBeGreaterThan' is for mathematical comparisons", function() {
    var pi = 3.1415926, e = 2.78;

    expect(pi).toBeGreaterThan(e);
    expect(e).not.toBeGreaterThan(pi);
  });

  //四舍五入
  it("The 'toBeCloseTo' matcher is for precision math comparison", function() {
    var pi = 3.1415926, e = 2.78;

    expect(pi).not.toBeCloseTo(e, 0.1);
    expect(pi).toBeCloseTo(e, 0);
  });

    
  //检测元素是否会抛错
  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();
  });
});

describe("A spec", function () {
    var foo;

    //在运行spec之前会运行这个方法
    beforeEach(function () {
        foo = 0;
        foo += 1;
    });

    //这个方法好像不会触发
    afterEach(function () {
        foo = 0;
    });

    it("is just a function, so it can contain any code", function () {
        expect(foo).toEqual(1);
    });

    it("can have more than one expectation", function () {
        expect(foo).toEqual(1);
        expect(true).toEqual(true);
    });
});

//模拟
describe("A spy", function () {
    var foo, bar = null;

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

        spyOn(foo, 'setBar');

        foo.setBar(123);
        foo.setBar(456, 'another param');
    });

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

    it("tracks its number of calls", function () {
        expect(foo.setBar.calls.length).toEqual(2);
    });

    it("tracks all the arguments of its calls", function () {
        expect(foo.setBar).toHaveBeenCalledWith(123);
        expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
    });

    //最近的一次调用
    it("allows access to the most recent call", function () {
        expect(foo.setBar.mostRecentCall.args[0]).toEqual(456);
    });

    it("allows access to other calls", function () {
        expect(foo.setBar.calls[0].args[0]).toEqual(123);
    });

    it("stops all execution on a function", function () {
        expect(bar).toBeNull();
    });
});


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').andCallThrough();

        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(123);
    });
});



describe("A spy, when faking a return value", function () {
    var foo, bar, fetchedBar;

    beforeEach(function () {
        foo = {
            setBar: function (value) {
                bar = value;
            },
            getBar: function () {
                return bar;
            }
        };
        //模拟返回值
        spyOn(foo, 'getBar').andReturn(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);
    });
});


describe("A spy, when faking a return value", function () {
    var foo, bar, fetchedBar;

    beforeEach(function () {
        foo = {
            setBar: function (value) {
                bar = value;
            },
            getBar: function () {
                return bar;
            }
        };

        //模拟返回方法
        spyOn(foo, 'getBar').andCallFake(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);
    });
});



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.identity).toEqual('whatAmI')
    });

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

    it("tracks its number of calls", function () {
        expect(whatAmI.calls.length).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.mostRecentCall.args[0]).toEqual("I");
    });
});




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);
    });
});


describe("jasmine.any", function () {
    //any语法很重要
    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));
        });
    });
});




describe("Manually ticking the Jasmine Mock Clock", function() {
    var timerCallback; 

  beforeEach(function() {
    timerCallback = jasmine.createSpy('timerCallback');
    jasmine.Clock.useMock();
   }); 

  it("causes a timeout to be called synchronously", function() {
    setTimeout(function() {
      timerCallback();
    }, 100);

    //这个是延期执行的,所以并不能立即匹配到结果
    expect(timerCallback).not.toHaveBeenCalled();
    //估计这个是让系统休眠101毫秒
    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.callCount).toEqual(1);

    jasmine.Clock.tick(50);
    expect(timerCallback.callCount).toEqual(1);

    jasmine.Clock.tick(50);
    expect(timerCallback.callCount).toEqual(2);
  });
}); 



//异步执行,这个没有测试通过
describe("Asynchronous specs", function () {
    var value, flag;

    it("should support async execution of test preparation and exepectations", function () {
        //runs是可以进行异步调用的
        runs(function () {
            flag = false;
            value = 0;
           
            setTimeout(function () {
                flag = true;
            }, 500);
        });

        //waitsfor函数有3个参数:第一个是判断是否结束等待的函数,如果其返回值为真就结束等待,这个函数是会反复执行的。
        //                     第二个参数应该是错误时返回的消息;
        //                     第三个参数应该是等待超时时间,如果等待超时就抛错误终止等待;
        waitsFor(function () {
            value++;

            return flag;
        }, "The Value should be incremented", 1000);


        //判断waitsfor函数中的等待函数是否执行了多次
        runs(function () {
            expect(value).toBeGreaterThan(0);
        });

    });
}); 


//这段代码是将执行结果保存在DIV标记中,该标记是自动创建的,ID值为HTMLReporter
//(function() {
//  var jasmineEnv = jasmine.getEnv();
//  jasmineEnv.updateInterval = 250; 

//  var htmlReporter = new jasmine.HtmlReporter();
//  jasmineEnv.addReporter(htmlReporter); 



//  jasmineEnv.specFilter = function(spec) {
//    return htmlReporter.specFilter(spec);
//  }; 




//  var currentWindowOnload = window.onload;
//  window.onload = function() {
//    if (currentWindowOnload) {
//      currentWindowOnload();
//    }

//    //document.querySelector('.version').innerHTML = jasmineEnv.versionString();
//    execJasmine();
//  };

//  function execJasmine() {
//    jasmineEnv.execute();
//  }
//})(); 

 

Demo


 

  相关解决方案