How to setup unit testing for React application using React Testing Library and Jest?

I have a simple react application that uses RTK Query and React Router. It makes an API call and it has 2 routes

  1. unauthorized
  2. welcome

I need help with testing setup and couple of sample tests using React Test Library and Jest.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <Routes>
        <Route path='/app' element={ <App />} />
      </Routes>
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

App.js

import React from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';

import Unauthorized from './features/unauthorized/Unauthorized';
import NotFound from './features/notFound/NotFound';
import RequireAuth from './features/auth/RequireAuth';
import Welcome from './features/welcome/Welcome';

function App() {
  return (
    <Routes>
      <Route index path="unauthorized" element={ <Unauthorized />} />
      <Route path="*" element={<NotFound />} />
      <Route element={<RequireAuth groups={groups} />}>
         <Route path="welcome" element={<Welcome />} />
         <Route path="/" element={<Navigate to={welcome} />} />
      </Rout>
    </Routes>
  );
}

export default App;

Unauthorized.js

function Unauthorized(){
  return 'Unauthorized';
}

export default Unauthorized;

NotFound.js

function NotFound(){
  return 'Not Found!';
}

export default NotFound;

RequireAuth.js

import React from 'react';
import { Navigate, Outlet, useLocation } from 'react-router-dom';

function RequireAuth() {
  const location = useLocation();

  const isAuthorized = true;

  if (isAuthorized) {
    return <Outlet />;
  } else {
    return <Navigate to='unauthorized' state={{ from: location }} replace />
  }
}

export default RequireAuth;

Welcome.js

import React from 'react';
import { useGetWelcomeQuery } from './welcomeApi';

function Welcome() {
  const { data } = useGetWelcomeQuery();

  return (
    <div>
      <p>Welcome!</p>
      <h2>Messages</h2>
      {data.map((item) => (
        <p key={item.id}>{item.message}</p>
      ))}
    </div>
  );
}

export default Welcome;

store.js

import { configureStore } from '@reduxjs/toolkit'
import { welcomeApi } from "../features/welcome/welcomeApi";

export const store = configureStore({
  reducer: {
    [welcomeApi.reducerPath]: welcomeApi.reducer
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
  devTools: true
});

welcomeApi.js

export const welcomeApi = createApi({
  reducerPath: 'welcomeApi',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  endpoints: (builder) => ({
    getWelcome: builder.query({
      query: () => ({
         url: '/message'
      }),
    }),
    addWelcome: builder.mutation({
      query: (welcomeMessage) => ({
        url: '/message',
        method: 'POST',
        body: welcomeMessage,
      }),
    }),
    updateWelcome: builder.mutation({
      query: (welcomeMessage) => ({
        url: `message/${id}`,
        method: 'PUT',
        body: welcomeMessage
      }),
    }),
  }),
});

export const {
  useGetWelcomeQuery,
  useAddWelcomeMutation,
  useUpdateWelcomeMutation
} = welcomeApi;

How to detect a CSS class is active in or change CSS class name using Javascript [duplicate]

I have the following html codes:

    <li class="imagenav active">
      some codes go here
    </li>

Is there a way of checking if imagenav class is active or change CSS class using Javascript. for example:

    if imagenav is active {
      do some codes here ...
    }

Many thanks in advance.

Thank you for Barmar for advising how to check if a list has a class. However, in my case, I prefer to change CSS class using Javascript which makes it easier to manipulate my codes. So I have to add id into HTML codes. I want the left arrow to be active/disabled when the page is first loaded. Here are my fully working codes:

    <div id="active-leftarrow" class="imagenav">
      <script type='text/javascript'>
        document.getElementById('active-leftarrow').className = 'imagenav disabled';
      </script>
    </div>

Many thanks

Javascript not executing in Shopify theme customiser Custom Liquid sections

I’m fairly new to developing in the Shopify environment. Although the issue I’m currently encountering doesn’t seem particularly complicated, but it has me stumped.

The theme in use is Dawn, although I don’t think that should make any difference.

I have some JS I wanted to run on pages that use a particular template (product.warranty.json), which has been constructed in the theme customizer.

I added the JS using a “Custom Liquid” section in the template, via the customizer.

The original JS I tried adding was executing, but wasn’t identifying the target of the trigger, so I started adding in some console.log debug checks, yet nothing was appearing in the console.

I’ve now put together some debugging code to figure out what’s going on. But that’s not executing either. For instance, Debug script loaded doesn’t output to the Console.

What am I overlooking?

<script>
    console.log('Debug script loaded');

    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM fully loaded and parsed');

        function checkElementAvailability() {
            const formSelector = 'form[data-id="50018"]';
            const submitButtonSelector = "#globo-formbuilder-50018 > div > div > div > form > div.globo-formbuilder-wizard > div > div.gfb__footer.wizard__footer > button.action.next.submit.flat-button.wizard__submit";

            let startTime = Date.now();

            function logStatus() {
                const currentTime = Date.now();
                const elapsedTime = currentTime - startTime;

                const form = document.querySelector(formSelector);
                if (form) {
                    console.log(`[${elapsedTime}ms] Form with data-id 50018 found`);

                    const submitButton = form.querySelector(submitButtonSelector);
                    if (submitButton) {
                        console.log(`[${elapsedTime}ms] Submit button found`);
                    } else {
                        console.log(`[${elapsedTime}ms] Submit button not found yet`);
                    }
                } else {
                    console.log(`[${elapsedTime}ms] Form not found yet`);
                }

                setTimeout(logStatus, 50);
            }

            logStatus();
        }

        checkElementAvailability();
    });
