[英]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.