Files
API/test/feedback/salesforce.service.test.ts
T
Paddy 3ea9e630ed Migrate the API to native ESM and vitest; pin Node 26
Prep PR for the admin auth module (docs/plan-admin-auth.md step 1).
better-auth 1.7 ships ESM only, so the API moves off CommonJS:

- "type": "module", module nodenext, target ES2024, .js suffixes on all
  relative imports, require('mariadb'|'cors') replaced by imports, and
  export= packages (winston, app-root-path, bcrypt) consumed via default
  imports. The logger now uses appRoot.path explicitly.
- TypeScript 5.9, @types/node 26, tslint removed. Node 26 pinned via
  engines and .nvmrc (Plesk runs 26).
- Jest 28 + ts-jest replaced by vitest 5. Eight test files depend on
  hoisted module mocks with static imports and resetModules + require,
  which Jest's ESM mode does not support; vitest keeps them nearly
  verbatim. Coverage via @vitest/coverage-v8 (lcov), Sonar generic report
  via vitest-sonar-reporter, so sonar-project.properties is unchanged.
  vitest.config.ts sets FEEDBACK_IP_SALT so the suite passes without a
  local .env.
- dotenv 8 -> 16 and axios 0.24 -> 1.x: their old typings are not
  resolvable under nodenext.
- autoCommit: false dropped from the pool configs; it is not a mariadb
  connector option and was silently ignored.

tsc clean, 96/96 tests green, compiled app boots and serves /, /docs and
CORS under Node ESM.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 16:02:26 +02:00

203 lines
8.4 KiB
TypeScript

