React testing library – TypeError: (0 , _axios.default) is not a function when using axios util that returns axios(config)

Im trying to write some unit test for my React app, and still in the process of getting familiar with the React testing library.

I created an empty page to just test on the axios api calls to make myself familiar with it. I have a axios util for customize basicAxios. When I follow the step for axios testing I got the typeError mentioned on the title.

here is my axios util code:

// axiosUtils.ts
import axios from "axios";
import { merge } from "lodash";
import type { AxiosPromise } from "axios";
import { getToken } from "./authUtils";

export const basicAxios = (options: {}): AxiosPromise<any> => {
  const token = getToken();
  const config = merge({ params: { token } }, options);
  return axios(config);
};

here is the test component:

// TestPage.tsx
const TestPage = () => {
  const [total, setTotal] = useState<number | null>(null);

  useEffect(() => {
    basicAxios({
      method: "POST",
      url: URL,
      data: payloadBody,
    }).then(({ data }) => {
      setTotal(data.total);
    });

    // async function getSummary() {
    //   try {
    //     const { data } = await axios.post(URL, payloadBody);
    //     setTotal(data.total);
    //   } catch (error) {
    //     console.log(error);
    //   }
    // }

    // getSummary();
  }, []);

  return (
    <Container>
      {!total ? (
        <Loader>Loading...</Loader>
      ) : (
        <div>
          Total amount of return:
          <Label data-testid="label">{total}</Label>
        </div>
      )}
    </Container>
  );
};

export default TestPage;

here is my jest setup to mock axios:

//axios.ts
export default {
  __esModule: true,
  post: jest.fn().mockResolvedValue({ data: {} }),
  get: jest.fn().mockResolvedValue({ data: {} }),
  default: jest.fn().mockResolvedValue({ data: {} }),
};

Lastly here is my test file:

// TestPage.test.tsx
import React from "react";
import { render } from "@testing-library/react";
import axios from "axios";
import "@testing-library/jest-dom/extend-expect";
import TestPage, { URL, payloadBody } from "../TestPage";

const mockedAxios = axios as jest.Mocked<typeof axios>;

test("show loader when it's fetching data, then render total num", async () => {
  mockedAxios.post.mockResolvedValueOnce({
    data: {
      aggregations: [],
      total: 144,
    },
  });

  const { findByTestId, getByText } = render(<TestPage />);

  expect(getByText(/loading.../i)).toBeInTheDocument();

  const labelValue = await findByTestId("label");

  expect(mockedAxios.post).toHaveBeenCalledWith(URL, payloadBody);
  expect(mockedAxios.post).toHaveBeenCalledTimes(1);
});

In my TestPage.tsx, if I use the comment-out code, the test pass without the error. The error occurs when I use basicAxios(used in multiple places in the app).
Below is the error log:

TypeError: (0 , _axios.default) is not a function

       9 |   const token = getToken();
      10 |   const config = merge({ params: { token } }, options);
    > 11 |   return axios(config);
         |          ^
      12 | };
      13 |

      at basicAxios (src/lib/axiosUtils.ts:11:10)
      at src/features/pages/TestPage.tsx:22:5
      at invokePassiveEffectCreate (node_modules/react-dom/cjs/react-dom.development.js:23487:20)
      at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:3945:14)
      at HTMLUnknownElement.callTheUserObjectsOperation (node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
      at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:338:25)
      at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
      at HTMLUnknownElementImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
      at HTMLUnknownElementImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
      at HTMLUnknownElement.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
      at Object.invokeGuardedCallbackDev (node_modules/react-dom/cjs/react-dom.development.js:3994:16)
      at invokeGuardedCallback (node_modules/react-dom/cjs/react-dom.development.js:4056:31)
      at flushPassiveEffectsImpl (node_modules/react-dom/cjs/react-dom.development.js:23574:9)
      at unstable_runWithPriority (node_modules/scheduler/cjs/scheduler.development.js:468:12)
      at runWithPriority$1 (node_modules/react-dom/cjs/react-dom.development.js:11276:10)
      at flushPassiveEffects (node_modules/react-dom/cjs/react-dom.development.js:23447:14)
      at Object.<anonymous>.flushWork (node_modules/react-dom/cjs/react-dom-test-utils.development.js:992:10)
      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:1107:9)
      at render (node_modules/@testing-library/react/dist/pure.js:82:26)
      at Object.<anonymous> (src/features/pages/__test__/TestPage.test.tsx:19:39)

