React Testing Library – unable to find the input with data-testid

So when I try to catch input by getByTestId I get an error:

TestingLibraryElementError: Unable to find an element by: [data-testid=”Name”]

I’ve changed method to queryByTestId and I’d been getting error:

Unable to fire a “change” event – please provide a DOM element.

I found out that if I enter following code:

expect(input).toBeNull;

I don’t get any errors at all and test is passed.

AddUser.test.js:

import React from 'react';
import '@testing-library/jest-dom';
import AddUser from 'views/AddUser';
import Dashboard from 'views/AddUser';
import { screen, fireEvent } from '@testing-library/react';
import { renderWithProviders } from 'helpers/renderWithProviders';

describe('Input With Button', () => {
  it('Renders the component', () => {
    renderWithProviders(
      <>
        <AddUser />
        <Dashboard />
      </>
    );
    const input = screen.queryByTestId('Name');
    console.log(input);
    expect(input).toBeNull; // PASSED!

    fireEvent.change(input, { target: { value: 'Andrew' } }); // ERROR!
    // fireEvent.change(screen.getByTestId('Attendance'), { target: { value: '89%' } });
    // fireEvent.change(screen.getByTestId('Average'), { target: { value: '4.1' } });
    // fireEvent.click(screen.getByText('Add'));
    // screen.getByText('Andrew');
  });
});

AddUser.js:

// ...
return (
        <ViewWrapper as="form" onSubmit={handleSubmitUser}>
          <Title>Add new student</Title>
          <FormField label="Name" id="name" name="name" value={formValues.name} onChange={handleInputChange} />
          <FormField label="Attendance" id="attendance" name="attendance" value={formValues.attendance} onChange={handleInputChange} />
          <FormField label="Average" id="average" name="average" value={formValues.average} onChange={handleInputChange} />
          <Button type="submit">Add</Button>
        </ViewWrapper>
      );
// ...

FormField.js:

// ...
return (
<Wrapper>
  <Label htmlFor={id}>{label}</Label>
  <Input name={name} id={id} type={type} value={value} onChange={onChange} data-testid={label} />
</Wrapper>
);
// ...

HTML Output of input element:

<input name="name" id="name" type="text" data-testid="Name" class="sc-gsDKAQ dfgpGW" value="">
                                         ------ HERE ------

Thank you in advance!

Resolving invalid_grant in Reddit

I am trying to authenticate my third party app against a Reddit account using oauth.

I first hit this endpoint

let authorizationUrl = https://www.reddit.com/api/v1/authorize?client_id=${redditClientId}&response_type=code&state=${state}&redirect_uri=${oAuthCallbackURL}&duration=permanent&scope=${scopes};

and then I was sent a code to my callback url

