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.
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").
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With