2

被测代码:

module lib {
    export class Topic {
        private _callbacks: JQueryCallback;
        public id: string;
        public publish: any;
        public subscribe: any;
        public unsubscribe: any;
        public test: any;

        constructor(id: string) {
            this.id = id;
            this._callbacks = jQuery.Callbacks();
            this.publish = this._callbacks.fire;
            this.subscribe = this._callbacks.add;
            this.unsubscribe = this._callbacks.remove;
        }
    }

    export class Bus {
        private static _topics: Object = {};

        static topic(id: string): Topic {
            var topic = id && this._topics[id];

            if (!topic) {
                topic = new Topic(id);
                if (id) {
                    this._topics[id] = topic;
                }
            }

            return topic;
        }
    }
}

规格测试对象:

module lib {
    class Person {
        private _dfd: JQueryDeferred<Topic>;
        private _topic: Topic;

        constructor(public firstName: string) {
            this._dfd = jQuery.Deferred();
            this._topic = Bus.topic("user:logon");
            this._dfd.done(this._topic.publish);
        }

        logon() {
            this._dfd.resolve(this);
        }
    }

    class ApiService {
        constructor() {
            Bus.topic("user:logon").subscribe(this.callLogonApi);
        }
        callLogonApi(person: Person) {
            console.log("Person.firstname: " + person.firstName);
        }
    }

    describe("Bus", () => {
        var person: Person;
        var apiService: ApiService;

        beforeEach(() => {
            person = new Person("Michael");
            apiService = new ApiService();
            spyOn(apiService, "callLogonApi");

                //or this fails as well
                //spyOn(apiService, "callLogonApi").and.callThrough();
            person.logon();
        });

        it("should create subscription and catch the published event", () => {
            expect(apiService.callLogonApi).toHaveBeenCalled();

                //this fails too 
            //expect(apiService.callLogonApi).toHaveBeenCalledWith(person);
        });
    });
}

调用 callLogonApi 函数并按预期写入控制台,但输出为:

Expected spy callLogonApi to have been called.
Error: Expected spy callLogonApi to have been called.

*这现在与 ApiService 的构造函数一起工作,更改为:

    constructor() {
        Bus.topic("user:logon").subscribe((data)=> { this.callLogonApi(data); });
    }

*并且 spyOn 需要

        spyOn(apiService, "callLogonApi").and.callThrough();

感谢瑞安的精彩回答!!

4

1 回答 1

6

这是正在发生的事情的较小版本。

首先,这是该spyOn方法的一个更简单的版本:

function spyOn(obj: any, methodName: string) {
    var prev = obj[methodName];
    obj[methodName] = function() {
        console.log(methodName + ' got called');
        prev();
    }
}

现在让我们用一个简单的类来试试这个:

/** OK **/
class Thing1 {
    sayHello() {
        console.log('Hello, world');
    }
}

var x = new Thing1();
spyOn(x, 'sayHello');
x.sayHello(); // 'sayHello got called'

这按预期工作。转到延迟版本,这就是您的代码正在执行的操作:

/** Not OK **/
class Thing2 {
    private helloMethod;

    constructor() {
        this.helloMethod = this.sayHello;
    }

    deferredHello() {
        window.setTimeout(this.helloMethod, 10);
    }

    sayHello() {
        console.log('Hello, world');
    }
}

var y = new Thing2();
spyOn(y, 'sayHello');
y.deferredHello(); // Why no spy?

最后是固定版本。我将解释为什么它很快就会修复:

/** OK now **/
class Thing3 {
    private helloMethod;

    constructor() {
        this.helloMethod = () => { this.sayHello(); }
    }

    deferredHello() {
        window.setTimeout(this.helloMethod, 10);
    }

    sayHello() {
        console.log('Hello, world');
    }   
}

var z = new Thing3();
spyOn(z, 'sayHello');
z.deferredHello(); // Spy works!

这是怎么回事?

请注意,该spyOn函数接受一个对象,包装该方法,然后在对象本身上设置一个属性,以替换间谍函数实例。这非常重要,因为它改变了方法名称的属性查找最终发生的位置。

在正常情况下(Thing1),我们覆盖(使用spyOn) on的属性x,然后在 上调用相同的方法xspyOn一切正常,因为我们正在调用包装的完全相同的函数。

在延迟的情况下 ( Thing2),y.sayHello改变了整个代码的含义。当我们第一次在构造函数中获取它时,我们从类的原型sayHello中获取方法。当 we 时,被包装的函数是一个新对象,但我们之前在执行中得到的引用仍然指向原型中的实现。spyOn y.sayHellosayHello

在固定的情况下 ( Thing3),我们使用一个函数来更懒惰地获取 的值sayHello,因此当z.sayHello发生更改时(因为我们窥探到了它),deferredHello调用“看到”现在位于实例对象而不是类原型上的新方法对象。

于 2014-03-25T18:56:48.633 回答