</script>

How do I access string keys when using Typescript? [closed]

Let’s say I have the following model definition:

export interface formData {
    formSection: {},
    errors: formError[]
}

export interface formError {
    [key: string]: {
        'default'?: string
        '201'?: string
    }
}

and I receive a JSON like this:

{
  "formSection": {},
  "errors": {
    "firstName": {
      "default": "invalid first name",
      "201": "first name has invalid characters"
    }
  }
}

how can I access errors.firstName.default when TS does not know about the firstName key existence? If I do something like:

const myFunction = (param: formData) => {
    return (
        <>
            {param.errors.firstName.value}
        </>
    )
}

TS will complain saying firstName does not exist in the model, which is correct, but then how can I access that “dynamic” key?

How to handle errors coming from nextjs’s router.refresh?

I’m having a page that getting refreshed every few seconds using router refresh

    const router = useRouter()

    ...

    useEffect(() => {
        interval = setInterval(() => {
            router.refresh()
        }, REFRESH_RATE_MIL)
        return () => {
            clearInterval(interval)
        }
    }, []);

The problem is, when the machine is entering to hydration (sleep mode or closing the screen and wait a few minutes) The app crashes with net::ERR_NETWORK_IO_SUSPENDED, causing the whole application to crash.

I’m using Mac Ventura 13 and Chrome Version 127.0.6533.72 (arm64)

I tried few things to solve it:

  1. Add user idle detection to clear the interval – that doesn’t solve the case when you close the lid (screen) of the machine.
  2. catch the router refresh using try catch clauses
  3. read the nextjs docs and the router.refresh (” Refresh the current page. refresh(): void;”) to try to figure out if there is any option/callback I can use to catch it.
  4. Searched MDN and googled if there is anyway to detect the ERR_NETWORK_IO_SUSPENDED ( and then prevent the router.refresh trigger)
  5. searched next issues for issues related to ‘router.refresh error handling’ or ERR_NETWORK_IO_SUSPENDED
  6. looked stackoverflow for related questions. Find this old one

** I want to use the router refresh because of the caching ability and the fact that it preserves the component’s state

Any ideas of how to address this?

heroku.cmd”‘ is not recognized as an internal or external command, operable program or batch file

Not able to use Heroku CLI in VS code. get error “heroku.cmd”‘ is not recognized as an internal or external command,
operable program or batch file.”

Many people say to uninstall and install again, then restart and this does not work.
Also, some say to add to path and this has not worked.

I have searched for help in Heroku and Stackoverflow and the above solutions were suggested and have not worked.

Any suggestions that anyone would have will be greatly appreciated.

thanks

Do not see help in he

“Failed to load resource: net::ERR_FILE_NOT_FOUND” Electron

Cannot load

enter image description here

Resource of CalHeatmap not found when testing app in Electron. I check on my vscode that clicked new CalHeatmap(); will jump into the source file, so it should be work, but when try to npm start the resource not found.

