Search code examples
javascripttestingrequirejsjasminespy

Javascript Jasmine Testing: Prevent tested function to call function from object that was created within tested function


I want to test a Javascript function with Jasmine that has a structure like this:

showEditUser: function (...) {
    // more code here...
    var editUserView = new EditUserView();
    // more code here...
    editUserView.generate(...);
}

editUserView.generate() causes an error. That does not matter because I don't want to test it. But how can I prevent it from being called?

EditUserView is a RequireJS Module that extends another Module called BaseView. The function generate() is defined in BaseView. There are other Modules that extend BaseView and I want all of them not to call generate while testing. How can I do that with Jasmine? It seems not to be possible with spyOn(...).and.callFake() because I don't have the editUserView Object when calling the function. Is there kind of a static way to tell Jasmine to callFake() the function generate in BaseView?


Solution

  • There is no "nice" way to solve this with jasmine. I think, to take a BaseView viewObj as parameter is a nicer coding style. It will reduce the dependencies of the method. So it don't have to know the specific BaseView-class, he will simply need a viewObj that has a generate-method.

    showEditUser: function(..., viewObj) {
        // ...
        viewObj.generate(...);
    }
    

    Then you could create a ViewMock and put it into that function like this:

    var viewMock = {};
    viewMock.generate = jasmine.createSpy('generate() spy');
    

    Then you will call it this way:

    showEditUser(..., viewMock);
    

    EDIT: Here is a similar question