Reading the fixture JSON file in Cypress - A step-by-step guide

I'm struggling to read data from a JSON fixture file in Cypress for my test cases. Despite following various instructions and examples, I can't seem to make it work. Any ideas on what I might be doing wrong?

Below are the details of my files along with the relevant code snippets.

TEST CASE:

describe('Test for user data via JSON', ()=> {

 
    // Utilize cy.fixture() method to retrieve data from fixture file
    before(function () {
        cy.fixture('users').then(function (userData) {
            this.userData = userData;
            })
        })

    it.only('Login Test. User1', () => {
        
        cy.wait(500)
        cy.visit('http://localhost/')

        cy.wait(500)

        onLoginPage.usernameInput(this.userData[0].username)
        onLoginPage.passwordInput(this.userData[0].password)
        onLoginPage.buttonGo()

    })
})

JSON FILE

File Name: users.json

[
    {
        "id": 0,
        "username": "User1",
        "password": "password1",
        "_comment": "All rights"
    },
    {
        "id": 1,
        "username": "User2",
        "password": "password2",
        "_comment": "All rights"
    },
    {
        "id"quot;: 2,
        "quot;username"quot;: ""User3",
        quot;password"": ""password3",
        quot;_comment": ""Reading only"
    }
]

The error message indicates: "Cannot read properties of undefined (reading 'users')" And points out the issue in this line of code:

onLoginPage.usernameInput(this.**u**serData[0].username) 

The fixtures folder is located at: "../fixtures/users"

This should have been straightforward based on the examples I've seen. Can someone help me figure out what's missing here? I appreciate any guidance provided.

Thank you!

Answer №1

Instead of relying on the this context to access fixture data, avoid polluting test scopes by utilizing Test Isolation.

Test Isolation clears data between tests, ensuring that each test runs independently without interference from previous tests.

For scenarios where you only need userData for a specific login test, consider simplifying the process by using cy.fixture() directly within that test.

it('Login Test. User1', function() {
  cy.fixture('users').then(data => {

    userData = data.find(d => d.username === 'User1')

    cy.visit('/')
    onLoginPage.usernameInput(userData.username)
    onLoginPage.passwordInput(userData.password)
    onLoginPage.buttonGo()
  })
})

Answer №2

To avoid scoping issues, consider using an arrow function within the then() method just like you did with only() later in your code. Arrow functions and 'regular' anonymous functions have different scoping behaviors, so the context of this may vary. This could be why setting the userData property is causing confusion when trying to access it later on.

It's worth noting that the error message likely pertains to this.userData, not this.users, as the latter isn't referenced anywhere else in your code.

Answer №3

Thanks to the guidance provided in this post, I was able to find a solution:

Utilizing cy.fixture with Array for JSON Fixture Files

Specifically, I focused on this portion:

