When I unit test my getters are setters for Typescript, I cannot find a way to spy on those getters and setters. Instead, the object immediately gets evaluated. I am using Jasmine to unit test.
Use the get and set keywords to define getters and setters in TypeScript. Getters enable us to bind a property to a function that is called when the property is accessed, whereas setters bind a property to a function that is called on attempts to set the property.
In TypeScript, there are two supported methods getter and setter to access and set the class members. In this very short article, I'm going to show you Typescript Accessor which includes getters/setters method. Actually, getters and setters are nothing but a way for you to provide access to the properties of an object.
You may use lombok - to manually avoid getter and setter method. But it create by itself. The using of lombok significantly reduces a lot number of code.
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").
spyOnProperty
is now available in Jasmine:
const foop = {
get value() {},
set value(v) {}
};
it('can spy on getter', () => {
spyOnProperty(foop, 'value', 'get').and.returnValue(1);
expect(foop.value).toBe(1);
});
it('and on setters', () => {
const spiez = spyOnProperty(foop, 'value', 'set');
foop.value = true;
expect(spiez).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