Save the value of a webpage element into a variable and utilize it across multiple JavaScript files in TestCafe

We are working in the insurance domain and have a specific scenario that we want to achieve using TestCafe:

1st step: Login into the application 2nd step: Create a claim and store the claim number in a global variable 3rd step: Use the globally declared claim number in all the test scripts.

We are implementing the Page Object Model to accomplish this scenario.

Please advise on how we can achieve this in TestCafe. We have noticed that the web element value obtained in the 2nd file disappears as soon as the test case is executed. How can we pass that web element value to our 3rd file?

If possible, please provide detailed steps on how to do this.

We have attempted to use keywords like "global" and "globalthis" to define our selector, but it did not work.

  1. In our 'page.js' file:

    import { Selector, t } from 'testcafe'; class PageModel { constructor() { global.ClaimNumber = Selector('#Txt_claimnumber'); // Selector for Claim Number

    this.DateOfEvent = Selector('#dateofevent'); // Selector for Date of Event

    this.DateOfClaim = Selector('#dateofclaim') // Selector for Date of Claim

    this.TimeOfEvent = Selector('#timeofevent') // Selector for Time of Event

    this.TimeOfClaim = Selector('#timeofclaim') // Selector for Time of Claim

    this.ClaimStatus = Selector('#claimstatus') // Selector for Claim Status

    this.Save = Selector('#Save'); // Selector for Save Button

    }};

    export default new PageModel();

  2. In our 'test.js' file:

    import { Selector } from 'testcafe';

    import PageModel from './page';

    fixture`Getting Started` .page`https://devexpress.github.io/testcafe/example`; var claimid; // Claim ID will be generated after saving a claim test('My first test', async t => { await t .typeText(this.DateOfEvent, '20/09/2022')

    .typeText(this.DateOfClaim, '20/09/2022')

    .typeText(this.TimeOfEvent, '12:00')

    .typeText(this.TimeOfClaim, '12:00')

    .typeText(this.ClaimStatus, 'xyz')

    .click(this.Save)

    claimid = global.ClaimNumber.value

    // After saving the claim, we want to fetch the claim ID and use it in another test script

    });

In our 'test1.js' file:

import { Selector } from 'testcafe';

import PageModel from './page';

import Test from './test'

fixture`Getting Started` .page`https://devexpress.github.io/testcafe/example`; test('My first test', async t => { var claimid1 = '23445'; await t.expect(claimid1).eql('claimid');

// Verify if the claim ID from test.js is equal to the claim ID from test1.js or not

// This is just an example, but our requirement is to use the claim ID (obtained from test.js) for different operations in the test1.js script.

});

Please provide guidance on how to achieve this scenario effectively.

Answer №1

Using information from one test in another is not considered accurate. To prepare before a test starts, implementing hooks can be helpful. Additionally, for reusing authentication details, utilizing Roles is recommended as good practice.

An example with a global variable is shown below:

//test.js
import { Selector } from 'testcafe';
import PageModel from './page';

 

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

 

test('My first test', async t => {
    await t
        .typeText(global.developerNameSelector, 'John Smith')
        .click('#submit-button')

 

        // Using assertion to verify if the actual header text matches the expected one
        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');
});
//page.js
import { Selector, t } from 'testcafe';

 

class PageModel { 
    constructor() { 
        global.developerNameSelector = Selector('#developer-name'); 
    } 
}; 

 

export default new PageModel();

Answer №2

It is not recommended to rely on data from one test in another, but if necessary, you can utilize the "global" object in JavaScript for this purpose:

test('First example test', async () => {
global.someValue = 'important-data';
});

test('Second example test', async t => {
await t.typeText(`#${global.someValue}`, 'example input');
});

Keep in mind that if the test execution order changes unexpectedly (e.g., in concurrent mode), it may lead to unpredictable outcomes.

I also noticed that you are storing the result of an "expect" method call in a variable. Could you explain your intention behind this? What specific behavior are you aiming to achieve?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for utilizing ng-checked and ng-disabled in conjunction with ng-repeat

I encountered a challenge with ng-repeat while incorporating ng-checked and ng-disable alongside it. <div ng-repeat="module in modulelist"> <input id="switch{{$index}}" ng-init="setState($index);" type="checkbox" ng-checked="switch.checked" ng-di ...

When multiple checkboxes are selected, corresponding form fields should dynamically appear based on the checkboxes selected. I attempted to achieve this functionality using the select option method

