Keywords: Jasmine | Unit Testing | Spies
Abstract: This article explains how to modify Jasmine spies to return different values based on arguments in unit tests. It covers the use of withArgs in Jasmine 3.0+ and callFake for older versions, with code examples and best practices.
Introduction
When unit testing JavaScript code with Jasmine, it is common to mock external dependencies using spies. A frequent requirement is to have a spy return different values based on the arguments passed to the function. This article explores two primary methods to achieve this: using withArgs in Jasmine 3.0 and above, and using callFake for older versions.
Using the withArgs Method
In Jasmine versions 3.0 and later, the withArgs method provides a clean way to specify return values for specific arguments. Here is an example:
spyOn(externalApi, 'get')
.withArgs('abc').and.returnValue('Jane')
.withArgs('123').and.returnValue(98765);
This approach is more readable and directly ties the arguments to their corresponding return values.
Using the callFake Method
For Jasmine versions earlier than 3.0, callFake is the appropriate method. It allows you to define a custom function that returns values based on arguments. A simplified version uses an object to map parameters to return values:
var params = {
'abc': 'Jane',
'123': 98765
};
spyOn(externalApi, 'get').and.callFake(function(myParam) {
return params[myParam];
});
Note the syntax differences: in Jasmine 1.3.1, it is .andCallFake(fn), and in 2.0, it is .and.callFake(fn).
Version Compatibility
It is important to check your Jasmine version. withArgs is available from version 3.0 onwards. For compatibility with older projects, callFake is the fallback. Always refer to the official Jasmine documentation for the latest syntax and features.
Conclusion
Modifying Jasmine spies based on arguments is straightforward with the right methods. Use withArgs for modern Jasmine setups to enhance code clarity, and rely on callFake for backward compatibility. This ensures effective and maintainable unit tests.