Testing the front end by utilizing React in combination with Selenium-Webdriver, while utilizing Rails as the backend

Currently, I am focused on testing the Front-End aspect of my project. Here is the challenge I am encountering:

Situation

In my setup, I have a well-established Ruby on Rails (V3.2) backend application and a completely new front-end application built with ReactJs (V16.4).

Issue at Hand

While testing the React app using Selenium-Webdriver and JestJs, we were able to navigate through various views smoothly. However, we faced difficulties when attempting POST requests to the Rails API.

I am hesitant to clutter my development database with unnecessary data due to testing purposes.

For instance, how should I handle testing the creation of a new user?

Potential Solutions Considered

I have considered three possible approaches:

  1. Intercept the API calls and simulate their responses (e.g., triggering a submission click using selenium-webdriver).
  2. Utilize Rails test environment in conjunction with React
  3. Attempt to reverse the API call by performing contradictory actions in the controller. This may involve executing deletes for each post request.

Answer №1

When deciding on how to approach testing, consider whether you want to test the entire stack (frontend/backend) or just focus on the frontend aspect.

Frontend Testing

If your goal is to solely test the frontend, then using mock API calls as your initial solution is recommended.

Directly relying on selenium-webdriver may limit your options. Instead, consider utilizing tools like nightwatch or testcafe. Notably, Testcafe does not require selenium and this feature has also become optional in recent releases of Nightwatch.

Testcafe even offers a Request mocking API:

In Nightwatch, you have the option of using nock for mocking HTTP requests. You can find more information at Nightwatch Mock HTTP Requests

Full Stack Testing

If a comprehensive evaluation of the entire stack is what you seek, consider implementing a custom API endpoint that facilitates database resetting to ensure a pristine state before or after test executions (e.g., "/myapi/clean").

For security reasons, make sure to restrict access to this endpoint in production environments.

You can further enhance your testing strategy by incorporating test hooks (before/after) to invoke your custom API endpoint:

Answer №2

One solution could be to create a testing sandbox. In my opinion, the clutter of test-generated data is manageable as you can regularly purge it or opt for a fresh environment per test cycle.

Answer №3

After much consideration, I ultimately opted to utilize enzyme in conjunction with jest and sinon.

Here is an example of the code:

import { mount } from "enzyme";
import sinon from "sinon";

beforeAll(() => {
 server = sinon.fakeServer.create();
 const initialState = {
  example: ExampleData,
  auth: AuthData
 };
 wrapper = mount(
  <Root initialState={initialState}>
    <ExampleContainer />
  </Root>
 );
});

