Army Noodles
Army Noodles

Reputation: 112

Testcafe with variable server port

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:${ ??? }`);

Upvotes: 0

Views: 246

Answers (1)

Alexey Popov
Alexey Popov

Reputation: 1047

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();
});

Upvotes: 1

Related Questions