DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Integrate Cucumber in Playwright With Java
  • WebDriverIO Integration With Cucumber
  • Advanced Error Handling in JavaScript
  • Storybook: A Developer’s Secret Weapon

Trending

  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • How Can Developers Drive Innovation by Combining IoT and AI?
  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. TestCafe Integration With Cucumber

TestCafe Integration With Cucumber

By 
Mohit Kulshreshtha user avatar
Mohit Kulshreshtha
·
Jun. 03, 20 · Analysis
Likes (5)
Comment
Save
Tweet
Share
20.1K Views

Join the DZone community and get the full member experience.

Join For Free

TestCafe: A Node.JS Tool to Automate End-To-End Testing

It is an open-source tool, that allows us to write automation tests in JavaScript or TypeScript languages, execute the tests, and publish the test results.

It does not use Selenium Webdriver and plugins to run the tests in browsers. It can create stable tests, perform assertions, launch concurrent tests, use PageObject to create readable tests, and also include the tests in CI/CD pipeline.

It supports automatic waits for page loads and uses web proxy for test execution. It can be used with any IDE that supports development using Node.js (most popular being VSCode IDE).

Cucumber

It is a tool that supports Behavior Driven Development (BDD). It allows us to write scenarios from the user’s perspective in plain English language, making it easy to understand for all the stakeholders like business analysts, product owners, developers, testers, and end-users.

The users can write acceptance test scenarios to describe the behavior of the application. It utilizes the Gherkin keywords like Given, When, Then to write the test scenarios in simple and understandable language.

Cucumber also helps in mapping the test scenarios steps to the actual test code. Cucumber scripts are supported in multiple languages, including JavaScript.

Use Case

A project team is using TestCafe’s powerful scripting engine to design automation test scenarios and perform end-to-end testing of web applications.

Now, the client has asked to implement BDD and test the applications from the user’s perspective. The project team must use a BDD framework like Cucumber, which allows them to write the business flows in plain English language and map them to the actual test code.

The project must design a framework that accepts test scenarios from the user, map them to the automation test code, design and execute the test scenarios, and provide interactive test reports.

Such a framework can be designed by integrating the Cucumber scenarios with the TestCafe automation tests. This helps in achieving automated end-to-end testing of applications from the user’s perspective.

Let's look at how to implement the integration of TestCafe with Cucumber.

cucumber

The above block diagram represents the model to perform the integration of Cucumber with TestCafe.

Cucumber + TestCafe Selectors and Actions

Feature Files User can write the test scenarios in plain language using gherkin keywords
Step Definitions Methods can be generated for each test step in the feature file scenarios and updated with TestCafe Actions for automating the application
Page Objects UI elements can be defined with their selectors in the page object files. This improves readability and is one of the most popular design patterns in test automation

TestCafe Test Controller Object Handling with asynchronous calls

The main objective is to inject the Test Controller object into the context of each cucumber step definition method. rquellh has provided a solution to this problem by using Test Controller Holder, Cucumber World, and Hooks.

Cucumber World

An integral part of Cucumber JavaScript and is an isolated context for each cucumber scenario, exposed to hooks and steps

Hooks It creates a dummy test file. This test file captures the test controller object and passes it back to Test Controller Holder. It waits for setting up of the test controller object asynchronously, and then adds the object to Cucumber World scope with the help of Test Controller Holder
Test Controller Holder It holds the object, until the Cucumber script execution finishes and then, the object is free

Installation and Pre-Requisites:

  • Download Node.js from https://nodejs.org/en/download/ and install in the machine
  • Download VSCode (Visual Studio Code) from https://code.visualstudio.com/ and install in the machine
  • The test application is https://devexpress.github.io/testcafe/example/

Steps to integrate Cucumber With TestCafe

  1. Create a new project folder with the name: Cucumber_TestCafe_Project at the desired location in the machine (ex. C:\Users\Public)
  2. Open VSCode IDE and open the project folder Cucumber_TestCafe_Project
  3. Let us change the icon pack in VSCode to view beautiful and distinctive icons for different file formats
    • Navigate to extensions, search for VSCode Great Icons and click the "Install' button
    • Open the command palette by using the shortcut CTRL + SHIFT + P
    • Type "Preferences: File Icon Theme"
    • Select "VSCode Great Icons" from the populated list
  4. In the project folder, create a new file with the name: package.json
  5. Implement the following package.json:
