views:

225

answers:

3

I have such JS class:

SomeClass = function {  
    // some stuff that uses initRequest    
    this.initRequest = function() {  
        if (window.XMLHttpRequest) {  
            return new XMLHttpRequest();  
        } else if (window.ActiveXObject) {  
            return new ActiveXObject("Microsoft.XMLHTTP");  
        }   
     }  
}

I want to override method initRequest for testing purposes. I tried to do something like that

var request = new MockXmlHttpRequest();  
var instance = new SomeClass();
instance.initRequest = function() {
    return request;
};
// some calls of the SomeClass methods that uses initRequest
// some test code with assertions about request

As I discovered instance uses my initRequest instead of original, but variable request is not changed after using of instance. Thus I my assertions fail.

Any ideas what's wrong?

A: 

Check out YUI's extend functionality. It makes all this really clean, PLUS, you can still access the method of the super class if you really want to. Their augment object might also be of interest to you.

Here is the link http://developer.yahoo.com/yui/examples/yahoo/yahoo_extend.html

Zoidberg
A: 

In your first example, initRequest returns a new object after each call; in the second example, all calls to initRequest return a reference to the one and only (mock) object.

The request object is not changed in the code example you provide. instance.initRequest simple returns a reference to request. Why do expect it to have changed?

Upper Stage
Because of// some calls of the SomeClass methods that uses initRequest
DixonD
Have you used FireBug to examine request before and after the call? I find FireBug indispensable. Maybe you could post additional code?
Upper Stage
A: 

I'm having a little trouble understanding your question because of your English, but I'll try to answer anyway (and if I answer the wrong question just let me know).

I think what you want to do is:

SomeClass = function {  
    // some stuff that uses initRequest    
    this.initRequest = function() {  
        return request;
     }  
}

In other words, you want to overwrite the original SomeClass object with a new function. Unless you do that new SomeClass objects won't use your test method, they'll just use the original method.

However, if you only want to override that method for a specific object, not for the whole class, what you have there should work. If that's the case, could you please clarify what exactly isn't working about it?

machineghost