0

Here is the sample code:

App.controller('Crtl', ["$scope", function ($scope) {

$scope.FetchDetail = function () {
    var accNum = this.customer.accNo;
    GetAccountDetails(accNum);
}; }]);

I am new to Jasmine and right now I am writing unit tests for my angular code. Here I created FetchDetail function which then calls javascript function GetAccountDetails(accNum).

How can I test this sample using Jasmine.

3
  • Where is GetAccountDetails() defined? Is it injected? Commented Nov 20, 2014 at 5:54
  • It is defined in another Javascript file. Commented Nov 20, 2014 at 6:05
  • So it is a global? You are better off injecting it and then you can stub it, but you can put a spy on it. I will add it as an answer. Commented Nov 20, 2014 at 6:12

1 Answer 1

1

It depends if you need to stub it (i.e. capture and change its behaviour) or if it is enough to spy on it (watch it). Either way, you would be better off injecting it, so you can control it.

I have been using sinon http://sinonjs.org quite happily.

If you want to spy on it, i.e. watch its behaviour without changing it, then before calling it, you would do

var spy = sinon.spy(GetAccountDetails);

Then you can check if it was called, or what arguments were, etc.

spy.calledOnce === true; // if it was called once
spy.called === true; // if it was called at all
spy.firstCall.args[0]; // first argument to first call
// etc. - check out the docs

If you need to stub it, use the stub functionality, where you can then define what the behaviour should be. You get all of the spying features, but also control what the response is. However, it is hard to spy on a global, as opposed to a method of an existing object.

Sign up to request clarification or add additional context in comments.

3 Comments

A pleasure. If you get stuck with it, post another q. FYI, important track is spy.reset() which resets the call count. I use it in beforeEach() so that each invocation I know exactly how many calls there should be and what args.
@deitch Should GetAccountDetails be defined on scope? I have it defined on the this of the same controller and Karma gives a ReferenceError: GetAccountDetails is not defined error!! Please suggest.
@Dravidian unsure. If it is defined on this, then the OP's example wouldn't work as it would need to be this.GetAccountDetails(). In general, I avoid globals as much as is humanly possible (and a wee bit more), and have tried to be as functional as possible (no this when I can get away with it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.