spyOn() takes two parameters: the first parameter is the name of the object and the second parameter is the name of the method to be spied upon. It replaces the spied method with a stub, and does not actually execute the real method. The spyOn() function can however be called only on existing methods.
Using Jasmine spies to mock code Jasmine spies are easy to set up. 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.
spyOn() spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code.
From Jasmine doc: By chaining the spy with and. callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation.
In Jasmine versions 3.0 and above you can use withArgs
describe('my fn', function() {
it('gets user name and ID', function() {
spyOn(externalApi, 'get')
.withArgs('abc').and.returnValue('Jane')
.withArgs('123').and.returnValue(98765);
});
});
For Jasmine versions earlier than 3.0 callFake
is the right way to go, but you can simplify it using an object to hold the return values
describe('my fn', function() {
var params = {
'abc': 'Jane',
'123': 98765
}
it('gets user name and ID', function() {
spyOn(externalApi, 'get').and.callFake(function(myParam) {
return params[myParam]
});
});
});
Depending on the version of Jasmine, the syntax is slightly different:
.andCallFake(fn)
.and.callFake(fn)
Resources:
You could also use $provide
to create a spy. And mock using and.returnValues
instead of and.returnValue
to pass in parameterised data.
As per Jasmine docs: By chaining the spy with
and.returnValues
, all calls to the function will return specific values in order until it reaches the end of the return values list, at which point it will return undefined for all subsequent calls.
describe('my fn', () => {
beforeEach(module($provide => {
$provide.value('externalApi', jasmine.createSpyObj('externalApi', ['get']));
}));
it('get userName and Id', inject((externalApi) => {
// Given
externalApi.get.and.returnValues('abc','123');
// When
//insert your condition
// Then
// insert the expectation
}));
});
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