it("description of the example", () => {
  server.respondWith("POST", "/api/v1/example", [
    200,
      { "Content-Type": "application/json" },
      'message: "Example message OK"'
    ]);
  server.respond();
  expect(wrapper.find(".response").text().to.equal('Example message OK');
})

The above code showcases how we can intercept API calls using the testing DOM generated by enzyme and then simulate API responses utilizing sinon.

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

Specify the dependencies in the package.json file to ensure that the React package designed for React v17 is compatible with React v18 as well

Recently, I developed an npm package using React v17.0.2. The structure of the package.json file is as follows: { "name": "shoe-store", "version": "0.1.0", "private": true, "dependencies": ...

`It is important to note that in Tailwind CSS, `h-8` does not supersede `h-4

I developed an Icon component that looks like this: import { IconProp, library } from "@fortawesome/fontawesome-svg-core"; import { far } from "@fortawesome/free-regular-svg-icons"; import { fas } from "@fortawesome/free-solid-svg- ...

How to retrieve session information in a Next.js page utilizing withIronSession()

My attempts to access the session using req.session.get('user') have been unsuccessful even after reading the post titled Easy User Authentication with Next.js and checking out a related question on Stack Overflow about using next-iron-session in ...

Troubleshooting: Border not showing up in Tailwind CSS (React JS)

Below is the code snippet from my JSX file: import { useState, useEffect } from "react"; import { PropTypes } from "prop-types"; import { HashtagIcon } from "@heroicons/react/24/outline"; // Function to fetch categories from the API (temporary replaced wi ...

Encountering the "excessive re-renders" issue when transferring data through React Context

React Context i18n Implementation i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ resources: { en: { translation: translationsEn }, bn: { translation: translationsBn }, }, lng: "bn ...

Limit file selection to images using MUI File Input

I am currently using MUI File Input in React for a file input element. The code I have works well, but I would like to restrict this file input to only accept images. How can I achieve this? Here is what I have done so far: const [locationImg, setLoc ...

Using TypeScript to define data types for Supabase payloads

Currently, I'm working on integrating supabase into my ReactJS Typescript project. However, I'm unsure about the data type of the channel payload response and I aim to extract the eventType along with the new data. const handleInserts = () => ...

I am having trouble locating the xpath for a randomly selected radio button in Selenium

I am facing difficulty in locating the XPath or the class name for a radio button that needs to select a color randomly from a list in a Google form(link) using Selenium. Other fields such as name, age, country, and email are functioning properly with th ...

Discovering the search functionality in React Native

I am currently facing issues with creating a search bar for my app using react-native-material-ui. The main problems I am encountering are: There is a noticeable delay on the real device when using the search bar. I am struggling ...

The deployment of my Next.js app on Heroku was refused due to an incompatible Node version

Encountering issues while attempting to deploy my app on Heroku, I am faced with the following shortened errors: remote: -----> Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL=error remote: NODE_VERBOSE=false remot ...

Magician's Spellbinding Form - React Final Incantation

I'm having an issue with a wizard that I created using react-final-form. The first page displays correctly, but when I click on next, the next page is empty. Can anyone help me understand why this is happening? Here is my form: const MyForm = () =&g ...

The command "npm start" fails to execute on Windows operating systems

After using npx create-react-app to create my application, I encountered an issue where running npm start would do nothing and exit with code 0. When I try to run the npm start command, I receive the following message: C:\projects\novo-curricul ...

extract text content from anomalous html using selenium and python

Looking to extract a phone number from a webpage, such as this Avito listing. The blue button on the left triggers an ajax request that returns the phone number in a separate text() node like this: <a href="tel:895**49****" class="button-text action-l ...

Establishing a connection to an Oracle database using ReactJS

I am currently working on a database project that involves using React.js for the frontend and Oracle database for the backend connection. While there are numerous resources available for connecting React with MySQL, I have struggled to find information ...

Unable to locate image files stored in vendor/images in the Rails 4 view

I have successfully set up a custom bootstrap theme with Rails 4, and placed the image file here: /vendor/assets/images/custom_bootstrap_theme/demo/bg01.jpg The index.html.erb file is referencing this image as follows: <img src="/vendor/assets/image ...

What is the significance of the message "JavaScript files do not have any valid rules specified"?

I am working on a React - Typescript project that was created using the following command: create-react-app my-app --scripts-version=react-scripts-ts While it compiles without any issues, I keep receiving a message or warning that says: No valid rules h ...

Dynamic styling updates on page refresh in Next.js

There is a strange issue with my styling that I can't seem to figure out. I have a NavBar set to be 20vh in height and an image set to be 100% in width. However, whenever I refresh the page, the NavBar height decreases and the image width increases si ...

What is the best way to transform a JS const into TSX within a Next.js application?

Exploring the code in a captivating project on GitHub has been quite an adventure. The project, located at https://github.com/MaximeHeckel/linear-vaporwave-react-three-fiber, showcases a 3D next.js application that enables 3D rendering and animation of mes ...

Utilize a solo input field to upload either a video or image, and showcase a preview of the uploaded content in a

I'm currently working on creating an input field that allows for the upload of both images and videos. Although I am able to successfully upload the files, I'm encountering an error when trying to display a preview. The code snippet below outline ...

Managing state - It is not possible to update a component (`Provider`) while rendering another component

I'm currently exploring how to utilize jotai for updating a global indicator. This indicator will toggle the LinearProgress component (true or false). Within atom.js, I've set up a basic atom to act as the indicator: export const isDownloadAtom ...