Does anyone have experience on this issue?

setInterval setting this to window instead of class (calling class function)

render() {
    drawRect(0,0,canvas.width,canvas.height,3);
    console.log(this) // when called with setInterval(classObject.render, 1000), returns window; if called with (classObject).render returns (classObject)
    for (let i = 0; i <= this.sprites.length; i++) {
        if (this.sprites[i]) {
            let cs = this.sprites[i]
            cs.drawRoutine(cs.position.x,cs.position.y);
        }
    }
}
setRenderInterval(fps) {
    setInterval(this.render,1000/fps);
}

Here, let’s assume classObject is called game.
When game.render() is called normally, it has game as this. But when it’s called using setInterval, it has window as this. How can I circumvent this?
this.sprites is an array of sprites for the game, and it needs to be accessed using this, as there can be multiple games with different variable names. And cs.drawRoutine is a function within the sprite that just draws in the canvas. The function runs when normally called.

He’i’p.microsoft.com Talk 8779477788 to a person = …

He’i’p.microsoft.com Talk 8779477788 to a person
This Help.microsoft.com +1-877-947-7788 rebuilds the data utility but doesn’t fix the help.microsoft.com. This is often a complicated issue and has required fixing as soon as possible. When this Help.microsoft.comoccurs users generally get the message, ‘Recover data file’ or ‘Your HELP.MICROSOFT.COMisn’t working. For this help.microsoft.com, the HELP.MICROSOFT.COMfile must fix and recovered. To stop this Help.microsoft.comfrom doing any damage, restore a backup copy, and then condense the company file. It’s a really Support software issue that needs immediate HELP.MICROSOFT.COMmention and will be fixed as soon as possible. How does HELP.MICROSOFT.COM +1-877-947-7788 Support Number affect? As mentioned earlier they skipped 111 Help.microsoft.comis one of the most occuCOIN.BASEing help.microsoft.coms in MS OFFICE. So it means the business or user is at constant risk of Contact of HELP.MICROSOFT.COMSupport Number HELP.MICROSOFT.COMSupport Phone Number mostly occurs within the application system because of file damage. The file must be repaired by either restoration or by replacing it with an earlier saved backup copy of the stored data. HELP.MICROSOFT.COMTECHNICAL Support phone number – However, this is often HELP.MICROSOFT.COMCustomer Support phone number software within the end and that’s why HELP.MICROSOFT.COMCustomer Support phone number sometimes it does face issues affecting the business operations of its users. An issue that’s quite common has the HELP.MICROSOFT.COM +1-877-947-7788 Support Phone Number. This Help.microsoft.comcode recovers the data that has been founded and again rebuilds the data section. losing their financial and operational data. Then they need storing in MS OFFICE. It’s imperative to make a backup of the data to stop problems in the future. Steps to resolve HELP.MICROSOFT.COMCustomer Support Phone Number Wherever there’s a problem there’s always a resolution. A similar is that the case with HELP.MICROSOFT.COM +1-877-947-7788 Support Number. Below mentioned are some steps that may help to repair can pass few tests and if your file passes these tests, then the backup of the file has automatically been created in the ADR folder. After this, the logging program of ADR transactions will invoice all the transactions quickly also as automatically. Ithave integrated with the file from a specific instance on HELP.MICROSOFT.COM +1-877-947-7788 Software. Once the recovering process is complete, HELP.MICROSOFT.COMaccounting software will create a duplicate of that file. But if your application is open, you’d not find any backup created. This may produce two backup duplicates and also the latest one would be 12 hours old while another would be 24 hours old. This way the oldest file would get deleted.
bold
italic

