Search code examples
javascripttestingautomated-testse2e-testingtestcafe

Testcafe - Test command line argument outside test case


As I'm getting familiar with Testcafe, I'm trying to use a command line argument to give the user more information on how to run tests. For that reason, I'm using the minimist package.

However, I cannot print or use any variables outside the test cases. Please find below my code.

import { Selector } from 'testcafe';
import minimist from 'minimist';

const args = minimist(process.argv.slice(2));
const env = args.env;

console.log('*** A SAMPLE CONSOLE OUTPUT ***'); // does not print

fixture `Getting Started`
  .page `http://devexpress.github.io/testcafe/example`;

test('My first test', async t => {
  console.log('*** ANOTHER SAMPLE CONSOLE OUTPUT ***'); // prints
  await t
    .typeText('#developer-name', 'John Smith')
    .wait(1000)
    .click('#submit-button')

    // Use the assertion to check if the actual header text is equal to the expected one
    .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');
});

I want to write an if statement that checks if env === '' or use a default argument.

How can I accomplish this?


Solution

  • However, I cannot print or use any variables outside the test cases.  

    Please use a programming way to run TestCafe. I've changed you code example (test.js) and created a file that runs TestCafe programmatically (run.js). Put these files into a folder and perform command 'node run.js --env value' in your terminal. Then you will see the following output:

    '*** A SAMPLE CONSOLE OUTPUT ***'
    Getting Started
    value
    
    test.js
    
    import { Selector } from 'testcafe';
    import minimist from 'minimist';
    
    const args = minimist(process.argv.slice(2));
    const env = args.env;
    
    console.log('*** A SAMPLE CONSOLE OUTPUT ***'); 
    
    fixture `Getting Started`
      .page `http://devexpress.github.io/testcafe/example`;
    
    test('My first test', async t => {
      console.log(env); // prints
      await t
        .typeText('#developer-name', 'John Smith')
        .wait(1000)
        .click('#submit-button')
        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');
    });
    
    run.js
    const createTestCafe = require('testcafe');
    let runner           = null;
    
    createTestCafe('localhost', 1337, 1338, void 0, true)
        .then(testcafe => {
            runner = testcafe.createRunner();
        })
        .then(() => {
             return runner
                .src('test.js')
                .browsers('chrome')
                .run()
                .then(failedCount => {
                    console.log(`Finished. Count failed tests:${failedCount}`);
                    process.exit(failedCount)
                });
        })
        .catch(error => {
            console.log(error);
            process.exit(1);
        });