JSON
 




xxxxxxxxxx
1
11


 
1
{
2
  "name": "integrate-testcafe-cucumber",
3
  "description": "An integration of TestCafe and Cucumber-JS",
4
  "dependencies": {
5
    "cucumber": "^5.1.0",
6
    "cucumber-html-reporter": "^2.0.3",
7
    "npm": "^6.0.0",
8
    "testcafe": "^1.1.0"
9
  }
10
}



The above code of the package.json has configured the dependencies that are required in the project.

6. Execute the command “npm install” in the VSCode Shell Terminal to install all the dependencies packages (node_modules) in the project folder

7. Setup Cucumber Language Support: Use an extension “Cucumber (Gherkin) Full Support” to enable syntax highlighting, auto-completion for CucumberJS feature files, and step definitions. This eases the work of maintaining the cucumber files in VSCode

  • In the project folder, create a new folder with the name: .vscode
  • In this folder, create a new file the name: settings.json
  • Implement the following settings.json:
JSON
 




xxxxxxxxxx
1
11


 
1
/* Plugin settings for Cucumber related files like feature file and step definitions file
2
This allows auto-completion of gherkin commands and assist in designing the cucumber files
3
*/
4

          
5
{
6
    "cucumberautocomplete.steps": [
7
        "features/step_definitions/*.js"
8
    ],
9
    "cucumberautocomplete.syncfeatures": "features/*.feature",
10
    "cucumberautocomplete.strictGherkinCompletion": true
11
}



  • Navigate to extensions, search for Cucumber (Gherkin) Full Support and click the "Install' button

Create a Cucumber Feature File

8. In the project folder, create a new folder with the name: features

9. In this folder, create a new file with the name: example_page.feature

10. Here is the code for the feature file: 

Gherkin
 




xxxxxxxxxx
1
16


 
1
# Add your test scenarios in the Cucumber Feature file.
2

          
3
# Since, we are using the Cucumber (Gherkin) Full Support extension in VSCode,
4
# please notice the syntax highlighting and completion, while writing the scenarios.
5

          
6
Feature: Example Page User Details
7

          
8
Scenario: The one where user enters all the details on Example Page
9
 Given user navigates to the example form page
10
    When user enters "John Doe" in the name field
11
    And user selects "JavaScript API" as TestCafe Interface
12
    And user checks the I have tried TestCafe checkbox
13
    And user enters "Good Tool" in feedback description field
14
    And user clicks on Submit button
15
    Then "Welcome John Doe" message appears
16

          



The above code represents the user scenario for entering all the details on the Example page and expecting a Welcome message from the application.

 11. The project structure looks like below:

project structure

12. Execute the command “./node_modules/.bin/cucumber-js.cmd” in the VSCode Shell Terminal to run the cucumber scenarios and generate the step definitions for the scenario steps

Create cucumber step definitions file

13. Inside the features folder, create a new folder with the name: step_definitions

14. In this folder, create a new file with the name: example_page_steps.js

15. Copy the generated step definitions from the terminal and paste in the example_page_steps.js file. Also, make the step definition functions async

16. Here is the code for the step definition file: 

JavaScript
 




xxxxxxxxxx
1
28


 
1
Given('user navigates to the example form page', async function () {
2
    
3
});
4

          
5
When('user enters {string} in the name field', async function (string) {
6
  
7
});
8

          
9
When('user selects {string} as TestCafe Interface', async function (string) {
10
  
11
});
12

          
13
When('user checks the I have tried TestCafe checkbox', async function () {
14
  
15
});
16

          
17
When('user enters {string} in feedback description field', async function (string) {
18
  
19
});
20

          
21
When('user clicks on Submit button', async function () {
22
  
23
});
24

          
25
Then('{string} message appears', async function (string) {
26
  
27
});
28

          


The above code represents the structure of all the steps specified in the feature file.

Create Page Objects to Store Selectors for Web Elements

17. Inside the features folder, create a new folder with the name: support

18. Inside the support folder, create a new folder with the name: pages

19. In this folder, create a new file with the name: example_pageObjects.js

20. Here is the code for the page objects file:

JavaScript
 




