testcafe

Dynamic data are not available in test files - testcafe - 3.6.0


I want to set project config which is unique in every test run, by creating new environment instance before tests run. It will contains for expample, base url to web page, api url e.t.c. I will use it in a lot of files, with tests, hooks e.t.c, so it should be available everywhere.

I created projectConfig file:

projectConfig.js

const config = {
    apiUrl: '',
    baseUrl: '',
    baseUrl2: ''
}

export const setConfig = (newConfig) => {
    console.log('setConfig')
    config.apiUrl = newConfig.apiUrl;
    config.baseUrl = newConfig.baseUrl;
    config.baseUrl2 = newConfig.baseUrl2;
}

export default config;

And I'm setting this config before create testcafe runner

runner.js

(async () => {
    // create new environment instance
    const newConfig = { // In real life it's getting from api
        apiUrl: 'http://localhost:3000',
        baseUrl: 'http://localhost:3001',
        baseUrl2: 'http://localhost:3002',
    };

    setConfig(newConfig);

    const testcafe = await createTestCafe();
    const runner = testcafe.createRunner()
    ...
})();

And I checked where I have access to config data

testConfig.js

import config from "../projectConfig";

console.log('test file')
console.log(config)

fixture('Getting Started')
    .page(config.baseUrl)
    .beforeEach(async () => {
        console.log('beforeEach')
        console.log(config)
    }
);

test('My 1st test', async ()  => {
    console.log('test body')
    console.log(config)
});

Config is not avaliable in test file so it can't open page because the url is empty string. It's not avaiable also in fixure/test local hooks and test body.

It's available only in global hooks (I checked testRun.before and test.before)


Solution

  • You can use userVariables to pass additional data to your tests. You can define them in the configuration file or in your runner code: createTestCafe()

    runner.js

    (async () => {
        // create new environment instance
        const newConfig = { // In real life it's getting from api
            apiUrl: 'http://localhost:3000',
            baseUrl: 'http://localhost:3001',
            baseUrl2: 'http://localhost:3002',
        };
    
        setConfig(newConfig);
    
        const testcafe = await createTestCafe({userVariables: { config }});
        const runner = testcafe.createRunner()
        ...
    })();
    

    testConfig.js

    import { userVariables } from "testcafe";
    
    const config = userVariables.config;
    
    console.log('test file')
    console.log(config)
    
    fixture('Getting Started')
        .page(config.baseUrl)
        .beforeEach(async () => {
            console.log('beforeEach')
            console.log(config)
        }
    );
    
    test('My 1st test', async ()  => {
        console.log('test body')
        console.log(config)
    });