Files
API/test/common/salesforce.client.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

126 lines
4.7 KiB
TypeScript

// salesforce.client caches the OAuth token at module scope, so every test
// resets the module registry for a clean cache and re-imports axios + the
// module under test after the reset (same approach as
// test/feedback/salesforce.service.test.ts). Mocked modules survive
// vi.resetModules(), so mock state is reset explicitly in beforeEach.
import {vi, describe, it, expect, beforeEach, afterAll} from 'vitest';
vi.mock('axios');
const freshImports = async () => {
const axios: any = (await import('axios')).default;
const {salesforceApexRestPost, salesforceEnabled} = await import('../../src/common/salesforce.client.js');
return {axios, salesforceApexRestPost, salesforceEnabled};
};
const ORIGINAL_ENV = {...process.env};
const ENABLED_ENV = {
...ORIGINAL_ENV,
SALESFORCE_ENABLED: 'true',
SALESFORCE_API_URL: 'https://example.my.salesforce.com',
SALESFORCE_CLIENT_ID: 'client-id',
SALESFORCE_CLIENT_SECRET: 'client-secret'
};
beforeEach(() => {
vi.resetModules();
vi.resetAllMocks();
process.env = {...ENABLED_ENV};
});
afterAll(() => {
process.env = {...ORIGINAL_ENV};
});
describe('salesforceEnabled', () => {
it('is true only when SALESFORCE_ENABLED === "true"', async () => {
process.env.SALESFORCE_ENABLED = 'true';
expect((await freshImports()).salesforceEnabled()).toBe(true);
vi.resetModules();
process.env.SALESFORCE_ENABLED = 'false';
expect((await freshImports()).salesforceEnabled()).toBe(false);
});
});
describe('salesforceApexRestPost', () => {
it('fetches a token, posts to the given Apex REST path, and returns the response body', async () => {
const {axios, salesforceApexRestPost} = await freshImports();
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
return Promise.resolve({data: {ok: true}});
});
const result = await salesforceApexRestPost('/services/apexrest/email/send', {to: 'x@example.com'});
expect(result).toEqual({ok: true});
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/email/send',
{to: 'x@example.com'},
expect.objectContaining({headers: {Authorization: 'Bearer tok-1'}})
);
});
it('reuses the cached token across calls instead of fetching twice', async () => {
const {axios, salesforceApexRestPost} = await freshImports();
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
return Promise.resolve({data: {}});
});
await salesforceApexRestPost('/services/apexrest/email/send', {});
await salesforceApexRestPost('/services/apexrest/email/send', {});
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, salesforceApexRestPost} = await freshImports();
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 (tokenFetches === 1) {
const err: any = new Error('Unauthorized');
err.response = {status: 401};
return Promise.reject(err);
}
return Promise.resolve({data: {ok: true}});
});
const result = await salesforceApexRestPost('/services/apexrest/email/send', {});
expect(result).toEqual({ok: true});
expect(tokenFetches).toBe(2);
});
it('does not retry on a non-401 error and rethrows it', async () => {
const {axios, salesforceApexRestPost} = await freshImports();
axios.post.mockImplementation((url: string) => {
if (url.endsWith('/services/oauth2/token')) return Promise.resolve({data: {access_token: 'tok-1'}});
const err: any = new Error('Server error');
err.response = {status: 500};
return Promise.reject(err);
});
await expect(salesforceApexRestPost('/services/apexrest/email/send', {})).rejects.toThrow('Server error');
const endpointCalls = axios.post.mock.calls.filter(([url]: [string]) => url.endsWith('/email/send'));
expect(endpointCalls).toHaveLength(1);
});
it('throws a clear error when client credentials are not configured', async () => {
process.env.SALESFORCE_CLIENT_ID = '';
const {salesforceApexRestPost} = await freshImports();
await expect(salesforceApexRestPost('/services/apexrest/email/send', {})).rejects.toThrow('SALESFORCE_CLIENT_ID');
});
});