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

What is the method for retrieving the values of multiple numbers entered in table rows using ASP?

I am trying to customize an input field so that the client can add or delete N number of input fields as needed. While I have successfully implemented adding input fields, I am facing difficulty in retrieving values from these dynamically added text fields ...

Customizing the Zoom Control Style in Vue Leaflet

I'm currently working on developing a Map App in Dark Mode using Vue, but I've encountered an issue with changing the style of the Zoom Control. Here's what I have tried so far: template> <div class="main-map"> <l ...

Is it possible to use velocity js to add a gradient color effect to text content?

Can I use velocity js to apply gradient color to text? I've looked at https://css-tricks.com/snippets/css/gradient-text/ My specific need is to dynamically add a changing gradient using js. Thank you in advance. ...

Creating a webpage that seamlessly scrolls and dynamically loads elements

Currently, I am working on a dynamic website that loads new elements as you scroll down the page. Here is an example of the HTML code: <div>some elements here</div> <div id="page2"></div> And this is the JavaScript code: var dis ...

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

Is there a way to automatically close a created div by clicking anywhere outside of it?

I'm facing an issue with a dynamically created div that I want to close by clicking outside of it. However, when I try to achieve this functionality, the div closes immediately as soon as it is opened. closediv(); } function closediv() { d ...

Revise the reply within ExpressJS

I need help with editing the response to a request in Express. When the request is made via XHR, I want to encapsulate the body inside a JavaScript object. This way, different parts of the page can be accessed individually within the JavaScript object, suc ...

Issue with Apollo Client - Mutation failing due to undefined property 'data'

When attempting to call a mutation on the client side in Next.js, I encounter an error every time I use the useMutation hook or the client itself, resulting in the following error: Cannot read property 'data' of undefined. See the code snippets b ...

Having trouble determining the dimensions of a newly added element

I am using jQuery to dynamically add an image but I am unable to retrieve its dimensions (width and height). Below is the snippet of code from my HTML file: <input type="checkbox" id="RocketElement" data-id="1"> And here is the JavaScript/jQuery c ...

Developing a Library for Managing APIs in TypeScript

I'm currently struggling to figure out how to code this API wrapper library. I want to create a wrapper API library for a client that allows them to easily instantiate the lib with a basePath and access namespaced objects/classes with methods that cal ...

Using `popWin()` in conjunction with `echo php` in Javascript

How can I create a JavaScript popup window inside an echo line? I have tried the following code but the popup window does not work: echo '<td> <a href="javascript:popWin(edit.php?id='.$row[id].')">Edit</a></td>&apos ...

Trying to access the 'style' property of a null value is causing an error

Although I have come across several questions related to this particular error, unfortunately, none of them provided a solution. Below is the HTML code: <!DOCTYPE html> <html> <head> <title>ChatRoom</title> <link ...

Ways to activate the enter key

Here we have the input bar and search button setup in our HTML code: <div> <div class="input-group search-bar"> <input type="text" class="form-control search-box" placeholder="Search people" autofocus="" ng-model="searchPeople"& ...

Developing a realtime search feature using AJAX and CodeIgniter

Attempting to implement a live search feature in CodeIgniter for the first time. As a newcomer to web development, still in the learning process. Came across a tutorial on how to achieve this here. Struggling with adapting the code from the tutorial to fi ...

Unleashing the Power of v-model in Vue.js: A Comprehensive Guide to Referencing Input

I am a beginner in vue.js and I am currently facing an issue with making a get request from a field that has a v-model="embed.url" after pasting a link. The paste event works fine, but I'm struggling to reference the input with v-model="embed.url" and ...

Exploring the differences between using a local controller in Angular's MdDialog modal versus displaying a shadow at

I've been attempting to utilize an app-level controller to showcase a modal dialog. The local function controller tests are functioning flawlessly, but the app level controller is only showing a grey shadow instead of the expected dialog. The edit an ...

Optimal method for identifying all inputs resembling text

I'm in the process of implementing keyboard shortcuts on a webpage, but I seem to be encountering a persistent bug. It is essential that keyboard shortcuts do not get activated while the user is typing in a text-like input field. The approach for hand ...

employ the inverse Euler application

var a = new THREE.Euler( 0, 1, 1.57, 'YXZ' ); var b = new THREE.Vector3( 1, 0, 1 ); var c = b.applyEuler(a); In order to get the value of c using b.applyEuler(a), I am looking for the reverse operation involving applyEuler. Given that the value ...

Adding HTML content inside an iFrame at a specific cursor position in Internet Explorer

Does anyone know a method to insert HTML into an iFrame specifically for IE? I have been using execCommand insertHtml in Chrome and Firefox, but it doesn't seem to work in IE. I was able to paste HTML into a content editable div using pasteHTML, howe ...

Extending State Interface in ReactJs and Typescript: A Step-by-Step Guide

I have the following: interface EditViewState<T> { entity?: T; } abstract class EditView<T, P, S> extends React.Component<P, EditViewState<T> & S> { constructor(props: P, ctx: any) { super(props, ctx); this. ...