繁体   English   中英

如何模拟 Jest 中的只读属性?

[英]How to mock a read-only property in Jest?

我有一个 function,它将大写字母的字符串转换为大写字母前带有破折号的字符串,并将字符串变为小写。

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');
    });
});

但我收到以下错误: Cannot assign to 'type' because it is a read-only property

我怎样才能模拟道具类型来覆盖 function formattedType()

您可以使用 static 方法Object.defineProperty直接在 object 上定义新属性或修改 object 上的现有属性。

例如:

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');
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM