Home > Enterprise >  Testcafe with variable server port
Testcafe with variable server port

Time:09-10

I'm starting a web server as part of the test runner initialization. The server picks any free port, so port numbers are not constant over multiple test runs. How can I access the port number in my tests?

My testcafe config

module.exports = {
    hooks: {
        testRun: {
            before: async ctx => {
                let appServerPort = await startLocalServer();
                // ???
            }
        }
    }
}

A test

test('my test', async (t) => {
    await t.expect(true).ok();

}).page(`localhost:${ ??? }`);

CodePudding user response:

You have at least 2 ways of doing this:

  1. You can create a global variable and set the server port to it. After that, you can use this variable everywhere you need.
  2. Set the port to ctx, get it from t.testRun.testRunCtx, and navigate to the desired page with t.navigateTo. For example:

Config

module.exports = {
    hooks: {
        testRun: {
            before: async ctx => {
                const appServerPort = await startLocalServer();

                ctx.port = appServerPort;
            }
        }
    }
}

Test

test('my test', async (t) => {
    await t.navigateTo(\`localhost:${ t.testRun.testRunCtx.port }\`)
    await t.expect(true).ok();
});
  • Related