I have the following function that must clone a class (this
) and return a new clone of it. In this case the class is called Tag
clone(): Tag {
// Create a new instance of Tag
let newItem = new Tag();
newItem.id = this.id;
newItem.userId = this.userId;
newItem._tag = this._tag;
newItem._color = this._color;
// deep copy of Date objects
newItem._createdOn = new Date(this._createdOn.valueOf());
newItem._updatedOn = new Date(this._updatedOn.valueOf());
newItem._archivedOn = this._archivedOn ? new Date(this._archivedOn.getTime()) : undefined;
return newItem;
}
In the accompanying Unit Test, I test for equality in the clone
describe("clone", () => {
it("should create an identical copy of the tag", () => {
const userId = uuidv4();
let tag = fakeTag(userId);
const clone = tag.clone();
expect(clone.id).toEqual(tag.id);
expect(clone.userId).toEqual(tag.userId);
expect(clone.tag).toEqual(tag.tag);
expect(clone.color).toEqual(tag.color);
// Errors appear here
expect(clone.updatedOn.getTime()).toBeCloseTo(tag.updatedOn.getTime(), 2);
expect(clone.createdOn.getTime()).toBeCloseTo(tag.createdOn.getTime(), 2);
});
});
Everything works until
expect(clone.updatedOn.getTime()).toBeCloseTo(tag.updatedOn.getTime(), 2);
This is the test output
expect(received).toBeCloseTo(expected, precision)
Expected: 1728162863968
Received: 1728241129040
Expected precision: 2
Expected difference: < 0.005
Received difference: 78265072
I have also tried the following to no avail
expect(clone.updatedOn.getTime()).toEqual(tag.updatedOn.getTime());
I have read quite a few Date clone S/O texts, but I don’t get why I’m still getting this error. There is something I’m doing wrong