Files
ManagerAccount/test/helpers/asset-route-fixture.js
2026-09-23 15:54:40 +07:00

89 lines
3.1 KiB
JavaScript

const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { createRequire } = require('node:module');
const serverPath = path.resolve(__dirname, '../../backend/server.js');
const serverSource = fs.readFileSync(serverPath, 'utf8');
const serverRequire = createRequire(serverPath);
// Run the real route handlers with an isolated pool so these regressions do not
// need credentials or alter a developer's inventory.
function createFixture(answer = () => ({ recordset: [] })) {
const queries = [];
const transactions = [];
class Request {
constructor(transaction) {
this.transaction = transaction;
this.inputs = {};
}
input(name, _type, value) {
this.inputs[name] = value;
return this;
}
async query(query) {
const call = { query, inputs: this.inputs, transaction: this.transaction };
queries.push(call);
return answer(call);
}
}
class Transaction {
constructor() { transactions.push(this); }
async begin() { this.begun = true; }
async commit() { this.committed = true; }
async rollback() { this.rolledBack = true; }
}
const sql = { ...serverRequire('mssql'), Request, Transaction };
const module = { exports: {} };
const context = {
require(name) { return name === 'mssql' ? sql : serverRequire(name); },
module,
exports: module.exports,
__dirname: path.dirname(serverPath),
__filename: serverPath,
Buffer,
URL,
console,
process: {
env: {
...process.env,
NODE_ENV: 'test',
DATA_ENCRYPTION_SECRET: 'test-only-archive-key-with-more-than-32-characters'
},
on() {}
},
testPool: { request: () => new Request() }
};
vm.runInNewContext(`${serverSource}
pool = testPool;
getUserDisplayNameById = async () => 'Borrower A';
safeCreateSystemNotification = async () => {};
ensureDepartmentExists = async () => {};
syncAssetDepartmentsFromInventory = async () => {};
syncAssetProjectsFromInventory = async () => {};
`, context, { filename: serverPath });
async function invoke(method, routePath, overrides = {}) {
const route = module.exports.app.router.stack.find(layer => (
layer.route?.path === routePath && layer.route.methods[method]
)).route;
const handler = route.stack.at(-1).handle;
const req = {
params: {}, query: {}, body: {},
user: { UserId: 1, Role: 'asset', FullName: 'Borrower A' },
...overrides
};
const response = {
statusCode: 200,
status(value) { this.statusCode = value; return this; },
json(value) { this.body = value; return this; }
};
await handler(req, response);
return response;
}
return { invoke, queries, transactions };
}
module.exports = { createFixture };