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()
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');
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.