then I hit the next endpoint like this:

    let accessTokenUrl = `https://www.reddit.com/api/v1/access_token`;
    let accessTokenRequest = new URLSearchParams();
    accessTokenRequest.append("grant_type", "authorization_code");
    accessTokenRequest.append("code", code);
    accessTokenRequest.append("redirect_uri", oAuthCallbackURL);

    let redditClientId = process.env.REDDIT_CLIENT_ID;
    let redditSecret = process.env.REDDIT_SECRET;
    const clientIdAndSecretBase64 = 
    Buffer.from(`${redditClientId}:${redditSecret}`).toString('base64');
    try {
        let authorizationCodeResponse = await axios.post(accessTokenUrl, accessTokenRequest, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${clientIdAndSecretBase64}`
            }
        });
        let { data } = authorizationCodeResponse;
        console.log(authorizationCodeResponse);
        console.log(`Reddit OAUTH Response=${JSON.stringify(data, null, 2)}`);
    } catch (e) {
        console.log(e);
}

But all I keep getting back is this error:

Reddit OAUTH Response={
“error”: “invalid_grant”
}

On careful observation of Reddit docs I saw a line that says invalid_grant is only thrown when

The code has expired or already been used

This makes no sense because during the testing phase I forgot to save the access token. I should be able to reinitiate this request anytime. Why this limitation? I wanted to really see what the response is like before saving the access token. Now, clearly it seems there is no way to resolve this issue.

But any insight will be really appreciated.

Implementing Winston as a Writable Stream

I was planning on implementing Winston for logging in my project but I needed to implement it as a writable stream. I’ve noticed that there is a export for writable in the Winston package itself. My original plan was to simply wrap Winston in a writable stream, but if Winston can export itself as a Writable stream how would I go about doing this while keeping the same customizability as just exporting Winston normally?

I am trying to have a second slider on the same page but its not working

I am trying to have a second slider on the same page but its not working.
The first one works fine but the second one is not working. I think there is something wrong with the parent element method but cant wrap my head around it.

var ids = ["view_0", "view_1", "view_2", "view_3"]
let current_id = 0;

function next(productnr) {
  if (document.getElementById(ids[current_id]).parentElement.id == productnr) {
    let last_array_position = ids.length;
    document.getElementById(ids[current_id]).classList.remove("show");
    current_id++;
    if (current_id >= last_array_position) {
      current_id = 0;
    }
    document.getElementById(ids[current_id]).classList.add("show");
  }
}
<style>#1 img {
  display: none;
}

#1 img.show {
  display: block;
}

</style>
<!DOCTYPE html>
<html>

<head>
  <title>Multiple Slider</title>
</head>

<body>

  <article id=1>
    <img class="show" id="view_0"></img>
    <img id="view_1"></img>
    <img id="view_2"></img>
    <img id="view_3"></img>
    <button><</button>
    <button onclick="next(1)">></button>
    <article id=2>
      <img class="show" id="view_0"></img>
      <img id="view_1"></img>
      <img id="view_2"></img>
      <img id="view_3"></img>
      <button><</button>
      <button onclick="next(2)">></button>




</body>

find object if attribute not exists and add that attribute with value

I have array of objects like below:

checklist= [
    {
      "participantId": 13,
      "rankStatus": "participated",
      "rank": 3,
      "comment": "my comment",
      "horse_name": "test232 fdfgdg",
      "country": "Afghanistan",
      "life_number": null
    },
    {
      "participantId": 12,
      "rankStatus": "eliminated",
      "comment": null,
      "horse_name": "test horse",
      "country": "Algeria",
      "life_number": "234234"
    },
    {
      "participantId": 11,
      "rankStatus": null,
      "rank": null,
      "comment": null,
      "horse_name": "tesdfs",
      "country": "Afghanistan",
      "life_number": null
    },
    {
      "participantId": 10,
      "rankStatus": null,
      "comment": null,
      "horse_name": "nam horse",
      "country": "India",
      "life_number": "fh345"
    }
  ];

In above array of objects, I need to add rank=0 to the objects where rank is not present.

I tried like below, but its not working.

checklist.filter(x =>  !x.hasOwnProperty('rank') ).map(x => x.rank == 0);

What is right way of doing this? Please help and guide. Thanks

How to implement a Fibonacci sequence in JavaScript?

I need to implement a Fibonacci sequence Оthrough a function for my homework. And I need to implement a function so that each subsequent call will output the next number in the sequence. It seems simple if you pass an argument to the function, but I’m not allowed to do that by the assignment. I have implemented this function with an argument, the code is shown below:

function helperFibonacci (n) {
 let number1 = 0;
 let number2 = 1;

 for (i = 0; i < n; i++) {
 let current = number1 + number2;
 number1 = number2;
 number2 = current;
     console.log(current);
  }
 }

 helperFibonacci(2); 

Please help me implement this function without passing an argument. thanks!

Node.js spawn is not running python command

I am trying to run a python command from Node.js v12.22.1 in a web application. This is the method that is being called in one of my controllers:

async start ({request,response,params}) {
                Log.create(request.request.headers.user,request.url())
                const { spawn } = require('child_process');
                const command = spawn('python',[process.env.BUS_PATH+'inventario/SystemDManager.py', params.name, "start"]);

                var responseData = "teste";
                command.stdout.setEncoding('utf-8');
                command.stdout.on('data', function (data){
                        responseData += data.toString();
                });
                command.stderr.on('data', function (data){
                        responseData += data.toString();
                });
                command.stdout.on('end',function(data){
                        console.log(responseData);
                });

                return responseData
        }

Variables are correctly instantiated, I have already printed them:

process.env.BUS_PATH = /home/ubuntu/

params.name = witty

So that the request command is:

python /home/ubuntu/inventario/SystemDManager.py witty start

This command runs perfectly when I type it directly into the shell console. However, nothing happens when running it through spawn. Moreover, when I change spawn arguments to:

spawn('cp',[process.env.BUS_PATH+'inventario/SystemDManager.py', "dummy.txt"]);

It works fine, it makes the file copy … Note that my responseData variable ends with “teste”, as if nothing had happened. I have even tried to change “python” to “/usr/bin/python”, but everything remains the same.

Does anyone has a tip of what is going wrong that python command is no being executed?

Vuetify : 2 rows in a card

I tried to create new row to place my table component there, and I want it to take the entire row

I’ve tried

<v-col cols="12">
    <Table />
</v-col>

It goes to the right

enter image description here

I’m trying to have 2 rows in a card

  • first row (icon) + title & subtitle
  • second row table

enter image description here

<template>
    <v-container fluid class="my-5">
        <v-row>
            <v-col cols="12">
                <v-card elevation="2" class="d-flex">
                    <!-- Icon -->
                    <v-col cols="1">
                        <v-card-title>
                            <v-btn text color="black">
                                <v-icon left x-large>{{ icon }}</v-icon>
                            </v-btn>
                        </v-card-title>
                    </v-col>

                    <!-- Title & Subtitle -->
                    <v-col cols="11">
                        <v-card-title>
                            {{ title }}
                        </v-card-title>
                        <v-card-subtitle style="color: #757575"> {{ subtitle }} </v-card-subtitle>

                        <Table />
                    </v-col>
                </v-card>
            </v-col>
        </v-row>
    </v-container>
</template>

Submit POST form from a function

I have a form that I would like to submit (POST) when a function is called outside the form and without a button (It works with a button).

I have tried to use this: document.getElementById('liked').submit();

But then it just pastes this into the url: http://localhost:3000/?postId=108&userId=1

I have tried to put method="post" in the form tag, but then it says “CANNOT POST”

The post is done with Axios.

Besides that, I would like it to NOT reload the page/component

This is my form:

<form id="liked" name="liked" onSubmit={handlePost}>
  <input hidden name="postId" id="postId" value={product.id} />
  <input hidden name="userId" id="userId" value={currentUser.id} />
</form>;

This is my callback that call the Axios post function:

const handlePost = useCallback((event) => {
    event.preventDefault();
    context.postBookmark(event.target);
  });

This is where I would like the form to be submitted:

const onSwipe = (direction) => {
    if (direction == "right") {
      // SUBMIT HERE
      document.getElementById("liked").submit();
    }
  }

Javascript for loop causes error – maybe technique wrong?

For introduction: https://mytechservinginternetmeals.blogspot.com/2021/10/how-to-start-making-browser-video-game.html

Could anyone tell how to fix the error in code that try’s to check errors in it?

THIS CAUSES TypeError: Cannot read properties of undefined (reading ‘resourcePath’)

const novietojumi = [
  "0.1221 0.1221",
  "0.1111 0.1111",
  "0.1111 0.1111",
  "0.1111 0.1111",
  "0.1111 0.1111",
  "0.1111 0.1111",
  "0.1111 0.1111",
  "0.1111 0.1111",
];
let arrayLength = novietojumi.length;

console.log(arrayLength);

for (let i = 0, x = 0, y = 0; i < arrayLength; i++, y++, x++) {
  //console.log(novietojumi[i]);

  const NOV = novietojumi[i].split(" ");
  console.log(NOV);
  console.log("KOORD1", NOV[0]);
  console.log("KOORD2", NOV[1]);
  _P.set(NOV[0], 0.0, NOV[1]);
  _P.add(center);
  _P.multiplyScalar(50.0);

  const key = '__scenery__[' + _P.x + '][' + _P.z + ']';
  if (this.FindEntity(key)) {
    //continue;
  }

  _V.copy(_P);

  _P.x += (this.noise_.Get(_P.x, 0.0, _P.z) * 2.0 - 1.0) * 25.0;
  _P.z += (this.noise_.Get(_P.x, 1.0, _P.z) * 2.0 - 1.0) * 25.0;
  _P.y = terrain.GetHeight(_P)[0];

  const biome = this.FindBiome_(terrain, _P);

  const roll = this.noise_.Get(_V.x, 2.0, _V.z);
  if (roll > _BIOMES[biome]) {
    //continue;
  }

  const e = this.SpawnAt_(biome, _P);

  //console.log(e);
  e.SetPosition(_P);

  //console.log(e, key);
  this.Manager.Add(e, key);

  e.SetActive(false);
  this.crap_.push(e);
}

THIS DOES NOT:

for (let x = -10; x <= 10; ++x) {
  for (let y = -10; y <= 10; ++y) {
    _P.set(x, 0.0, y);
    _P.add(center);
    _P.multiplyScalar(50.0);

    const key = '__scenery__[' + _P.x + '][' + _P.z + ']';
    if (this.FindEntity(key)) {
      continue;
    }

    _V.copy(_P);

    _P.x += (this.noise_.Get(_P.x, 0.0, _P.z) * 2.0 - 1.0) * 25.0;
    _P.z += (this.noise_.Get(_P.x, 1.0, _P.z) * 2.0 - 1.0) * 25.0;
    _P.y = terrain.GetHeight(_P)[0];

    const biome = this.FindBiome_(terrain, _P);

    const roll = this.noise_.Get(_V.x, 2.0, _V.z);
    if (roll > _BIOMES[biome]) {
      //continue;
    }

    const e = this.SpawnAt_(biome, _P);

    e.SetPosition(_P);

    this.Manager.Add(e, key);

    e.SetActive(false);
    this.crap_.push(e);
  }
}

THIS CODE sample is where error gets found :

const _SCENERY = {
  birch1: {
    base: 'Birch_1.fbx',
    resourcePath: './resources/trees/FBX/',
    names: {
      Bark: 'Birch_Bark.png',
      Leaves: 'Birch_Leaves_Yellow.png'
    },
    scale: 0.075,
    biomes: ['forest'],
    collision: true,
  },
  tree1: {
    base: 'Tree_1.fbx',
    resourcePath: './resources/trees/FBX/',
    names: {
      Bark: 'Tree_Bark.jpg',
      Leaves: 'Leaves_Blue.png'
    },
    scale: 0.1,
    biomes: ['forest'],
    collision: true,
  },
  rock1: {
    base: 'Rock_1.fbx',
    resourcePath: './resources/nature/FBX/',
    names: {},
    scale: 0.025,
    biomes: ['arid', 'desert'],
  },
  rockMoss1: {
    base: 'Rock_Moss_1.fbx',
    resourcePath: './resources/nature/FBX/',
    names: {},
    scale: 0.025,
    biomes: ['forest'],
  },
  plant1: {
    base: 'Plant_1.fbx',
    resourcePath: './resources/nature/FBX/',
    names: {},
    scale: 0.05,
    biomes: ['forest', 'arid'],
  },
  grass1: {
    base: 'Grass_1.fbx',
    resourcePath: './resources/nature/FBX/',
    names: {},
    scale: 0.05,
    biomes: ['forest', 'arid'],
  },
  flowers1: {
    base: 'Flowers.fbx',
    resourcePath: './resources/nature/FBX/',
    names: {},
    scale: 0.05,
    biomes: ['forest'],
  },
};

const _BIOMES = {
  desert: 0.1,
  forest: 0.8,
  arid: 0.6,
};

const multiples = {
  birch1: {
    name: 'Birch_',
    key: 'birch',
    num: 10
  },
  tree1: {
    name: 'Tree_',
    key: 'tree',
    num: 10
  },
  rock1: {
    name: 'Rock_',
    key: 'rock',
    num: 7
  },
  rockMoss1: {
    name: 'Rock_Moss_',
    key: 'rockMoss',
    num: 7
  },
  plant1: {
    name: 'Plant_',
    key: 'plant',
    num: 5
  },
  grass1: {
    name: 'Grass_',
    key: 'grass',
    num: 2
  },
};


SpawnAt_(biome, spawnPos) {
  const matchingScenery = [];
  for (let k in _SCENERY) {
    if (_SCENERY[k].biomes.indexOf(biome) >= 0) {
      matchingScenery.push(k);
    }
  }

  const roll = this.noise_.Get(spawnPos.x, 3.0, spawnPos.z);
  const randomProp = _SCENERY[
    matchingScenery[Math.round(roll * (matchingScenery.length - 1))]];

  const e = new entity.Entity();
  e.AddComponent(new render_component.RenderComponent({
    scene: this.params_.scene,
    resourcePath: randomProp.resourcePath,
    resourceName: randomProp.base,
    textures: {
      resourcePath: './resources/trees/Textures/',
      names: randomProp.names,
      wrap: true,
    },
    emissive: new THREE.Color(0x000000),
    specular: new THREE.Color(0x000000),
    scale: randomProp.scale * (0.8 + this.noise_.Get(spawnPos.x, 4.0, spawnPos.z) * 0.4),
    castShadow: true,
    receiveShadow: true,
    onMaterial: (m) => {
      if (m.name.search('Leaves') >= 0) {
        m.alphaTest = 0.5;
      }
    }
  }));

  if (randomProp.collision) {
    console.log("e");
    e.AddComponent(
      new spatial_grid_controller.SpatialGridController({
        grid: this.params_.grid
      }));
  }

  const q = new THREE.Quaternion().setFromAxisAngle(
    new THREE.Vector3(0, 1, 0), this.noise_.Get(spawnPos.x, 5.0, spawnPos.z) * 360);
  e.SetQuaternion(q);

  return e;
}

How to create a reusable array.reduce function

Im working on solving an Anagram problem wanted to get clever with Javascript methods

here is my code

const stringA = ["hello"]
const stringB = ["olhle"]
let cleanStrA = stringA.replace(/[^w]/g, '').toLowerCase().split('')
let cleanStrB = stringB.replace(/[^w]/g, '').toLowerCase().split('')

function charMap (str) {
    str.reduce((acc, cur) => {
        acc[cur] = acc[cur] + 1 || 1 
        return acc
    },{})
    return str
}

let buildCharMapA = charMap(cleanStrA)
let buildCharMapB = charMap(cleanStrB)
console.log(buildCharMapA)

result = ("hello")

When i console log this it returns the original array, but when i remove the function encompassing the reduce method it create the intended object

    let reduceFn = cleanStrA.reduce((acc, cur) => {
        acc[cur] = acc[cur] + 1 || 1 
        return acc
    },{})
console.log(reduceFn)
result = {h:1, e:1, etc.}

What gives?

How to select nth parent p tag of div? [duplicate]

Am wondering how can we select 2nd p tag of a div.

html

<div id="my_div">
<p>
   <label>aaaa</label>
   <label>aaaa</label>
   <label>aaaa</label>
</p>
<p>
   <label>aaaa</label>
   <label>aaaa</label>
   <label>aaaa</label>
</p>
<p>
   <label>aaaa</label>
   <label>aaaa</label>
   <label>aaaa</label>
</p>

</div>

what i tried.

jQuery("#my_div :nth-child(2)").attr('style','width: 50%;');

this works but it also select p tag 2nd <label> but am only interested in parent p tag do not want to touch p tag childs. So any idea how to do it.

On Opening one dropdown the other drop down if it is opened should close

I want to add the logic of automatically closing an already opened drop-down menu, on opening the other menu. For example, I have opened feature-1 drop down, and while I click on feature-2 to open, feature-1 dropdown should close and vice versa.

const [expand1, setExpand1] = useState(false);
const [expand2, setExpand2] = useState(false);

             <ul>
                <li>
                    <div onClick ={() => setExpand1(!expand1)}>
                        <a onClick={() => openPane('1')} className="menu-item">
                        
                        <span>Feature-1</span>
                        <div className={`drop-down ${expand1 ? 'active' : ""}`}>
                        <i class='bx bx-chevron-down'></i>
                        </div>
                    </a>
                    </div></li>
                 <li>
                    <div onClick ={() => setExpand2(!expand2)}>
                    <a onClick={() => openPane('2')} className="menu-item">
                        <span>Feature-2</span>
                        <div className={`drop-down ${expand2 ? 'active' : ""}`}>
                        <i class='bx bx-chevron-down'></i>
                        </div>
                    </a>
                    </div>
               </li>
           </ul>