quote

How to save multiple username and password in javascript

First – I know not to keep passwords and logins that way. I am only doing this as a task.

So, i need to save username and password from register form, and next use it in login form.
How i can do this with only html and JS?

Now i have something like that:

let user_name = document.getElementById("username");
let user_paswrd = document.getElementById("password");


let store_data = () => {
  let input_username = localStorage.setItem("username", user_name.value);
  let input_password = localStorage.setItem("password", user_paswrd.value);

};

https://jsfiddle.net/gcu78z20/

it’s saving username and password in localstorage, but I need to save all registered username and password. Then in login menu get it back when login. How can I do it? It is better to do this with localstore or cookie?

IMPORTANT INFORMATION
this form will only be opened locally. The website will not be on the web.

How can I get value from api to google chart?

I have my api like this:

const api = "https://api.exchangerate-api.com/v4/latest/USD";

and I want to download it then separate the value to Country and Ratio and embed them to google table. I have found a chart like this. I want to modify the code so it can display in a table with country and corresponding ratio. But at this point, I have no idea how to do it. May I ask for some hint ?

TypeError cannot read property url of undefined on strapi

I have a list of items. Some have a download link and some not.

If I try to render a an undefined url, I have this error. So I tried this :

if (spectacle.pdf.url) {
    const pdf = spectacle.pdf.url;
    const flag = `/fl_attachment:dossier${spectacle.slug}`;
    const position = 47;
    const output = [pdf.slice(0, position), flag, pdf.slice(position)].join('');
}

But I now have an other error telling me that output is not defined.
Does someone can explain me how to do it well to stop a function to load if undefined ?

[slug].js

const Spectacle = ({ spectacle, spectacles, categories }) => {



  const slideRight = () => {
    const slider = document.querySelector('.gallery');
    console.log(slider);
    slider.scrollBy({
      left: 450,
      behavior: 'smooth'
    });
  }

  const slideLeft = () => {
    const slider = document.querySelector('.gallery');
    console.log(slider);
    slider.scrollBy({
      left: -450,
      behavior: 'smooth'
    });
  }

  useEffect(() => {
    const bigTitle = document.getElementById('big-title');
    const vertTitle = document.getElementById('ver-title');
    const title = spectacle.title;
    if (title.length > 30) {
      bigTitle.style.fontSize = "8vw";
      vertTitle.style.fontSize = "3rem";
    }
  }, []);

  
if (spectacle.pdf.url) {
    const pdf = spectacle.pdf.url;
    const flag = `/fl_attachment:dossier${spectacle.slug}`;
    const position = 47;
    const output = [pdf.slice(0, position), flag, pdf.slice(position)].join('');
}


  return (
    <>
      <div className="spectacle-header">
        <img src={spectacle.image.url} />
        <div className="spectacle-titles">
          <h1 id="big-title" className="big-title">{spectacle.title}</h1>
          <h5 className="subtitle">{spectacle.sousTitre}</h5>
        </div>
      </div>
      <Container className="spectacle-text">
        <Row className="bloc-mob">
          <Col className="ext a">
            <h1 id="ver-title" className="vertical-title red">{spectacle.title}</h1>
            <h2 className="quote shows">{spectacle.citation}</h2>
          </Col>
          <Col className="middle-col">
            <p className="">
              <Moment format="YYYY" className="date">{spectacle.year}</Moment>
            </p>
            <Row className="status">
              <Col>
                <span>{spectacle.status}</span>
              </Col>
              <Col>
                <span>{spectacle.category.name}</span>
              </Col>
            </Row>
            <div>
              <p className="description" id='desc'>
                <ReactMarkdown source={spectacle.description} />
                <a href={output} download="newfilename"><h4>Télécharger le document</h4></a>
              </p>
              <div className="video"
              dangerouslySetInnerHTML={{ __html: spectacle.video}} >
              </div>
            </div>
          </Col>
          <Col className="ext b">
            <p className="generic" id="generic">
              <ReactMarkdown source={spectacle.cast} />
            </p>

           
            <div className="scroll-down">
              Scroll down
              <img src="https://res.cloudinary.com/ciefact/image/upload/v1634668021/arrow_0e058f1520.svg"
                className="arrow-down" />
            </div>
          </Col>
          {/* <Col className="illu">
            <img src={spectacle.Illustration.url} />
          </Col> */}
        </Row>

        <Row className="gallery">

          {spectacle.galery.map((item) => (
            <ModalImage
              key={item.id}
              small={item.url}
              large={item.url}
              alt={item.title}
              hideZoom={true}
              hideDownload={true}
            />
          ))}
        </Row>
        <button
          id="slideLeft"
          type="button"
          onClick={slideLeft}
        >
          <img src="https://res.cloudinary.com/ciefact/image/upload/v1634668021/arrow_0e058f1520.svg"
            className="arrow-down" />
        </button>
        <button
          id="slideRight"
          type="button"
          onClick={slideRight}
        >
          <img src="https://res.cloudinary.com/ciefact/image/upload/v1634668021/arrow_0e058f1520.svg"
            className="arrow-down" />
        </button>
      </Container>
    </>
  )
}