xxxxxxxxxx
1
28


 
1
const {Selector} = require('testcafe');
2

          
3
/*
4
Create and export a module with name "elements". This module contains functions.
5
Each function is returning a Selector for a particular web element and bind to testController.
6
This module can be imported and called from Step Definitions to access the web elements.
7
*/
8
exports.elements = {
9
    nameTxtBox: function() {
10
        return Selector('#developer-name').with({ boundTestRun: testController });
11
    },
12
    interfaceMenu: function() {
13
        return Selector('#preferred-interface').with({ boundTestRun: testController });
14
    },
15
    testCafeCheckBox: function() {
16
        return Selector('#tried-test-cafe').with({ boundTestRun: testController });
17
    },
18
    descriptionTxtBox: function() {
19
        return Selector('#comments').with({ boundTestRun: testController });
20
    },
21
    submitBtn: function() {
22
        return Selector('#submit-button').with({ boundTestRun: testController });
23
    },
24
    messageElement: function() {
25
        return Selector('#article-header').with({ boundTestRun: testController });
26
    }
27
}
28

          



The above code represents the selectors for all the web elements involved in the test scenario.

Modify the cucumber step definitions file and specify the TestCafe commands inside the step definition methods

21. Open the example_page_steps.js file, and specify the TestCafe commands, interacting with elements from example_pageObjects.js

22. Here is the complete code for the step definition file:

JavaScript
 




xxxxxxxxxx
1
44


 
1
/*
2
1. Import module from newly created page object file.
3
2. Import the required keywords from Cucumber.
4
3. Import the Selector from TestCafe.
5
*/
6
const examplePage = require('../support/pages/example_pageObjects.js');
7
const {Given, When, Then} = require('cucumber');
8
const { Selector } = require('testcafe');
9

          
10
Given('user navigates to the example form page', async function () {
11
    await testController.navigateTo('https://devexpress.github.io/testcafe/example/');
12
});
13

          
14
When('user enters {string} in the name field', async function (string) {
15
    const nameField = examplePage.elements.nameTxtBox();
16
    await testController.typeText(nameField, string);
17
});
18

          
19
When('user selects {string} as TestCafe Interface', async function (string) {
20
    const interfaceField = examplePage.elements.interfaceMenu();
21
    const interfaceOption = interfaceField.find('option');
22
    await testController.click(interfaceField).click(interfaceOption.withExactText(string));
23
});
24

          
25
When('user checks the I have tried TestCafe checkbox', async function () {
26
    const triedTestCafeCheckBox = examplePage.elements.testCafeCheckBox();
27
    await testController.click(triedTestCafeCheckBox);
28
});
29

          
30
When('user enters {string} in feedback description field', async function (string) {
31
    const descriptionField = examplePage.elements.descriptionTxtBox();
32
    await testController.typeText(descriptionField, string);
33
});
34

          
35
When('user clicks on Submit button', async function () {
36
    const submitButton = examplePage.elements.submitBtn();  
37
    await testController.click(submitButton);
38
});
39

          
40
Then('{string} message appears', async function (string) {
41
    const welcomeMessageElement = examplePage.elements.messageElement();
42
    await testController.expect(welcomeMessageElement.innerText).contains(string);
43
});
44

          



The above code represents the interaction of web elements with TestCafe actions inside the cucumber step definition methods.

Inject TestCafe test controller into cucumber step definitions

23. We have already created features, step definitions with TestCafe commands, and page objects. The main goal is to inject the TestCafe test controller object into the context of each cucumber step definition. This is accomplished by creating 3 files, namely TestControllerHolder, CucumberWorld, and Hooks.

24. Inside the support folder, create a new file with the name: testControllerHolder.js

25. Here is the code for the testControllerHolder file:

JavaScript
 




xxxxxxxxxx
1
47


 
1
const testControllerHolder = {
2

          
3
    testController: null,
4
    captureResolver: null,
5
    getResolver: null,
6

          
7
    // This function is used to capture the testController object and return a promise to be resolved when the Cucumber script finishes.
8
    // This function will be called by the TestCafe test in the beginning.
9
    capture: function(t) {
10
        testControllerHolder.testController = t;
11

          
12
        if (testControllerHolder.getResolver) {
13
            testControllerHolder.getResolver(t);
14
        }
15

          
16
        return new Promise(function(resolve) {
17
            testControllerHolder.captureResolver = resolve;
18
        });
19
    },
20

          
21
    // This function is used to free the testController object.
22
    // This function will be called by the TestCafe test in the ending.
23
    free: function() {
24
        testControllerHolder.testController = null;
25

          
26
        if (testControllerHolder.captureResolver) {
27
            testControllerHolder.captureResolver();
28
        }
29
    },
30

          
31
    // This function is used to resolve and get the testControllerObject.
32
    // This function will be called by CucumberWorld and helps in setting up the controller asynchronously,
33
    // then add it to Cucumber’s world scope.
34
    get: function() {
35
        return new Promise(function(resolve) {
36
            if (testControllerHolder.testController) {
37
                resolve(testControllerHolder.testController);
38
            } else {
39
               testControllerHolder.getResolver = resolve;
40
            }
41
        });
42
    }
43
};
44

          
45
// Exporting the module for other files to import and use
46
module.exports = testControllerHolder;
47

          