Notes:

  • In load.js focus on imports and focus on line <script type="module" src="./load.js"></script> in index.html. Let me know if you still need info.
  • I already manage to get work of cal-heatmap in VITE then I try to make into Electron. In VITE project all it’s fine, but in Electron project it’s not.
  • If you need more information, let me know in the comment.

load.js

import CalHeatmap from './node_modules/cal-heatmap';
import './node_modules/cal-heatmap/cal-heatmap.css';

// Instantiate CalHeatmap
const cal = new CalHeatmap();

const _data = {
    data: {
        source: 'https://raw.githubusercontent.com/vega/vega/main/docs/data/seattle-weather.csv',
        type: 'csv',
        x: 'date',
        y: d => +d['temp_max'],
        groupY: 'max',
    },
    date: { start: new Date('2012-01-01') },
    range: 12,
    scale: {
        color: {
            type: 'threshold',
            range: ['#14432a', '#166b34', '#37a446', '#4dd05a'],
            domain: [10, 20, 30],
        },
    },
    domain: {
        type: 'month',
        gutter: 4,
        label: { text: 'MMM', textAlign: 'start', position: 'top' },
    },
    subDomain: { type: 'ghDay', radius: 2, width: 11, height: 11, gutter: 4 },
}


cal.paint(_data);

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
    <h1>Hello World!</h1>
    <p>
        We are using Node.js <span id="node-version"></span>,
        Chromium <span id="chrome-version"></span>,
        and Electron <span id="electron-version"></span>.
    </p>
    <div id="cal-heatmap"></div>
    <script type="module" src="./load.js"></script>
</body>
</html>

JavaScript loop running on console but not on code

I’m trying to make a a JS forEach loop that is supposed to run after the DOM is fully loaded, but for some reason it won’t run on code but when I put the same loop on console it runs fine.

window.onload = (event) => {

    var checkboxes = document.getElementsByName("plates")
    var labelPlate = document.getElementsByName("labelPlate")

    checkboxes.forEach((i, index) => {
        if (i.checked) {

            labelPlate[index].classList.add("active")
        } else {
            labelPlate[index].classList.remove("active")
        }
    })
};

Loop is supposed to run.

asp.net with vue js FsLightbox lybrary Access to XMLHttpRequest origin has been blocked by CORS policy

asp.net with vue js FsLightbox lybrary Access to XMLHttpRequest at ‘https://localhost:44347/CarImages/3e0da2fa7fd0417ea2e2f4678229e264Logo.png’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. error

when use FsLightbox library show this error , im use this images path in another slider its run good
and im use another images from internet to FsLightbox also run good
this problem just appear when use my images paths with FsLightbox !!??

// this is policy code from program.cs 
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(
        builder =>
        {
            //you can configure your custom policy
            builder.AllowAnyOrigin()
                                .AllowAnyHeader()
                                .AllowAnyMethod();
        });
});
var app = builder.Build();
// Apply CORS policy
app.UseCors();

/////////////////////

// this in vue js FsLightbox like documntation
<FsLightbox :toggler="toggler" :sources="vehicleImages" />

Update columns of DataTable after having the data from server

I’m new at DataTables js, I need a solution for my problem. I have a Django app where I use DataTables with server-side processing, the table template is dynamic for all the models I have, I just pass the columns (a list of dicts with data, name and title) within the context of the template, pretty straightforward…

def my_page_view(request):
    columns = generate_datatables_columns("MyModel")

    return render(
        request,
        "my_page.html",
        {"columns": columns}
    )
<script>
    $(document).ready(function() {
        var columns = [];
        {% for col in columns %}
            var jsObject = {
                {% for key, value in col.items %}
                    "{{ key }}": "{{ value }}",
                {% endfor %}
            };
            columns.push(jsObject);
        {% endfor %}

        var table = $('#my-table').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "/my/url",
                "type": "GET",
            },
            "columns": columns,
        });
    });
</script>

<table id="my-table" class="display" width="100%">
    <thead>
        <tr>
            {% for column in columns %}
                <th id="dt_col_{{column.data}}">{{ column.name }}</th>
            {% endfor %}
        </tr>
    </thead>
</table>

After that, I needed to make some changes on the columns, but depending on the data received, meaning I should be able to update my columns inside the DataTable definition after having the data. To make the idea clearer, the following code represents one of the attempts I tried, using ajax.dataSrc prop:

