I am trying to write private attributes in a Typescript class but they are fully accessible and can be overwritten by my jest tests. Am I doing something wrong or is this normal?
This question received an answer related to using #
instead of private
, but isn't this pure javascript? Shouldn't Typescript's private
keyword prevent me from overwriting or even accessing this value?
My class:
export class TodoItemID {
public constructor() {
return "TodoItem#" + Math.random() * 100000000000000000;
}
}
class TodoItem {
private id: TodoItemID = new TodoItemID();
private name: Required<String>;
private description: String;
private completed: boolean;
private todoListId: TodoListID;
constructor(name: Required<String>) {
this.name = name;
}
}
export default TodoItem;
My test (note: both tests pass):
import TodoItem, { TodoItemID } from "./";
describe("TodoItem", () => {
let todoItem;
const todoItemName = "Todo Item for testing purposes";
beforeEach(() => {
todoItem = new TodoItem(todoItemName);
});
it("should have an id", () => {
expect(todoItem.id).toBeInstanceOf(TodoItemID);
todoItem.id = "blabla";
expect(todoItem.id).toBe("blabla");
});
});