Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I spyOn Typescript getters and setters?

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.

like image 948
dot_zero Avatar asked Nov 06 '15 21:11

dot_zero


People also ask

How do you define a getter and setter in TypeScript?

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.

Can we use getter and setter in TypeScript?

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.

What can I use instead of getters and setters?

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.

How do you get spyOn property 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").


1 Answers

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();
});
like image 154
Laoujin Avatar answered Oct 01 '22 02:10

Laoujin