Deeply freeze object

This commit is contained in:
2026-08-10 02:30:55 +00:00
parent a075594683
commit 78311487a4
4 changed files with 94 additions and 7 deletions
+44
View File
@@ -89,6 +89,49 @@ const testEventEmitterEmitReturnsTrueWithListeners = (): void => {
expect(hasListeners).toBe(true);
};
/**
* Tests that emitted events cannot be mutated.
*/
const testEventEmitterEmittedEventsCannotBeMutated = async (): Promise<void> => {
vi.useFakeTimers();
try {
const emitter = new EventEmitter<TestEvents>();
const listener = vi.fn();
const payload = { nested: { value: 1 } };
emitter.on('nested', listener, 100);
// Arm the debounce timer with the current payload.
emitter.emit('nested', payload);
// Mutate the original object while the timer is still pending.
payload.nested.value = 999;
await vi.advanceTimersByTimeAsync(100);
// The listener must receive a snapshot from emit time, not the mutated value.
expect(listener).toHaveBeenCalledOnce();
// Expect the listener to have received the original payload object without any mutations
expect(listener).toHaveBeenCalledWith({
nested: {
value: 1,
},
});
// Expect the payload object to have been mutated
expect(payload).toStrictEqual({
nested: {
value: 999,
},
});
} finally {
vi.useRealTimers();
vi.restoreAllMocks();
}
};
/**
* Tests that the off callback returned by on() removes the listener.
*/
@@ -514,6 +557,7 @@ const runTests = async (): Promise<void> => {
test('EventEmitter: only calls listeners for the emitted event type', testEventEmitterCallsOnlyMatchingListeners);
test('EventEmitter: returns false when emitting with no listeners', testEventEmitterEmitReturnsFalseWithNoListeners);
test('EventEmitter: returns true when emitting with listeners', testEventEmitterEmitReturnsTrueWithListeners);
test('EventEmitter: emitted events cannot be mutated', testEventEmitterEmittedEventsCannotBeMutated);
test('EventEmitter: stops calling a listener after its off callback is invoked', testEventEmitterOffCallbackRemovesListener);
test('EventEmitter: removes a listener when off is called with the same reference', testEventEmitterOffRemovesListenerByReference);
test(