Files
kita-planer/tests/mail-transport.test.cjs

56 lines
4.2 KiB
JavaScript

/* eslint-disable @typescript-eslint/no-require-imports -- Execute the installed SDK and real TypeScript mail adapter. */
const { test, before, after }=require('node:test');const assert=require('node:assert/strict');
const fs=require('node:fs'),path=require('node:path'),vm=require('node:vm'),ts=require('typescript');
let prisma; // The mail adapter never accesses a database.
function loader(overrides = {}) {
const cache = new Map();
function load(file) {
file = path.resolve(file);
if (cache.has(file)) return cache.get(file).exports;
const mod = { exports: {} }; cache.set(file, mod);
const code = ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, esModuleInterop: true },
fileName: file,
}).outputText;
const req = spec => {
if (Object.hasOwn(overrides, spec)) return overrides[spec];
if (spec === 'server-only') return {};
if (spec === '@/lib/prisma') return { prisma };
if (spec === 'next/headers') return { headers: async () => new Headers() };
if (spec === 'next/cache') return { revalidatePath() {} };
if (spec === 'next/navigation') return { redirect(url) { throw new Error(`REDIRECT:${url}`); }, notFound() { throw new Error('NOT_FOUND'); } };
if (spec.startsWith('@/') || spec.startsWith('.')) {
const target = spec.startsWith('@/') ? path.resolve('src', spec.slice(2)) : path.resolve(path.dirname(file), spec);
for (const suffix of ['.ts', '.tsx', '/index.ts']) if (fs.existsSync(target + suffix)) return load(target + suffix);
}
return require(spec);
};
vm.runInThisContext(`(function(require,module,exports){${code}\n})`, { filename: file })(req, mod, mod.exports);
return mod.exports;
}
return load;
}
const originalFetch=global.fetch;const saved=Object.fromEntries(['RESEND_API_KEY','EMAIL_FROM','NODE_ENV'].map(k=>[k,process.env[k]]));let send;
before(()=>{process.env.RESEND_API_KEY='re_test_not_real';process.env.EMAIL_FROM='Test <test@example.invalid>';process.env.NODE_ENV='test';send=loader()('src/lib/mail.ts').sendAppEmail;});
after(()=>{global.fetch=originalFetch;for(const [k,v] of Object.entries(saved)){if(v===undefined)delete process.env[k];else process.env[k]=v;}});
const input={to:'recipient@example.invalid',subject:'Test',react:'Test',idempotencyKey:'stable-job'};
test('SDK receives the stable key and an AbortSignal on the actual fetch call',async()=>{
let captured;global.fetch=async(_url,options)=>{captured=options;return new Response(JSON.stringify({id:'test-id'}),{status:200});};
assert.equal((await send(input)).success,true);assert.ok(captured.signal instanceof AbortSignal);assert.match(new Headers(captured.headers).get('Idempotency-Key'),/^stable-job\/[a-f0-9]{64}$/);
});
test('Transport timeout aborts the pending fetch rather than merely abandoning its promise',async()=>{
let aborted=false;global.fetch=async(_url,options)=>new Promise((_resolve,reject)=>options.signal.addEventListener('abort',()=>{aborted=true;reject(options.signal.reason);},{once:true}));
const keepAlive=setTimeout(()=>{},1000);try{assert.equal((await send({...input,timeoutMs:20})).success,false);assert.equal(aborted,true);}finally{clearTimeout(keepAlive);}
});
test('Array recipients have distinct stable keys and duplicate addresses are removed',async()=>{
const keys=[];global.fetch=async(_url,options)=>{keys.push(new Headers(options.headers).get('Idempotency-Key'));return new Response(JSON.stringify({id:'test'}),{status:200});};
const message={...input,to:['one@example.invalid','two@example.invalid','one@example.invalid']};await send(message);await send(message);
assert.equal(keys.length,4);assert.notEqual(keys[0],keys[1]);assert.equal(keys[0],keys[2]);assert.equal(keys[1],keys[3]);
});
test('Corrected message payload receives a new version without changing stable retries',async()=>{
const keys=[];global.fetch=async(_url,options)=>{keys.push(new Headers(options.headers).get('Idempotency-Key'));return new Response(JSON.stringify({id:'test'}),{status:200});};
await send(input);await send(input);await send({...input,react:'Corrected dates'});assert.equal(keys[0],keys[1]);assert.notEqual(keys[1],keys[2]);
});