Create Custom Test Actions

Article Summary

Define custom test actions in a JavaScript configuration file:

module.exports = {
  customActions: {
   async makeCoffee (args) {
        await this.click(args);
    }, 
  }
};

Include custom methods in your tests alongside other TestController methods:

test('Test with a custom action', async t => {
    await t.click()
        .customActions.makeCoffee()
        .click();
})

Define a new custom action

Use a Javascript configuration file to define custom actions. Place action functions inside the customActions configuration file property.

  • TestCafe test actions are asynchronous. Use the asyncawait syntax to define test actions.
  • Use the this keyword to access the TestController object and its methods inside custom action definitions.
  • Separate different action definitions with a comma.
  • If you want to include custom actions in action chains, make sure the function does not return a value.
module.exports = {
  customActions: {
   async makeCoffee (args) {
        await this.click(args);
    }, 
  }
};

Execute custom actions

Place a JavaScript configuration file with custom action definitions (.testcaferc.js or .testcaferc.cjs) in the test launch directory. If you store the configuration file elsewhere, specify the path with the --config-file command line option or the configFile option of the TestCafe Runner API.

Custom actions are methods of the TestController object. You can use them anywhere the TestController object is available.

test('Test with a custom action', async t => {
    await t.click();
    await t.customActions.makeCoffee();
    await t.click();
})

If the action does not return a value, you can chain it:

test('Test with a custom action', async t => {
    await t.click().customActions.makeCoffee().click();
})

Use custom actions with TypeScript

Create type definitions for each custom action. Store definitions in a separate file:

//definitions.d.ts
import 'testcafe';
declare global {
    interface CustomActions {
        click: (selector: Selector) => TestControllerPromise
        getSelectorInnerText: (selector: Selector) => Promise<string>
    }
}

Include the file with the definitions when you run your tests:

//.testcaferc.js
src:           ["definitions.d.ts", "tests"],