var table = $('#my-table').DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "/my/url",
        "type": "GET",
        "dataSrc": function (json) {
            var data = json.data;
            var newColumns = columns;

            // make changes on data and newColumns variables with some conditions...
            
            // here should update the datatable columns with the value of newColumns.

            return data;
        }
    },
    "columns": columns,
});

With this method I couldn’t find a way to update the columns, I tried also other ways like using drawCallback, or custom ajax function, but I always end up with a dead-end.

I will be really grateful if someone helped me with that.

Shopify App Proxy – Ajax HTTP POST Request Returns 400 Bad Request:

I’m working on a Shopify app that includes an AJAX POST request to a proxy app URL. The request works fine locally and on ngrok, but when deployed to Shopify, I receive a 400 Bad Request error.

I made several posts on Shopify’s Community Forums, messaged Shopify developers, surfed Youtube, and checked the documentation many times – unfortunately I have yet to resolve this problem.

To provide more details, I am leveraging a .NET Razorpage application, where the frontend displayed by my proxy app is written in the razor view, and the handler methods my ajax calls hit are in the code-behind file. I configured my proxy url path as apps/member. The following ajax call is meant to take submitted form data by the user and pass it to my backend file. The ajax call that works locally and through ngrok’s url:

$.ajax({
    type: 'POST',
    url: '/apps/member?handler=MethodName',
    contentType: 'application/json',
    data: JSON.stringify(formData),
    headers: {
   
        'RequestVerificationToken': antiForgeryToken,
        'Content-Type': 'application/json'
        
    },
    dataType: 'json',
    beforeSend: function (jqXHR, settings) {
        console.log('Request URL:', settings.url);
        console.log('Request Type:', settings.type);
 
    },
    xhrFields: {
        withCredentials: true
    },
    success: function (response) {
        if (response.success) {
            $('#UserFeedbackMessage').text(response.message).css('color', 'green').show();
        } else {
            $('#UserFeedbackMessage').text(response.message).css('color', 'red').show();
        }
    },
    error: function (xhr, status, error) {
        console.error("Error updating collector info:", error);
        console.log("XHR:", xhr);
        console.log("Status:", status);
        console.log("Response Text:", xhr.responseText);
        $('#UserFeedbackMessage').text("An error occurred while updating your profile.").css('color', 'red').show();
    },
    complete: function (jqXHR, status) {
        console.log('Complete Response Headers:', jqXHR.getAllResponseHeaders());
    }
});

What makes this issue weirder is that this approach was working a year ago, but I know how frequently Shopify updates. I want to know the following:

  • Are only ajax GET requests allowed for proxy urls?

  • For moving data from the client side to an external api, what is the most common approach?

I tried to leverage a theme-app-extension by placing the ajax call in there and triggering it with a button to see if it made a difference – negative.

I tried to leverage the “method” and “post” attributes of the form tag:

<form id="updateCollectorForm" method="post" action="/apps/member-area?handler=UpdateCollectorInfo">

this also didn’t work (believe it or not, this was working a little over a year ago on Shopify…)

How i can insert data in ckeditor textarea

i am trying to edit a textarea whis is ckeditor but iam facing issue if some one kown please tell me.

HTML CODE

  <div class="col-md-12">
                <a class="btn btn-primary pull-right" id="nextdiv">
                    <i class="fa fa-plus"></i>
                </a>
                {!! Form::label('content', __('lang_v1.content') . ':*') !!}
                <div id="editor-container">
                    <div class="printableArea ck-editor__editable_inline">
                        {!! Form::textarea('content[]', null, [
                            'class' => 'form-control editor updateEditor',
                            'placeholder' => __('lang_v1.content'),
                            'id' => 'editor',
                        ]) !!}
                    </div>
                </div>
                <div id="container"></div>
            </div>

js code
$(“.template”).on(‘change’, function() {

$.ajax({
url: ‘/get/template/data/’ + templateId,
type: ‘GET’,
success: function(response) {
console.log(response.content)
CKEDITOR.instances[‘editor’].setData(response.content);
}
)}
}

IT GIVE THIS ERROR
TypeError: Cannot read properties of undefined (reading ‘editor’)

WHERE IS ISSUE I AM DOING