export async function getStaticPaths() {
  const spectacles = await fetchAPI("/spectacles")

  return {
    paths: spectacles.map((spectacle) => ({
      params: {
        slug: spectacle.slug,
      },
    })),
    fallback: 'blocking',
  }
}

export async function getStaticProps({ params }) {
  const spectacle = (await fetchAPI(`/spectacles?slug=${params.slug}`))[0]

  const [spectacles, categories] = await Promise.all([
    fetchAPI("/spectacles"),
    fetchAPI("/categories"),
  ])
  return {
    props: { spectacle: spectacle, spectacles, categories },
    revalidate: 1,
  }
}

export default Spectacle 

Export Object after promise is resolved

I am using “load” and “OBJloader” from loaders.gl/core and loaders.gl/obj to load a mesh to export it as a const so other module can use it, currently I am using this

export const myMesh = Object.freez({
     mesh : load(path_to_obj_file,OBJLoader),
     origin: [1.4,0,2.2],
     dimensions: [2,2,2],
     scale: 1
)}

but then I find out that I can calculate the origin and dimensions from the obj file itself without the need to put them manually (I used to calculate them form meshlab), and I can do it from the load function itself

load(path_to_obj_file,OBJLoader).then((obj)=>{
console.log(obj.schema.metadata.get["boundingBox"]
}

boundingBox would be like that [[-1.4,-1,-2],[0.6,1,-0.2]] (numbers are not accurate at all).
and I can calculate origin and dims from the boundingBox.

my question is, how can I export the const myMesh now? since I have promise, also when we write:

mesh : load(path_to_obj_file,OBJLoader) 

could that cause a problem since load returns a promise ? (currently it is working correctly)

I tried:

export const loadMyMesh = load(path_to_obje_file,OBJLoader).then((obj) =>{
     const myMesh = Object.freez({
     mesh: obj,
     origin: calculateOrigin(obj),
     dimensions: claculateDim(obj),
     scale: 1
    });
  return myMesh
})

where calculateOrigin and calculateDim are functions used to get the boundingbox and calculate the origin and the dims, but that didn’t work.

so any solution ?

React-the state is already updated, but when calling setstate again, the value is still the old value

If I enter a fromAmount which is larger than the current toAmount, then toAmount value is expected to become fromAmount + $1.


    const initialObj = {
      fromAmount: '',
      toAmount: '',
      comment: ''
    };
    const [itemObj, setItemObj] = useState(initialObj);

    const setItemFieldHandler = (key, value) => {
      console.log("set", key, value);
      console.log("old state: ", itemObj);
      
      const newState = {
        ...itemObj,
        [key]: value
      };
      
      console.log("new state: ", newState);
      
      setItemObj(newState);
    };


    const handleFromAmountInput = useCallback((value) => {
       setItemFieldHandler('fromAmount', value);
      //check if from amount > to amount, 
      // then set toAmount = fromAmount + 1
      if(areBothAmountsValid()) {
         const newToAmount = value + 1;
         handleToAmountInput(newToAmount);
      }
    }, [itemObj]);


    const handleToAmountInput = useCallback((value => {
      setItemFieldHandler('toAmount', value);
    }, [itemObj]);
    }

The current from-amount is 1, to-amount is 5. If I change from-amount to 10, the console log is:

set fromAmount 10
old state: 
  {
    fromAmount: 1,
    toAmount: 5,
    comment: ''
  }
new state: 
   {
    fromAmount: 10,
    toAmount: 5,
    comment: ''
  }

set toAmount 11
old state: 
  {
    fromAmount: 1,
    toAmount: 5,
    comment: ''
  }
new state: 
   {
    fromAmount: 1,
    toAmount: 11,
    comment: ''
  }

What confuses me is that, fromAmount is already set as 10, why when calling handleToAmountInput(), the fromAmount’s value is still 1.

At first, I thought it is because the setState is async, so I used setTimeOut to make handleToAmountInput() running after like 5s to test, but the issue is still the same.

Does anyone know the reason and how to solve it?

React / Typescript : pushing obj into array of object and undefined type

I’m beginnig my journey into TypeScript in React and to experiment what I’ve learn, I’ve try a simple Todo App.
Everything is working fine except ONE things !

When I’m pushing ‘newTask’
When I’m hovering ‘newTask’ here’s the hint (Google Trad from French) :

The ‘Todo | undefined ‘is not attributable to the parameter of type’ Todo ‘.
Cannot assign type ‘undefined’ to type ‘Todo’.

I guess it’s related to something here :

let [newTask, setNewTask] = useState<Todo>();

because if I type useState<any>(); I don’t have any error..

Here’s the full code :

import React, { useState } from "react";

// INTERFACES
interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

export const TodoComponent = () => {
  // STATE
  const initialTodos: Todo[] = [
    { id: 0, text: "Todo 1", completed: false },
    { id: 1, text: "Todo 2", completed: true },
    { id: 2, text: "Todo 3", completed: false },
  ];

  const [todos, setTodos] = useState<Todo[]>(initialTodos);

  let [newTask, setNewTask] = useState<Todo>();

  // ACTIONS
  const handleClickOnComplete = (id: number, completed: boolean) => {
    const newTodos = [...todos];
    newTodos[id].completed = !completed;
    setTodos(newTodos);
  };

  const handleRemove = (todo: Todo) => {
    const newTodos = todos.filter((t) => t !== todo);
    setTodos(newTodos);
  };

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setNewTask({
      id: todos.length,
      text: event.target.value,
      completed: false,
    });
  };

  const handleSubmitNewTodo = () => {
    const newTodos = [...todos];
    console.log(newTask, newTodos);
    newTodos.push(newTask);
    setTodos(newTodos);
  };

  return (
    <div>
      <h1>Todo App !</h1>

      <div>
        {todos.map((todo) => {
          return (
            <div key={todo.id}>
              {todo.id} - {todo.text} -{" "}
              <input
                type="checkbox"
                checked={todo.completed}
                onChange={() => handleClickOnComplete(todo.id, todo.completed)}
              />
              <button onClick={() => handleRemove(todo)}>Remove task</button>
            </div>
          );
        })}
      </div>

      <hr />

      <div>
        <input placeholder="Add todo" type="text" onChange={handleChange} />
        <button onClick={handleSubmitNewTodo}>Add todo</button>
      </div>
    </div>
  );
};

Problem is in handleSubmitTodo

Thanks for your help and advices.
Take care.

Remix: middleware pattern to run code before loader on every request?

Is there a recommended pattern in Remix for running common code on every request, and potentially adding context data to the request? Like a middleware? A usecase for this might be to do logging or auth, for example.

The one thing I’ve seen that seems similar to this is loader context via the getLoadContext API. This lets you populate a context object which is passed as an arg to all route loaders.

It does work, and initially seems like the way to do this, but the docs for it say…

It’s a way to bridge the gap between the adapter’s request/response API with your Remix app

This API is an escape hatch, it’s uncommon to need it

…which makes me think otherwise, because

  • This API is explicitly for custom integrations with the server runtime. But it doesn’t seem like middlewares should be specific to the server runtime – they should just be part of the ‘application’ level as a Remix feature.

  • Running middlewares is a pretty common pattern in web frameworks!

So, does Remix have any better pattern for middleware that runs before every loader? If so, how do you use it?

Why is this javascript / css animation only working on the first of its kind and not the rest?

I am trying to get multiple different circles to do this transition, but only the first one will trigger the effect (regardless of where the rest are on the page)

javascript

let circle = document.querySelector('.circle')

circle.addEventListener('mouseenter', () => {
    if(!circle.classList.contains('hover')){
        circle.classList.add('hover');
    }
})

circle.addEventListener('mouseleave', () =>{
    if(circle.classList.contains('hover')){
        circle.classList.remove('hover');
    }
})

css

.circle {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
    width: 100px;
    background: slateblue;
    border-radius: 100px;
    font-size: 1.5rem;
    color: #fff;
    cursor: pointer;
    transition: cubic-bezier(0.075, 0.82, 0.165, 1) 3s;
}

.hover {
  transform: scale(1.5);
}

html

<div class="circle">1</div>
<div class="circle">2</div>

Is it possible to extract several js files out of one entry point in webpack?

I have set up webpack to generate the public directory from my development enviroment. I have several pages that are being built.
Therefore my entry configuration looks like this:

entry: {
    page_one: [one/main.js, one/index.html, ...]
    page_two: [two/main.js, two/index.html, ...]
}

This works perfectly fine. However i also want to extract some js-files that depends on some serverside renderings. Therefore i dont always have to include those. My initial aproach was to simply add the js file to my entryset. Looks like this:

entry: {
    page_one: [one/main.js, one/maybe.js, one/index.html, ...]
    page_two: [two/main.js, one/another.js, two/index.html, ...]
}

The problem is that both js files get packed into one output file. That kinda makes sense to me but is there some way to archieve my goal of exporting them both separately on the same entrypoint?

Folder structure i get:

 - public
   - one
     - index.html
     - main.js
   - two
     - index.html
     - main.js

Folder structure i want:

 - public
   - one
     - index.html
     - main.js
     - maybe.js
   - two
     - index.html
     - main.js
     - another.js

As mentioned maybe.js and another.js are there but packed into main.js but i want them to be extracted separately.

W3C HTML5 ERROR Start tag head seen but an element of the same type was already open

Start tag head seen but an element of the same type was already open.
also I got some other errors:

” Saw <?. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.) “

