Javascript测试框架Jasmine(五):Spies

测试报告会自动追加到页尾

describe("Jasmine Spy的跟踪属性", function() {
    var foo, bar = null;

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

        spyOn(foo, 'setBar');
    });

    it(".calls.any()示例", function() {
        expect(foo.setBar.calls.any()).toEqual(false);

        foo.setBar();

        expect(foo.setBar.calls.any()).toEqual(true);
    });

    it(".calls.count()示例", function() {
        expect(foo.setBar.calls.count()).toEqual(0);

        foo.setBar();
        foo.setBar();

        expect(foo.setBar.calls.count()).toEqual(2);
    });

    it(".calls.argsFor(index)示例", 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"]);
    });

    it(".calls.allArgs()示例", function() {
        foo.setBar(123);
        foo.setBar(456, "baz");

        expect(foo.setBar.calls.allArgs()).toEqual([
            [123],
            [456, "baz"]
        ]);
    });

    it(".calls.all()示例", function() {
        foo.setBar(123);

        expect(foo.setBar.calls.all()).toEqual([{
            object: foo,
            args: [123]
        }]);
    });

    it(".calls.mostRecent()示例", function() {
        foo.setBar(123);
        foo.setBar(456, "baz");

        expect(foo.setBar.calls.mostRecent()).toEqual({
            object: foo,
            args: [456, "baz"]
        });
    });

    it(".calls.first()示例", function() {
        foo.setBar(123);
        foo.setBar(456, "baz");

        expect(foo.setBar.calls.first()).toEqual({
            object: foo,
            args: [123]
        });
    });

    it(".calls.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);
    });
});