Testcafe如何在测试中获取动态分配的服务器端口?
在TestCafe中获取随机启动的服务器端口号
方法一:利用TestRun上下文(推荐)
TestCafe的testRun.before钩子中的ctx对象可存储自定义数据,测试代码能通过测试控制器的testRun.testRunCtx访问这些数据,这种方式能保证测试上下文的隔离性,不会干扰其他测试运行。
- 修改TestCafe配置文件,将端口号存入上下文:
module.exports = { hooks: { testRun: { before: async ctx => { let appServerPort = await startLocalServer(); // 把端口号存入ctx对象 ctx.appPort = appServerPort; } } } }
- 在测试代码中动态获取端口并导航:
test('my test', async (t) => { // 从上下文取出端口号 const appPort = t.testRun.testRunCtx.appPort; // 动态导航到服务器地址 await t.navigateTo(`http://localhost:${appPort}`); await t.expect(true).ok(); });
方法二:使用环境变量
如果需要在.page()静态配置中直接使用端口,可以通过环境变量传递,但要注意环境变量是全局的,多实例并行测试时可能出现冲突。
- 在钩子中设置环境变量:
module.exports = { hooks: { testRun: { before: async ctx => { let appServerPort = await startLocalServer(); // 将端口号存入环境变量 process.env.APP_PORT = appServerPort.toString(); } } } }
- 在测试代码中读取环境变量:
test('my test', async (t) => { await t.expect(true).ok(); }).page(`http://localhost:${process.env.APP_PORT}`);
内容的提问来源于stack exchange,提问作者Army Noodles
相关产品推荐
相关产品推荐

