Javascript Testing With JasmineBDD: Overriding Spy Return In Nested Describe
Posted about 2 years ago on April 30, 2011
I have been using Jasmine’s SpyOn method to stub results for dependencies within methods.
My goal was to override these stubbed methods in nested describe contexts. My first thought was to redefine the Spy (stub) using the spyOn method. This fails with an obvious error message: “Error: xyz has already been spied upon…”. What I needed to understand was that the spy object had already been created in the outer describe block, so I needed to simply re-use it. Instead of trying to re-declare the spy, just use the same object and use the andReturn() method to redefine the return value of the stubbed method.
Here is an illustration:
describe("Outer describe", function() {
beforeEach(function() {
//Setup Stuff
spyOn(someObject, 'someMethod').andReturn(3);
});
it("...", function() {
//Test here
});
describe("Inner Describe", function() {
beforeEach(function() {
//Nested setup stuff
//Fails: "Error: someMethod has already been spied upon"
spyOn(someObject, 'someMethod').andReturn(0);
//Passes: The object has already been initialized as a spy, so use the existing spy object and tell it to change the return value.
someObject.someMethod.andReturn(0);
});
it("...", function() {
objectUnderTest.someMethod();
expect($("input#some-element")).toBeDisabled();
});
});
});
Comments
New Comment