The above code represents the functions to capture, free, and get the TestCafe test controller object with a promise. These functions will be called from CucumberWorld and Hooks files.

26. Inside the support folder, create a new file with the name: cucumberWorld.js

27. Here is the code for the cucumberWorld file:

JavaScript
 




xxxxxxxxxx
1
19


 
1
// World is an isolated context for each cucumber scenario, exposed to the hooks and steps.
2
// Import setWorldConstructor from cucumber-js.
3
const {setWorldConstructor} = require('cucumber');
4
const testControllerHolder = require('./testControllerHolder');
5

          
6
function CustomWorld() {
7

          
8
    /*
9
    1. The waitForTestController promise object waits for TestCafe to finish setting up the controller asynchronously, 
10
    then adds it to Cucumber’s world scope as testController.
11
    2. It calls the testControllerHolder.get function to trigger the promise to return the testController.
12
    */
13
    this.waitForTestController = testControllerHolder.get()
14
        .then(function(tc) {
15
            return testController = tc;
16
        });
17
}
18

          
19
setWorldConstructor(CustomWorld);



The above code represents the World in Cucumber-js, which is an isolated context for each cucumber scenario, exposed to the hooks and steps. This function is called from the hooks file.

28. Inside the support folder, create a new file with the name: hooks.js

29. Here is the code for the hooks file:

JavaScript
 




xxxxxxxxxx
1
87


 
1
/*
2
1. Import fs and use it to create and write text into a file.
3
2. Import testControllerHolder module from testControllerHolder.js file.
4
3. Import hook keywords from cucumber.
5
4. Create a timeout variable with a value.
6
*/
7
const fs = require('fs');
8
const createTestCafe = require('testcafe');
9
const testControllerHolder = require('./testControllerHolder');
10
const {AfterAll, setDefaultTimeout, Before, After} = require('cucumber');
11
const timeout = 100000;
12
let cafeRunner = null;
13

          
14
/*
15
Objective: We need to inject the TestCafe test controller object into the context of each step definition.
16

          
17
1. We are creating a dummy test file by function "createTestFile".
18
2. The cucumbertest.js file reads as a TestCafe test file with fixtures.
19
3. It doesnot execute the test, rather it captures the TestCafe controller and passes it back to testControllerHolder.js
20
4. It is performed by calling testControllerHolder.capture function. This passes in the test controller, which responds with a Promise, 
21
to be resolved when the Cucumber script finishes and calls testControllerHolder.free function
22
5. Until then, the TestCafe script waits in the background, allowing us to use the test controller to execute all the cucumber scenarios.
23
*/
24
function createTestFile() {
25
    fs.writeFileSync('cucumbertest.js',
26
        'import testControllerHolder from "./features/support/testControllerHolder.js";\n\n' +
27
        'fixture("cucumberfixture")\n' +
28
        'test\n' +
29
        '("test", testControllerHolder.capture)')
30
}
31

          
32
// Create a runner function with configurations like src, screenshots, browsers.
33
function runTest(browser) {
34
    createTestCafe('localhost', 1337, 1338)
35
        .then(function(tc) {
36
            cafeRunner = tc;
37
            const runner = tc.createRunner();
38
            return runner
39
                .src('./cucumbertest.js')
40
                .screenshots('reports/screenshots/', true)
41
                .browsers(browser)
42
                .run();
43
        });
44
}
45

          
46
// Setting the default time out value
47
setDefaultTimeout(timeout);
48

          
49
/*
50
1. Before hook runs before each Cucumber test.
51
2. It calls the "runTest" function, which contains the runner configuration.
52
3. Then, it calls the "createTestFile" function. It generates a dummy file, cucumbertest.js, behaving as the source of the tests.
53
4. Then, it calls the waitForTestController of cucumberWorld.js to add testController to Cucumber’s world scope.
54
5. Then, it also maximizes the test controller window.
55
*/
56
Before(function() {
57
    runTest('firefox');
58
    createTestFile();
59
    return this.waitForTestController.then(function(testController) {
60
        return testController.maximizeWindow();
61
    });
62
});
63

          
64
// After hook runs after each Cucumber test. It is used to unlink the test and make testController "null".
65
// It calls the testControllerHolder.free function. 
66
After(function() {
67
    fs.unlinkSync('cucumbertest.js');
68
    testControllerHolder.free();
69
});
70

          
71
// AfterAll hook runs after all the tests execution. It check the last runs status to be "test-done-confirmation",
72
// and then, close the cafeRunner and exit the process.
73
// It checks with a wait timeout of 500.
74
AfterAll(function() {
75
    let intervalId = null;
76
    function waitForTestCafe() {
77
        intervalId = setInterval(checkLastResponse, 500);
78
    }
79
    function checkLastResponse() {
80
        if (testController.testRun.lastDriverStatusResponse === 'test-done-confirmation') {
81
            cafeRunner.close();
82
            process.exit();
83
        }
84
    }
85
    waitForTestCafe();
86
});
87

          



