开发者

Redefine a method on an object

I'm trying t开发者_运维知识库o do the following:

//Code under test
function Foo() {
  this.do_something_interesting = function() {
    var dependency = new CanYouMockMe();
    if(dependency.i_want_stubbed() === true) {
      //do stuff based on condition
    } else {
      //do stuff if false
    }
  }
}

//Test Code
describe("Foo", function () {
  it("should do something if the dependency returns true", function () {
    var foo = new Foo();
    //how do I stub and/or redefine the "i_want_stubbed" method here?
    var result_if_true = foo.do_something_interesting();
    expect(true).toEqual(result_if_true);
  });
});

The gist of the question is: how do I redefine an instance method in javascript?


Your Foo.do_something_interesting demonstrates a common feature of untestable / hard-to-test code, namely that it uses "new" and has a dependency that is not passed-in. Ideally, you would have:

do_something_interesting = function(dependency) {
// ...
}

In the above, it is much easier to replace your dependency with a Mock. That said, you can use the properties of a given instance or of the prototype to replace bits and pieces. For example:

 Foo.prototype.CanYouMockMe = function() {};
 Foo.prototype.CanYouMockMe.prototype.i_want_stubbed = function() {
     console.log("I'm a stub");
 };

You can save the properties before you overwrite them, and then restore those properties after your test case, to make it possible to run multiple tests in isolation of each other. That said, making dependencies explicit is a big win both for testability and for making your APIs more flexible / configurable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