Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

test(backend:infrastructure): improve coverage

johaven101362c0c6d8
diff --git a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts b/backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts
index 9cb3f45e..1bd65708 100644
--- a/backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts
+++ b/backend/src/authentication/services/auth-methods/auth-method-ldap.service.spec.ts
@@ -105,12 +105,6 @@ describe(AuthMethodLdapService.name, () => {
configuration.auth.ldap = { servers: ['ldap://localhost:389'], loginAttribute: 'uid', baseDN: 'ou=people,dc=example,dc=org', filter: '' }
})
- afterEach(() => {
- // Ensure per-test spies/mocks are reset
- jest.restoreAllMocks()
- jest.clearAllMocks()
- })
-
it('should be defined', () => {
expect(authMethodLdapService).toBeDefined()
expect(usersManager).toBeDefined()
diff --git a/backend/src/infrastructure/context/services/context-manager.service.spec.ts b/backend/src/infrastructure/context/services/context-manager.service.spec.ts
new file mode 100644
index 00000000..40642067
--- /dev/null
+++ b/backend/src/infrastructure/context/services/context-manager.service.spec.ts
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2012-2025 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { Test, TestingModule } from '@nestjs/testing'
+import { ContextManager } from './context-manager.service'
+import type { ContextStore } from '../interfaces/context-store.interface'
+
+describe(ContextManager.name, () => {
+ let contextManager: ContextManager
+
+ beforeAll(async () => {
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [ContextManager]
+ }).compile()
+
+ contextManager = module.get<ContextManager>(ContextManager)
+ })
+
+ it('should be defined', () => {
+ expect(contextManager).toBeDefined()
+ })
+
+ // Test helpers to reduce repetition and keep strong typing in one place
+ const getKey = <K extends keyof ContextStore>(key: K): ContextStore[K] => contextManager.get(key) as ContextStore[K]
+
+ const runWithContext = <T>(ctx: Partial<ContextStore>, fn: () => T): T => contextManager.run(ctx as ContextStore, fn) as unknown as T
+
+ 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('' as keyof ContextStore)).toBeUndefined()
+ })
+
+ it('run() should expose context within the callback and surface return value', () => {
+ const ctx = { userId: 'u1', requestId: 'r1' } as Partial<ContextStore>
+
+ const value = runWithContext<number>(ctx, () => {
+ expect(getKey('userId' as keyof ContextStore)).toBe('u1')
+ expect(getKey('requestId' as keyof ContextStore)).toBe('r1')
+ return 123
+ })
+
+ expect(value).toBe(123)
+ })
+ })
+
+ describe('Context lifecycle', () => {
+ it('should restore to no context after run() completes', () => {
+ const ctx = { userId: 'u2' } as Partial<ContextStore>
+
+ runWithContext<void>(ctx, () => {
+ expect(getKey('userId' as keyof ContextStore)).toBe('u2')
+ })
+
+ expect(getKey('userId' as keyof ContextStore)).toBeUndefined()
+ })
+
+ it('should support nested contexts and restore the previous one after inner run()', () => {
+ const outer = { userId: 'outer' } as Partial<ContextStore>
+ const inner = { userId: 'inner' } as Partial<ContextStore>
+
+ runWithContext<void>(outer, () => {
+ expect(getKey('userId' as keyof ContextStore)).toBe('outer')
+
+ runWithContext<void>(inner, () => {
+ expect(getKey('userId' as keyof ContextStore)).toBe('inner')
+ })
+
+ // After inner completes, outer should be visible again
+ expect(getKey('userId' as keyof ContextStore)).toBe('outer')
+ })
+
+ // After outer completing, no context should be active
+ expect(getKey('userId' as keyof ContextStore)).toBeUndefined()
+ })
+ })
+
+ describe('Async propagation', () => {
+ it('should propagate context across microtasks (Promise)', async () => {
+ const ctx = { userId: 'async-user' } as Partial<ContextStore>
+
+ await runWithContext<Promise<void>>(ctx, async () => {
+ await Promise.resolve()
+ expect(getKey('userId' as keyof ContextStore)).toBe('async-user')
+ })
+ })
+
+ it('should propagate context across timers (setTimeout)', async () => {
+ const ctx = { requestId: 'req-timer' } as Partial<ContextStore>
+
+ await runWithContext<Promise<void>>(ctx, async () => {
+ await new Promise<void>((resolve) =>
+ setTimeout(() => {
+ expect(getKey('requestId' as keyof ContextStore)).toBe('req-timer')
+ resolve()
+ }, 0)
+ )
+ })
+ })
+ })
+})
diff --git a/backend/src/infrastructure/mailer/mailer.service.spec.ts b/backend/src/infrastructure/mailer/mailer.service.spec.ts
new file mode 100644
index 00000000..42a4d1b1
--- /dev/null
+++ b/backend/src/infrastructure/mailer/mailer.service.spec.ts
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2012-2025 Johan Legrand <[email protected]>
+ * This file is part of Sync-in | The open source file sync and share solution
+ * See the LICENSE file for licensing details
+ */
+
+import { Test, TestingModule } from '@nestjs/testing'
+import { ConfigService } from '@nestjs/config'
+import { PinoLogger } from 'nestjs-pino'
+import nodemailer from 'nodemailer'
+import { Mailer } from './mailer.service'
+import { MailerConfig } from './mailer.config'
+
+// Mocks
+jest.mock('nodemailer')
+const createTransportMock = {
+ verify: jest.fn().mockResolvedValue(true),
+ sendMail: jest.fn().mockResolvedValue(true)
+}
+;(nodemailer.createTransport as jest.Mock).mockReturnValue(createTransportMock)
+
+describe(Mailer.name, () => {
+ let module: TestingModule
+ let mailer: Mailer
+ let configService: ConfigService
+ let logger: PinoLogger
+
+ const mailerConfig: MailerConfig = {
+ host: 'smtp.example.com',
+ port: 587,
+ auth: { user: 'user', pass: 'pass' },
+ secure: false,
+ sender: '[email protected]',
+ debug: false,
+ logger: false
+ }
+
+ const initModule = async (config: MailerConfig | undefined) => {
+ module = await Test.createTestingModule({
+ providers: [
+ Mailer,
+ { provide: ConfigService, useValue: { get: jest.fn().mockReturnValue(config) } },
+ {
+ provide: PinoLogger,
+ useValue: {
+ setContext: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ info: jest.fn(),
+ assign: jest.fn(),
+ logger: { level: 'info' }
+ }
+ }
+ ]
+ }).compile()
+
+ mailer = module.get<Mailer>(Mailer)
+ configService = module.get<ConfigService>(ConfigService)
+ logger = module.get<PinoLogger>(PinoLogger)
+ }
+
+ beforeAll(async () => {
+ await initModule(undefined)
+ })
+
+ it('should be defined', () => {
+ expect(module).toBeDefined()
+ expect(mailer).toBeDefined()
+ expect(configService).toBeDefined()
+ expect(logger).toBeDefined()
+ })
+
+ it('should not initialize transporter if config is absent', () => {
+ expect(mailer['transport']).toBeUndefined()
+ expect(nodemailer.createTransport).not.toHaveBeenCalled()
+ })
+
+ it('should initialize secure transport with no secure port', async () => {
+ await initModule({ ...mailerConfig, secure: true })
+ expect(mailer['configuration'].secure).toBe(false)
+ await initModule({ ...mailerConfig, port: 25, secure: true, logger: true, debug: true })
+ expect(mailer['configuration'].secure).toBe(false)
+ const loggerWarnSpy = jest.spyOn(logger, 'warn')
+ expect(loggerWarnSpy).toHaveBeenCalledWith(expect.stringMatching(/has been disabled/i))
+ loggerWarnSpy.mockClear()
+ })
+
+ it('should set mailer availability to false if transport failed', async () => {
+ createTransportMock.verify.mockRejectedValueOnce(new Error('Mail Server down'))
+ await initModule(mailerConfig)
+ expect(mailer.available).toBe(false)
+ const loggerErrorSpy = jest.spyOn(logger, 'error')
+ expect(loggerErrorSpy).toHaveBeenCalledWith(expect.stringMatching(/mail server down/i))
+ loggerErrorSpy.mockClear()
+ })
+
+ it('should initialize transporter if config exists', async () => {
+ // Reinstantiate the module and the services
+ await initModule(mailerConfig)
+ expect(nodemailer.createTransport).toHaveBeenCalledWith(
+ expect.objectContaining({
+ host: mailerConfig.host,
+ port: mailerConfig.port,
+ auth: mailerConfig.auth,
+ secure: mailerConfig.secure
+ }),
+ expect.objectContaining({
+ from: mailerConfig.sender
+ })
+ )
+ })
+
+ it('should send mails when available', async () => {
+ mailer.available = true
+ await mailer.sendMails([{ to: '[email protected]', subject: 'Hello', html: 'world' }])
+ expect(createTransportMock.sendMail).toHaveBeenCalledWith(expect.objectContaining({ to: '[email protected]' }))
+ createTransportMock.sendMail.mockClear()
+ })
+
+ it('should not send mails when not available', async () => {
+ mailer.available = false
+ await mailer.sendMails([{ to: '[email protected]', subject: 'Hello', html: 'world' }])
+ expect(createTransportMock.sendMail).not.toHaveBeenCalled()
+ createTransportMock.sendMail.mockClear()
+ })
+
+ it('should continue sending remaining mails if one send fails and log error', async () => {
+ mailer.available = true
+ // first call rejects, second resolves
+ createTransportMock.sendMail.mockRejectedValueOnce(new Error('SMTP down')).mockResolvedValueOnce(true)
+ await mailer.sendMails([
+ { to: '[email protected]', subject: 'One', html: '1' },
+ { to: '[email protected]', subject: 'Two', html: '2' }
+ ])
+
+ expect(createTransportMock.sendMail).toHaveBeenCalledTimes(2)
+ expect(createTransportMock.sendMail).toHaveBeenNthCalledWith(1, expect.objectContaining({ to: '[email protected]' }))
+ expect(createTransportMock.sendMail).toHaveBeenNthCalledWith(2, expect.objectContaining({ to: '[email protected]' }))
+ createTransportMock.sendMail.mockClear()
+ })
+})
diff --git a/backend/src/infrastructure/mailer/mailer.service.ts b/backend/src/infrastructure/mailer/mailer.service.ts
index ee243fcd..2a5784a6 100644
--- a/backend/src/infrastructure/mailer/mailer.service.ts
+++ b/backend/src/infrastructure/mailer/mailer.service.ts
@@ -8,14 +8,15 @@ import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { PinoLogger } from 'nestjs-pino'
import nodemailer from 'nodemailer'
+import type { Logger as NodeMailLogger } from 'nodemailer/lib/shared'
import { MailDefaultsTransport, MailProps, MailTransport } from './interfaces/mail.interface'
import { MailerConfig } from './mailer.config'
@Injectable()
export class Mailer {
+ public available: boolean = false
private readonly transporter: nodemailer.Transporter
private readonly configuration: MailerConfig
- public available: boolean = false
constructor(
private configService: ConfigService,
@@ -23,24 +24,25 @@ export class Mailer {
) {
this.logger.setContext(Mailer.name.toUpperCase())
this.configuration = this.configService.get<MailerConfig>('mail')
- if (this.configuration) {
- this.logger.logger.level = this.configuration.debug ? 'debug' : 'info'
- if (this.configuration.secure && (this.configuration.port === 587 || this.configuration.port === 25)) {
- this.logger.warn(`Secure transport has been disabled due to use of port : ${this.configuration.port}`)
- this.configuration.secure = false
- }
- this.transporter = nodemailer.createTransport(
- {
- host: this.configuration.host,
- port: this.configuration.port,
- auth: this.configuration.auth,
- secure: this.configuration.secure,
- logger: this.configuration.logger ? (this.logger as any) : false
- } satisfies MailTransport,
- { from: this.configuration.sender, tls: { rejectUnauthorized: false } } satisfies MailDefaultsTransport
- )
- this.verify().catch((e: Error) => this.logger.error(e))
+ if (!this.configuration) {
+ return
+ }
+ this.logger.logger.level = this.configuration.debug ? 'debug' : 'info'
+ if (this.configuration.secure && (this.configuration.port === 587 || this.configuration.port === 25)) {
+ this.logger.warn(`Secure transport has been disabled due to use of port : ${this.configuration.port}`)
+ this.configuration.secure = false
}
+ this.transporter = nodemailer.createTransport(
+ {
+ host: this.configuration.host,
+ port: this.configuration.port,
+ auth: this.configuration.auth,
+ secure: this.configuration.secure,
+ logger: this.configuration.logger ? (this.logger as NodeMailLogger & any) : false
+ } satisfies MailTransport,
+ { from: this.configuration.sender, tls: { rejectUnauthorized: false } } satisfies MailDefaultsTransport
+ )
+ this.verify().catch(this.logger.error)
}
async sendMails(mails: MailProps[]) {