Require checkboxes instead of a selection option and have multiple checkbox options. Depending on the checked checkboxes, different form fields should appear. A submit button is needed. I have included some CSS code, but a more detailed CSS code is requir ...

Is it necessary for NPM to execute scripts labeled as dependencies during the npm i command execution?

When npm i is run, should it execute the scripts named dependencies? I've observed this behavior in the latest version of Node (v19.8.1) and I'm curious if it's a bug. To replicate this, follow these steps: mkdir test cd test npm init -y T ...

Asynchronously retrieving results in MongoDB

My task involves fetching all users from the users collection. app.post('/login', function(req,res,next){ users = self._db.get('users', {}) }) Below is the function in my database class: this.get = function( col, opt ) { ...

Synchronize numerous PouchDB databases with a single CouchDB database

After reading the PouchDB documentation, I learned that sync occurs between a local database and a remote CouchDB database. Currently, I am working on developing a native application that includes a unique local database for each user (multiple databases) ...

Tips for interacting with a custom web component using Selenium WebDriver

As a newcomer to writing selenium tests, I am attempting to create an automated test for a carousel feature on our homepage. The objective is to click on one of the carousel navigation buttons and then confirm that a specific inline style has been applied ...

verify whether the image source has been altered

There is an img tag displaying the user's avatar. When they click a button to edit the image and choose a new one, the src attribute of the img changes to the new image src. How can I detect when the src changes? Below is the code for the button tha ...

Tips on connecting the endpoints of two parallel quadratic Bezier curves that both begin with a MoveTo command

I am currently working on creating a Sankey Diagram from scratch using VueJS and SVG. I have encountered challenges in closing the paths of two parallel quadratic Bezier curve paths from nodes to nodes. For instance, after some additional calculations, I ...

Pattern matching using regex can also be used to restrict the number of characters allowed

Having some trouble with regex to match a specific pattern and also limit the number of characters: Let's say I have allowed number prefixes: 2, 31, 32, 35, 37, 38, 39, 41, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 I only want numb ...

Retrieve vuex state in a distinct axios template js file

I have encountered an issue with my Vue project. I am using Vuex to manage the state and making axios requests. To handle the axios requests, I created a separate file with a predefined header setup like this: import axios from 'axios' import st ...

Is there a way I can appropriately display an image in a specific size box?

Check out the code snippet I wrote below: import React from 'react' function OurCourse() { return ( <div className='w-full '> <div className='w-full h-[390px]' style={{ backgroundImage:&apos ...

CSS fixed dynamically with JavaScript and multiple div elements placed randomly

Is it possible to dynamically change the position of multiple div elements on a webpage without reloading? I am looking for a way to modify the top and left positions of several divs, all with the same class, simultaneously. I want each div to have a diff ...

Break down for me what Json is in a way that a five-year-old could understand

Let me clarify one thing, I may not be a Javascript expert but I'm far from being 5 years old. Json is one concept that's been confusing me lately as I dive into the world of programming. Can someone please explain json to me in a simplified mann ...

How can you ensure a form is properly validated using javascript before utilizing ajax to submit it

I've been working on developing a website and I am in need of an attractive login/registration/forgot password form. My aim was to utilize 'ajax' to enhance the user experience, leading me to immerse myself in a steep learning curve for the ...

What is the best way to send a JavaScript variable to Django using AJAX?

I am facing an issue while trying to pass an array in json format using ajax to my django views. Even though I receive a status of 200 indicating that the POST request has been successfully made, when I attempt to display the data passed in another templat ...

serving files using express.static

I have set up express.static to serve multiple static files: app.use("/assets", express.static(process.cwd() + "/build/assets")); Most of the time, it works as expected. However, in certain cases (especially when downloading many files at once), some fil ...

Incorporate a Google Chart link by integrating it with a select handler

I'm facing an issue while trying to open a link in a Google line chart using the selection handler. The chart stops rendering, and as a newcomer to javascript, I'm unsure why. This is how the code is integrated into my HTML: <pre><code ...

MUI Tutorial: Displaying Text with Line Breaks

Whenever I input text into the MUI Textfield, it displays without any line breaks. Is there a more effective solution available? <Stack direction="row" alignItems="start" justifyContent="start" mb={5}> <TextFie ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Issue with VueJs router-link component

Whenever I click on a vuejs router-link element in my app.blade.php page navigation bar, I keep seeing an error in my console which is displayed below [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent comp ...