I'm learning OOJS and I want to use pattern getters and setters (for study), but I don't understand why my test doesn't catch the error when I use the set. If I use without set, just only a method, it works.
In my test the empty field is validated and this is not expected, the correct thing is to return the empty field error
My class:
export default class Category {
constructor(name) {
this._name = name;
}
set name(name) {
if (isEmpty(name) || isNull(name))
throw new Error(`category field needs to be filled`);
this._name = name;
}
get name() {
return this._name;
}
}
categoryDAO
import Category from "../models/Category.js";
export default class CategoryDAO {
constructor() {
this._list = [];
}
add(category) {
if (!(category instanceof Category)) {
throw new Error("the object is not of type category");
}
if (this._list.some((c) => c.name === category.name)) {
throw new Error("category has been created");
}
this._list.push(category);
}
}
test
try {
const categoryDAO = new CategoryDAO();
const category1 = new Category("Devops");
const category2 = new Category("Devops");
categoryDAO.add(category1);
categoryDAO.add(category2);
console.log(`saved ${category1.name}`);
console.log(`saved ${category2.name}`);
} catch (err) {
console.log(`WRG ${err}`);
}
try {
const categoryDAO = new CategoryDAO();
const category1 = new Category(" ");
categoryDAO.add(category1);
console.log(`saved ${category1.name}`);
} catch (err) {
console.log(`WRG ${err}`);
}
validate.js
export const mailFormat = /^([\w-]\.?)+@([\w-]+\.)+([A-Za-z]{2,4})+$/g;
export const notEmpty = (value) => (value === " " ? false : true);
export const isEmpty = (value) => !notEmpty(value);
export const isNull = (value) => value === null;
export const maxLength = (length) => (value) => value.length < length;
Thanks for any help