Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jasmine to spy on variables in a function

Suppose I have a function as follows

function fun1(a) {
  var local_a = a;
  local_a += 5;
  return local_a/2;
}

Is there a way to test for the value of local_a being what it should be (for example in the first line of code)? I'm a bit new to Jasmine, so am stuck. Thanks in advance.

like image 557
Chetter Hummin Avatar asked Mar 08 '12 14:03

Chetter Hummin


People also ask

How do you make a spy for function in Jasmine?

In Jasmine, you can do anything with a property spy that you can do with a function spy, but you may need to use different syntax. Use spyOnProperty to create either a getter or setter spy. it("allows you to create spies for either type", function() { spyOnProperty(someObject, "myValue", "get").

How do you mock a variable in Jasmine?

First define a variable like this: let authService: AuthService; Then once the testbed has been set up, set this to the actual service being used by the TestBed inside the last beforeEach() : authService = TestBed.

What does Jasmine spyOn do?

Jasmine spies are used to track or stub functions or methods. Spies are a way to check if a function was called or to provide a custom return value. We can use spies to test components that depend on service and avoid actually calling the service's methods to get a value.

How do you mock a method in Jasmine?

Using Jasmine spies to mock code You set the object and function you want to spy on, and that code won't be executed. In the code below, we have a MyApp module with a flag property and a setFlag() function exposed. We also have an instance of that module called myApp in the test.


1 Answers

Not really. You can do the following though:

Test the result of fun1():

expect(fun1(5)).toEqual(5);

Make sure it's actually called (useful if it happens through events) and also test the result:

var spy = jasmine.createSpy(window, 'fun1').andCallThrough();
fire_event_calling_fun1();
expect(spy).toHaveBeenCalled();
expect(some_condition);

Really reproduce the whole function inspecting intermediate results:

var spy = jasmine.createSpy(window, 'fun1').andCallFake(function (a) {
  var local_a = a;
  expect(local_a).toEqual(a);
  local_a += 5;
  expect(local_a).toEqual(a+5);
  return local_a/2;
});
fun1(42);
expect(spy).toHaveBeenCalled();
like image 171
ggozad Avatar answered Sep 20 '22 05:09

ggozad