The above code represents the hooks, which includes functions for:

  • Creating a new test file and trigger the capture function of testControllerHolder
  • Creating a test runner
  • Before function to activate test runner, create a test file, and waitForTestController by triggering the function of cucumberWorld
  • After function to free the test controller object by triggering the free function of testControllerHolder
  • Afterall function to close and exit the test runner, when test done confirmation is received

Generate HTML Reports Using Cucumber-HTML-Reporter

30. We want to generate an interactive HTML report with graphical representation (pie charts) and detailed information about the execution of test steps. We will use cucumber-HTML-reporter to read the report.json file and convert it into an interactive HTML report

31. Dependencies for cucumber-HTML-reporter is already defined in the package.json file

32. In the project folder, create a new file with the name: index.js

33. Here is the code for the index file:

JavaScript
 




xxxxxxxxxx
1
23


 
1
/* Plugin settings for "cucumber-html-reporter" plugin.
2
These settings help us in configuring the HTML report to be generated from JSON report.
3
We can provide information like metadata to be published in the HTML report, theme of the report, 
4
and other options like scenarioTimestamp, reportSuiteAsScenarios.
5
*/
6

          
7
var reporter = require('cucumber-html-reporter');
8

          
9
var options = {
10
        theme: 'bootstrap',
11
        jsonFile: 'reports/report.json',
12
        output: 'reports/cucumber_report.html',
13
        reportSuiteAsScenarios: true,
14
        scenarioTimestamp: true,
15
        launchReport: true,
16
        metadata: {
17
            "Title": "Sample Report",
18
            "Browser": "Firefox",
19
            "Platform": "Windows 10"
20
        }
21
    };
22

          
23
reporter.generate(options);



The above code represents the settings to generate an HTML report from the JSON report, along with metadata information to be displayed in the report.

34. We have designed the project to integrate Cucumber with TestCafe. The project structure looks like below:

package.json

Execute the Cucumber_TestCafe_Project

35. Execute the command “./node_modules/.bin/cucumber-js.cmd” in the VSCode Shell Terminal to run the project

36. Observe the test automation in real-time and the test results in the terminal

code snippet

37. Navigate to reports folder in the Cucumber_TestCafe_Project folder and view the screenshot of the application for the failed test step

thank you, john doe

38. To generate JSON report along with test execution, execute the command “./node_modules/.bin/cucumber-js.cmd --format json:./reports/report.json” in the VSCode Shell Terminal

39. Navigate to reports folder in the Cucumber_TestCafe_Project folder and view the report.jsonVS code
40. To generate an interactive HTML report, execute the command “node index.js” in the VSCode Shell Terminal

41. Navigate to reports folder in the Cucumber_TestCafe_Project folder and view the cucumber_report.html in a browser

integrate-testcafe


Cucumber (software) Testing file IO Integration Object (computer science) application Visual Studio Code JavaScript Hook

Opinions expressed by DZone contributors are their own.

Related

  • Integrate Cucumber in Playwright With Java
  • WebDriverIO Integration With Cucumber
  • Advanced Error Handling in JavaScript
  • Storybook: A Developer’s Secret Weapon

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!