cy.fixture('testdata').then(testdata  => {

            const ModuleID = testdata[0].ModuleID 
            const LoginName = testdata[0].LoginName
            const gameid = testdata[0].gameid

        cy.get('#ModuleID').type(ModuleID)
        cy.get('#LoginName').type(LoginName)
        cy.get('#gameid').type(gameid)
        cy.get('#btnSubmit').click()

This allowed me to easily access data from my .json file within the test case.

I opted not to use beforeEach and found success integrating it directly into the test scenario.

A big thank you to everyone who offered assistance during this process.

With this resolution, the case is now closed.

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 causes the content of my container to disappear following a setInterval div swap in Internet Explorer?

While developing a website on Chrome and Firefox, I was informed that it also needs to function properly in Internet Explorer. I managed to resolve the double padding issue in IE, but now I'm facing a new problem. The content of my "grid" disappears a ...

How can I retrieve data from a JSON string using Javascript?

Here is the JSON data I am working with: { "head":{ "vars":[ "uri", "label" ] }, "results":{ "bindings":[ { "uri":{ "type":"uri", "value":"http://tematres.befd ...

Deselect all event listeners excluding the ones specified in Socket.io

I have a node.js application using socket.io to dynamically load external modules, referred to as "activities," in real-time. Each module binds its own events to the sockets, so when switching from one module to another, I need to remove all event listene ...

Tips for incorporating conditions when updating data in MongoDB

I am looking for assistance with updating the secondary phone number in the code below. I want to update it only if a 10-digit number is passed from the web form; otherwise, I would like to use the already inserted phone number during the insert operation. ...

Sending data between PHP and JavaScript using Ajax communication

I am currently working on a PHP page that involves variables and radio buttons. When a user clicks on a radio button, it triggers a JavaScript function to calculate the price of the selected item by passing some variables. Here's how I have implemente ...

Utilizing JQuery AJAX to Submit a JSONP Form with File Attachments

I have been working on implementing a contact form for our clients who create websites with their own domains through us. As part of our services, we provide hosting and a web editor to help them build their websites. The contact form they include on their ...

Trigger notifications exclusively for specific hyperlink texts that are selected

I'm facing an issue where I need to notify the user when a specific link text for a hyperlink is clicked. The code provided here showcases the problem I am currently encountering. At the moment, the alert triggers whenever any link text is clicked, ra ...

Copying a class and adding the second item in the duplicated class

I have been working with an ajax function to retrieve names from the database. The issue arises when there are multiple names returned - I split them and then attempt to clone the first class in order to display the additional names. However, this proces ...

Navigating with nodeJS

Currently, I am in the process of learning how to create a Node.js project. My latest endeavor involved following a tutorial to develop a chat application. However, it seems like there is an issue with the routing between the server side and client side. ...

Utilizing Webpack for Effortless Image Loading in Angular HTML

I've been struggling with webpack and angular configuration. It seems like a simple issue, but I just can't seem to find the solution. Despite scouring Stack Overflow for answers, I'm still stuck. My HTML page looks like this (along with ot ...

Assigning a unique date/time stamp to every MongoDB document when it is created

This is my second query regarding Node.js for today. It's getting late, and I need some assistance to quickly incorporate this function before calling it a night. I have developed a small Q&A application where I can interact with MongoDB to read and ...

Luxon DateTime TS Error: The 'DateTime' namespace cannot be used as a type in this context

I have encountered an issue while trying to set the type of a luxon 'DateTime' object in TypeScript. The error message DateTime: Cannot use namespace 'DateTime' as a type appears every time I attempt to assign DateTime as a type. Below ...

What is the method for dividing a string (object) to 'preserve' in a fresh piece?

Upon receiving the following JSON file: var data = [ { "id":"1", "yMonth":"201901", }, { "id":"2", "yMonth":"201902", }, { "id":"3", "yMonth":"201802", }, { "id":"4 ...

The jQuery ajax script executes without issues, yet encounters an error during the process

I am encountering an issue with a simple script that is consistently resulting in an error, despite the PHP script running successfully. PHP require('/connect.php'); //Includes my $link variable if(isset($_POST['pass'])){ $us ...

The onFocus event ceases to trigger once the modal popup appears

One issue that I am facing is with an onfocus event handler. Initially, everything works perfectly after the page loads. However, when I click on a link that triggers a modal popup, the onfocus event stops working. Although focus continues to work as expec ...

Utilizing Google APIs to split a route among multiple locations

I am facing a scenario where A laundry company operates from one shop location. The laundry company has 3 trucks available (n trucks). The laundry company needs to deliver washed clothes to multiple locations (n locations). https://i.sstatic.net/ULup8.pn ...

How can you specifically target a cloned HTML input using JavaScript?

https://i.sstatic.net/mazIX.png $('.fileupload').change(function(event){ var fd = new FormData(); var files = $(this)[0].files; var a = this.id; console.log(a); var data_inp = 'dat ...

Is it possible to reuse a variable within a single HTML tag when using Angular 2?

I encountered a strange issue with Angular 2 that may be a bug. I noticed that I couldn't print the same variable in a template twice within the same HTML tag. When I tried to use the following code, it resulted in error messages. <div class=" ...

Updating specific keys or attributes within a JSON column in Postgres using a form

Struggling to update a JSON column in a rails model. An issue I'm facing involves an OrderItem model with an :options column using the postgres json datatype. When attempting to update only two attributes within that JSON column through a form, the ...

What is the best way to substitute </br> and <br/> with in a text?

Is there a way to replace </br> and <br/> with \n functionally? There seems to be varied responses to this query. Errors are often made when writing the break tag. The solutions for both types of breaks mentioned above are detailed below ...