@sync-in/server
Version:
The secure, open-source platform for file storage, sharing, collaboration, and sync
98 lines (97 loc) • 3.76 kB
JavaScript
/*
* Copyright (C) 2012-2025 Johan Legrand <johan.legrand@sync-in.com>
* This file is part of Sync-in | The open source file sync and share solution
* See the LICENSE file for licensing details
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
const _testing = require("@nestjs/testing");
const _contextmanagerservice = require("./context-manager.service");
describe(_contextmanagerservice.ContextManager.name, ()=>{
let contextManager;
beforeAll(async ()=>{
const module = await _testing.Test.createTestingModule({
providers: [
_contextmanagerservice.ContextManager
]
}).compile();
contextManager = module.get(_contextmanagerservice.ContextManager);
});
it('should be defined', ()=>{
expect(contextManager).toBeDefined();
});
// Test helpers to reduce repetition and keep strong typing in one place
const getKey = (key)=>contextManager.get(key);
const runWithContext = (ctx, fn)=>contextManager.run(ctx, fn);
describe('Context access', ()=>{
it('get() should return undefined when no context is active', ()=>{
// Using a fake key ensures we don’t rely on a specific ContextStore shape
expect(getKey('')).toBeUndefined();
});
it('run() should expose context within the callback and surface return value', ()=>{
const ctx = {
userId: 'u1',
requestId: 'r1'
};
const value = runWithContext(ctx, ()=>{
expect(getKey('userId')).toBe('u1');
expect(getKey('requestId')).toBe('r1');
return 123;
});
expect(value).toBe(123);
});
});
describe('Context lifecycle', ()=>{
it('should restore to no context after run() completes', ()=>{
const ctx = {
userId: 'u2'
};
runWithContext(ctx, ()=>{
expect(getKey('userId')).toBe('u2');
});
expect(getKey('userId')).toBeUndefined();
});
it('should support nested contexts and restore the previous one after inner run()', ()=>{
const outer = {
userId: 'outer'
};
const inner = {
userId: 'inner'
};
runWithContext(outer, ()=>{
expect(getKey('userId')).toBe('outer');
runWithContext(inner, ()=>{
expect(getKey('userId')).toBe('inner');
});
// After inner completes, outer should be visible again
expect(getKey('userId')).toBe('outer');
});
// After outer completing, no context should be active
expect(getKey('userId')).toBeUndefined();
});
});
describe('Async propagation', ()=>{
it('should propagate context across microtasks (Promise)', async ()=>{
const ctx = {
userId: 'async-user'
};
await runWithContext(ctx, async ()=>{
await Promise.resolve();
expect(getKey('userId')).toBe('async-user');
});
});
it('should propagate context across timers (setTimeout)', async ()=>{
const ctx = {
requestId: 'req-timer'
};
await runWithContext(ctx, async ()=>{
await new Promise((resolve)=>setTimeout(()=>{
expect(getKey('requestId')).toBe('req-timer');
resolve();
}, 0));
});
});
});
});
//# sourceMappingURL=context-manager.service.spec.js.map