3

I have a function which transform a string with Uppercase to a string with dash before the uppercase and it makes the string lowercase.

formattedType() {
        // Adds a dash before the uppercase and make everything lowercase
        const type = this.props.type?.split(/(?=[A-Z])/).join("-").toLowerCase();
        return type;
}

describe("formattedType method", () => {
    it("should transform the string into lowercase with a dash as seperator", () => {
        // given
        FormTrack.prototype.props.type= 'testOption';
        

        // when
        const actualResult = FormTrack.prototype.formattedFormType();

        // then
        expect(actualResult).toBe('test-option');
    });
});

But I'm getting the error below: Cannot assign to 'type' because it is a read-only property

How can I mock the props type to cover the function formattedType()

Can
  • 553
  • 1
  • 9
  • 29
  • that's why I'm asking here. – Can Dec 19 '21 at 11:09
  • Then show us what have you found and then why it isn't help you. For example, link other stackoverflow post to your post, with each you can comment why it can't apply to your situation: https://stackoverflow.com/questions/52437082/assign-value-to-readonly-properties-from-methods-called-by-the-constructor – Tan Nguyen Dec 19 '21 at 11:55
  • For lack of a better solution, you can typecast it so that typescript does not complain: (FormTrack.prototype.props.type as string) = 'testOption'; – gaurav5430 Jul 28 '22 at 18:23

1 Answers1

1

You can use the static method Object.defineProperty to define a new property directly on an object or modifies an existing property on an object.

For example:

describe("formattedType method", () => {
    it("should transform the string into lowercase with a dash as seperator", () => {
        // given
        Object.defineProperty(FormTrack.prototype.props, 'type', {value: 'testOption' });

        // when
        const actualResult = FormTrack.prototype.formattedFormType();

        // then
        expect(actualResult).toBe('test-option');
    });
});