【发布时间】:2021-06-05 01:55:47
【问题描述】:
我有一个使用 Express 运行后端 RESTful API 的 TypeScript 项目。它在设计上非常重对象,因此可以在运行时和测试服务类时实例化大量类并相互注入。
我们有一套适用于所有服务类别的良好测试。但是,我们有一个 index.ts 将这一切结合在一起,而这目前已经脱离了测试自动化。我正在考虑各种方法来测试它,以便端点和轻量级控制器免受回归的影响。 (与其列出我所有可能导致问题过于宽泛的想法,我现在将专注于一个具体的想法)。
让我展示一个我的前端控制器的示例 (src/index.ts):
/* Lots of imports here */
const app = express();
app.use(express.json());
app.use(cors());
app.options('*', cors());
/* Lots of settings from env vars here */
// Build some modules
const verificationsTableName = 'SV-Verifications';
const verificationsIndexName = 'SV-VerificationsByUserId';
const getVerificationService = new GetVerification(
docClient,
verificationsTableName,
verificationsIndexName,
timer,
EXPIRY_LENGTH,
);
const writeVerifiedStatusService = new WriteVerifiedStatus(
docClient,
verificationsTableName,
timer,
getVerificationService,
);
/* Some code omitted for brevity */
// Create some routes
GetVerificationController.createRoutes(getVerificationService, app);
FinishVerificationController.createRoutes(finishVerificationService, app);
addPostStartVerification(startVerification, app);
IsVerifiedController.createValidationRoutes(di2.createOverallFeatureFlagService(), getVerificationService, app);
app.listen(PORT, () => {
console.log(`⚡️[server]: Server is running at http://localhost:${PORT}`);
});
你明白了——类是使用依赖注入组装的,我们从环境变量中获取一些配置,然后启动 HTTP 侦听器。需要注意的主要一点是该文件不包含或导出任何类或函数。
我想在 Jest 测试套件中运行此文件,如下所示:
describe('Test endpoint wiring', () => {
beforeEach(() => {
// Set up lots of env vars
// How to run `src/index.ts` here?
});
afterEach(() => {
// Tear down the server here
});
test('First endpoint test', () => {
// Run a test against an endpoint
});
});
我想知道是否有某种await exec('node command') 我可以在这里做?我希望它在后台运行,以便在服务器启动后运行测试。理想情况下,这将构成 Jest 中异步线程的一部分,但如果这不可能,那么直接生成进程可能就可以了。
如果有一种可靠的方法可以在每次测试结束时终止它,那就太好了(我想保持 PID 并发送停止信号是可以的)。
修改index.ts 不是不可能的(实际上我打算将所有这些 DI 构造填充到一个类中,以便可以使用简单的方法继承来替换部分以进行测试)。但我想先探索一下这个无更改选项。
【问题讨论】:
标签: typescript jestjs background-process