// The module under test caches its OAuth token at module scope (see
// salesforce.service.ts's `cachedToken`), so every test resets the module
// registry for a clean cache. Every mocked dependency (axios, Feedback.db,
// the logger) is re-imported after the reset rather than referenced from a
// top-level import, so the test always holds the same instance the service
// under test resolves. Mocked modules survive vi.resetModules(), so their
// mock state is reset explicitly in beforeEach.
import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
vi.mock('axios');
vi.mock('../../src/models/feedback/Feedback.db.js', () => ({
NachklangFeedbackDB: {getConnection: vi.fn()}
}));
vi.mock('../../src/middleware/logger.js', () => ({
__esModule: true,
default: {info: vi.fn(), error: vi.fn()}
}));
const SIGNUP_ROW = {
signup_id: 7,
first_name: 'Erika',
last_name: 'Mustermann',
email: 'erika@example.com',
event_name: 'Sommerkonzert 2026'
};
const makeConn = (rows: any[]) => ({
query: vi.fn().mockResolvedValue(rows),
end: vi.fn().mockResolvedValue(undefined)
});
// Re-imports every mocked dependency (see the note above) and returns the
// live references plus the service under test.
const freshImports = async () => {
const axios: any = (await import('axios')).default;
const {NachklangFeedbackDB} = await import('../../src/models/feedback/Feedback.db.js');
const logger = (await import('../../src/middleware/logger.js')).default;
const {syncNewsletterSignup} = await import('../../src/models/feedback/integrations/salesforce.service.js');
return {axios, mockGetConnection: NachklangFeedbackDB.getConnection as Mock, logger, syncNewsletterSignup};
};
const ORIGINAL_ENV = {...process.env};
describe('syncNewsletterSignup - disabled mode', () => {
beforeEach(() => {
vi.resetModules();
vi.resetAllMocks();
process.env = {...ORIGINAL_ENV, SALESFORCE_ENABLED: 'false'};
});
it('logs the payload it would send and does not touch the network or write to the DB', async () => {
const {axios, mockGetConnection, logger, syncNewsletterSignup} = await freshImports();
const conn = makeConn([SIGNUP_ROW]);
mockGetConnection.mockResolvedValue(conn);
await syncNewsletterSignup(7);
expect(logger.info).toHaveBeenCalledWith(
expect.stringContaining('would have sent'),
expect.objectContaining({
signupId: 7,
payload: {firstName: 'Erika', lastName: 'Mustermann', email: 'erika@example.com', eventName: 'Sommerkonzert 2026'}
})
);
expect(axios.post).not.toHaveBeenCalled();
// One read connection only - no UPDATE issued, since the row's
// sync_status is already 'SKIPPED' from the insert.
expect(mockGetConnection).toHaveBeenCalledTimes(1);
});
it('logs and returns without calling the network when the signup row does not exist', async () => {
const {axios, mockGetConnection, logger, syncNewsletterSignup} = await freshImports();
mockGetConnection.mockResolvedValue(makeConn([]));
await syncNewsletterSignup(999);
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('not found'), {signupId: 999});
expect(axios.post).not.toHaveBeenCalled();
});
});
describe('syncNewsletterSignup - enabled mode', () => {
beforeEach(() => {
vi.resetModules();
vi.resetAllMocks();
process.env = {
...ORIGINAL_ENV,
SALESFORCE_ENABLED: 'true',
SALESFORCE_API_URL: 'https://example.my.salesforce.com',
SALESFORCE_CLIENT_ID: 'client-id',
SALESFORCE_CLIENT_SECRET: 'client-secret'
};
});
it('fetches a token, posts the signup, and marks the row SENT with the returned record id', async () => {
const {axios, mockGetConnection, syncNewsletterSignup} = await freshImports();
const updateConn = makeConn([]);
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
if (url.endsWith('/services/apexrest/newsletter/signup')) {
return Promise.resolve({data: {status: 'PENDING_CONFIRMATION', salesforceObject: 'Lead', salesforceRecordId: '00Q1234', created: true}});
}
throw new Error(`unexpected url ${url}`);
});
await syncNewsletterSignup(7);
expect(axios.post).toHaveBeenCalledWith(
'https://example.my.salesforce.com/services/oauth2/token',
expect.any(String),
expect.objectContaining({headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
);
expect(axios.post).toHaveBeenCalledWith(
'https://example.my.salesforce.com/services/apexrest/newsletter/signup',
{firstName: 'Erika', lastName: 'Mustermann', email: 'erika@example.com', eventName: 'Sommerkonzert 2026'},
expect.objectContaining({headers: {Authorization: 'Bearer tok-1'}})
);
expect(updateConn.query).toHaveBeenCalledWith(expect.stringContaining("sync_status = 'SENT'"), ['00Q1234', 7]);
});
it('reuses the cached token across two calls instead of fetching twice', async () => {
const {axios, mockGetConnection, syncNewsletterSignup} = await freshImports();
mockGetConnection
.mockResolvedValueOnce(makeConn([SIGNUP_ROW]))
.mockResolvedValueOnce(makeConn([]))
.mockResolvedValueOnce(makeConn([SIGNUP_ROW]))
.mockResolvedValueOnce(makeConn([]));
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
return Promise.resolve({data: {status: 'PENDING_CONFIRMATION', salesforceObject: 'Lead', salesforceRecordId: '00Q1234', created: true}});
});
await syncNewsletterSignup(7);
await syncNewsletterSignup(7);
const tokenCalls = axios.post.mock.calls.filter(([url]: [string]) => url.endsWith('/services/oauth2/token'));
expect(tokenCalls).toHaveLength(1);
});
it('retries once with a fresh token on a 401, then succeeds', async () => {
const {axios, mockGetConnection, syncNewsletterSignup} = await freshImports();
const updateConn = makeConn([]);
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
let tokenFetches = 0;
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) {
tokenFetches += 1;
return Promise.resolve({data: {access_token: `tok-${tokenFetches}`}});
}
if (url.endsWith('/services/apexrest/newsletter/signup')) {
if (tokenFetches === 1) {
const err: any = new Error('Unauthorized');
err.response = {status: 401, data: {message: 'Session expired'}};
return Promise.reject(err);
}
return Promise.resolve({data: {status: 'PENDING_CONFIRMATION', salesforceObject: 'Lead', salesforceRecordId: '00Q9999', created: true}});
}
throw new Error(`unexpected url ${url}`);
});
await syncNewsletterSignup(7);
expect(tokenFetches).toBe(2);
expect(updateConn.query).toHaveBeenCalledWith(expect.stringContaining("sync_status = 'SENT'"), ['00Q9999', 7]);
});
it('marks the row FAILED with the error message on a non-401 error, without throwing', async () => {
const {axios, mockGetConnection, logger, syncNewsletterSignup} = await freshImports();
const updateConn = makeConn([]);
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
const err: any = new Error('Internal error');
err.response = {status: 500, data: {message: 'The newsletter signup could not be processed.'}};
return Promise.reject(err);
});
await expect(syncNewsletterSignup(7)).resolves.toBeUndefined();
expect(updateConn.query).toHaveBeenCalledWith(
expect.stringContaining("sync_status = 'FAILED'"),
['The newsletter signup could not be processed.', 7]
);
expect(logger.error).toHaveBeenCalledWith('syncNewsletterSignup failed', expect.objectContaining({signupId: 7}));
});
it('marks the row FAILED with a clear message when client credentials are not configured', async () => {
process.env.SALESFORCE_CLIENT_ID = '';
const {mockGetConnection, syncNewsletterSignup} = await freshImports();
const updateConn = makeConn([]);
mockGetConnection.mockResolvedValueOnce(makeConn([SIGNUP_ROW])).mockResolvedValueOnce(updateConn);
await syncNewsletterSignup(7);
expect(updateConn.query).toHaveBeenCalledWith(
expect.stringContaining("sync_status = 'FAILED'"),
[expect.stringContaining('SALESFORCE_CLIENT_ID'), 7]
);
});
});