and

” No p element in scope but a p end tag seen. “

I have no clue how to fix them.

<!DOCTYPE html>
    <html lang="pl">
    <style>
    html, body { margin: 0; padding: 0; color: black; background-color: grey;}
    #strona { position: absolute; color: white}
    #rects { position: relative; width: 300px; height: 125px; border: 1px solid #FF0000; color: yellow; margin: 5px; padding: 2px;}
    </style>
    <head>
        <meta charset="UTF-8"/>
        <title> site</title>
    </head>
    <body>
    <div> <script>
    function clickbutton1(){
        document.getElementById("opis").innerHTML = Date();
    }
    </script>
    </div>
    
        <div id="strona">
            <h1>test</h1>
    <?php
    echo "<p>data replacement</p>";
    echo "<div id='rects'>
        <!-- starting of the function -->
    <p id='opis'> internal description </p>
    <script>
    document.getElementById('rects').onclick = clickbutton1;
    </script>
    </div>";
    ?>
    </div>
    
    
    </body>
    
    </html>```

Actionscript ( ) vs Javascript ( )

For same string actionScript’s function charCodeAt returns unicode character 13 and javascript’s function charCodeAt returns unicode character 10. Is there a reason why a line feed is returned by JS and a carriage return is returned by AS. After reading a few answers online I have come to the conclusion that both of these do not have much difference, can anyone please explain why was this change made.