2

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?

Garrarufa
  • 1,145
  • 1
  • 12
  • 29
  • I'm not familiar with Jasmine, but using Sinon I guess one would use stubs. http://sinonjs.org/docs/#stubs – Edo Apr 29 '15 at 12:03
  • i think jasmine only uses spies. is this the same thing as stubs? I also think it is not possible to solve this problem with spies. – Garrarufa Apr 29 '15 at 12:37
  • A spy is not the same as a stub. A spy only observes calls to the original function, whereas a stub would replace the original function entirely. I guess you could use sinon within jasmine, not sure how messy that would get though. – Edo Apr 29 '15 at 12:47

1 Answers1

1

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

Community
  • 1
  • 1
marcel
  • 2,967
  • 1
  • 16
  • 25