I am trying to test if a local method ( method1 ) is being called from another method( method2 ). I tried something like this but it does not work as the method1() still has the original definition . The code snippet looks like this:
var ClassA = function () {
var method1 = function () {
console.log('method1');
};
var method2 = function () {
method1();
};
return {method1: method1, method2: method2}
}
Test case:
it("should call method1 when method2 is called", function () {
var objectA = new ClassA();
spyOn(objectA, 'method1').andCallThrough;
objectA.method2();
expect(objectA, 'method1').toHaveBeenCalled();
});
Tried overriding method1 to without any success:
objectA.method1 = jasmine.createSpy('aSpy').andCallThrough();
When you call new ClassA() you invoke the ClassA function and get a new object with the related prototype. This means that when you spyOn(ClassA, "doSomething") you're not setting up a spy on the object returned by the new call, but on a possible doSomething function on the ClassA function itself. You should be able to do something like:
it("calls method1", function() {
var originalConstructor = ClassA,
spiedObj;
spyOn(window, 'ClassA').and.callFake(function() {
spiedObj = new originalConstructor();
spyOn(spiedObj, 'method1');
return spiedObj;
});
method2();
expect(spiedObj.method1).toHaveBeenCalled();
});
Please let me know if this works if not we can discuss more.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.