Im trying to write unit tests for class methods with jest ( new to jest)
I have methods that e.g. take arrays and modify them and bring them into different form to satisfy algorithm needs.
But I dont see a way how I simply can test class method receiving and returning values.
Looks like there is a problem with classes, class methods cant be tested as simple functions.
But if I look at the docs I dont see it covering these topics, it only covers e.g. was a class instance called, was a class method called..
Category: javascript
Category Added in a WPeMatico Campaign
Failed to load resource: the server responded with a status of 401 (Unauthorized) in REACT and NODE.js
This is REACT js client side code
in console error is this 1.Failed to load resource: the server responded with a status of 401 (Unauthorized) 2. Uncaught TypeError: inventories.map is not a function
useEffect(() => {
setDataLoading(true);
const url = `http://localhost:5000/inventoryByEmail?email=${user.email}`;
fetch(url, {
headers: {
authorization: `Bearer ${localStorage.getItem("access-token")}`,
},
})
.then((res) => res.json())
.then((data) => {
setInventories(data);
setDataLoading(false);
});
}, [user]);
This is Server site Nodejs code
function verifyJWT(req, res, next) {
const authHeader = req.header.authorization;
if (!authHeader) {
return res.status(401).send({ message: "unauthorized access" });
}
const token = authHeader.split(" ")[1];
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
return res.status(403).send({ message: "Forbidden access" });
}
req.decoded = decoded;
next();
});
}
and this is api Route
app.get("/inventoryByEmail", verifyJWT, async (req, res) => {
const decodedEmail = req.decoded.email;
const email = req.query.email;
if (email === decodedEmail) {
const query = { email: email };
const cursor = inventoryCollection.find(query);
const result = await cursor.toArray();
res.send(result);
} else {
res.status(403).send({ message: "forbidden access" });
}
});
How to slove this issue? thanks so much for your time!
Javascript : How convert existing JSON Object into custom key based Object? [closed]
I need to convert/destructure my existing JSON object into a new form with key-based JSON,
please look at the below input JSON
Note : Below array has n numbers of Objects.
INPUT JSON:
[
{
"processId": 95,
"pid": "PID_0",
"actionData": [
{
"actionId": 96,
"action": "Sbend",
"avg": 0.09134998917579651,
"avgVid": "",
"max": 0.13287270069122314,
"maxVid": ",
"maxPos": 1,
"min": 0.06643635034561157,
"minVid": "",
"minPos": 0,
"total": 8,
"totalTime": null
},
{
"actionId": 98,
"action": "Stand",
"avg": 0.7355453372001648,
"avgVid": "",
"max": 2.889981508255005,
"maxVid": "",
"maxPos": 11,
"min": 0.06643635034561157,
"minVid": "",
"minPos": 9,
"total": 28,
"totalTime": null
}
]
}
]
Here I need is take the ‘pid’ key value and set it to the root key for existing JSON,
Below there is an expected output
Expected OUTPUT
[
"PID_0" : {
"processId": 95,
"actionData": [
{
"actionId": 96,
"action": "Sbend",
"avg": 0.09134998917579651,
"avgVid": "",
"max": 0.13287270069122314,
"maxVid": ",
"maxPos": 1,
"min": 0.06643635034561157,
"minVid": "",
"minPos": 0,
"total": 8,
"totalTime": null
},
{
"actionId": 98,
"action": "Stand",
"avg": 0.7355453372001648,
"avgVid": "",
"max": 2.889981508255005,
"maxVid": "",
"maxPos": 11,
"min": 0.06643635034561157,
"minVid": "",
"minPos": 9,
"total": 28,
"totalTime": null
}
]
}
]
Kindly help me out to fix this issue, its really helps me a lot.
Thanks.
Why I get an error as “redeclaration of const phone_price” in console?
Question1: Why do I get this error on my browser(firefox):
redeclaration of const phone_price
But here, An error is not thrown:
const phone_price = 102.22;
const tax = 0.08;
const price_thereshold = 230;
const accessory = 10;
var account_bank = 310;
var amount = 0;
function withTax(amt){
return amt * tax;
}
function formatted_price(amt){
return "$" + amt.toFixed(2);
}
while(amount < account_bank){
amount = amount + phone_price;
if(amount < price_thereshold){
amount = amount + accessory;
}
}
amount = amount + withTax(amount);
amount = formatted_price(amount);
console.log("your purchase price: " + amount);
if(amount > account_bank){
console.log("you haven't afford for your purchase");
}
Question 2: Why does the second console not run?
how to force gulp run the gulpfile.babel.js instead of gulpfile.js (both are in same directory)?
I have a project with both gulpfile.js (“gulp syntax”) and gulpfile.babel.js (“ES6 syntas”) files in the same (root) directory.
So when I’m executing
gulp [taskname]
in the command line (Windows10-cmd + gulp-CLI) – the gulpfile.js is executing by default.
But can I force the gulp-CLI to run the gulpfile.babel.js instead of gulpfile.js in some ways?
when I click to bookmark a program it duplicates the bookmark icon
when I click to bookmark a program it duplicates the bookmark icon<> I think there is a problem with my inner foreach.
when I click to bookmark a program it duplicates the bookmark icon<> I think there is a problem with my inner foreach.
when I click to bookmark a program it duplicates the bookmark icon<> I think there is a problem with my inner foreach.
can anyone help ??
<div class="row">
@foreach($events as $item )
<div class="col-md-3">
<a href="{{url('/detail/'.$item->id)}}" class="text-decoration-none text-reset">
<div id="click" class="card mb-4 bg-light shadow-sm ">
<img src="{{URL::asset($item->picture)}}" class="card-img-top" alt="{{$item->picture}} ">
<div class="card-body bg-white rounded">
<h5 class="card-title">{{$item->event_name}}</h5>
<p class="card-text"> {{$item->event_description}} </p>
<i class="bi bi-cash ms-0"></i><b> {{$item->fees}}</b> ريال
<span>    </span>
<i class="bi bi-person me-0"></i> {{$item->chaires}}
@if(count($booked)==0)
<span>    </span>
<a href="{{ url('archive/'.$item->id) }}" style="color:black"> <i class="bi bi-bookmark"></i></a>
@endif
@foreach($booked as $book )
@if(($book->event_id)==($item->id))
<span>    </span>
<a href="{{ url('deleteArchive/'.$item->id) }}" style="color:black"><i class="bi bi-bookmark-fill"></i></a>
@elseif(($book->event_id)!=($item->id))
<span>    </span>
<a href="{{ url('archive/'.$item->id) }}" style="color:black"> <i class="bi bi-bookmark"></i></a>
@endif
@endforeach
</div>
</div>
</a>
</div>
@endforeach
</div>
writing file with a colon as the filename
The code is as follows:
fs.readFile(bat_path + '0000.bat', 'utf8', function (err, data) {
if (err) throw err;
var result = data.replace('username', username);
fs.writeFile(bat_path + "99:99" + username + '.bat', result, 'utf8', (err) => {
if (err) {
console.log(err);
};
});
});
however when i try to write this , writeFile does not throws an error and it just generates a file with filename 99 and nothing is in it.. if i remove ’99:99′ string, it works just fine..
note: the 99:99 is just illustration purposes that will be replaced with a dynamic variable later on
why is this ? i am pulling out my hair
converting string arithmetic expression
I am expecting from the user an arithmetic expression like
1 + 2 – ((array_sum(4) % 2) * 3 * 1)
and I need to dynamically convert it to the above logic
const ar_exp = [
{ operand: 1 },
{ operator: "+" },
{ operand: 2 },
{ operator: "-" },
{
parenthesis: [
{
parenthesis: [
{
function: {
name: "array_sum",
arguments: [{ operand: 4 }],
},
},
{ operator: "%" },
{ operand: 2 },
],
},
{ operator: "*" },
{ operand: 3 },
{ operator: "*" },
{ operand: 1 },
],
},
];
any advice of how to approach this problem?
is there any lib which can help me out with such operations ?
I thought of splitting the whole string by operators, but this () parenthesis makes it a bit confusing when it comes to inner values
Check if any item in one range is present within another range javascript
I am currently writing something that requires checking if one range contains any items from another range
var lvlRange = [];
for (var i = sLVL; i <= dLVL; i++) {
lvlRange.push(i);
}
var methodRange = [];
for (var i = skillIdentity.method1Start; i <= skillIdentity.method1End; i++) {
methodRange.push(i);
}
For example, if the lvlRange array has everything from 1-30, I need to check if the methodRange also has anything between 1 and 30 in it. Essentially checking if they have any overlapping numbers.
Something like (if lvlRange shares any numbers with methodRange) return true;
No node found for selector: #react-select-2-input
<div class="css-1hwfws3"><div class="css-o3gndj-placeholder">Select</div><div class="css-eo20y5"><div class="" style="display: inline-block;"><input autocapitalize="none" autocomplete="off" autocorrect="off" id="react-select-2-input" spellcheck="false" tabindex="0" type="text" aria-autocomplete="list" aria-label="Month" value="" style="box-sizing: content-box; width: 2px; background: 0px center; border: 0px; font-size: inherit; opacity: 1; outline: 0px; padding: 0px; color: inherit;"><div style="position: absolute; top: 0px; left: 0px; visibility: hidden; height: 0px; overflow: scroll; white-space: pre; font-size: 18px; font-family: Whitney, "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 400; font-style: normal; letter-spacing: normal; text-transform: none;"></div></div></div></div>
Im Trying To Type in the inbut box of this Div But Im Getting Erros Saying no node found
I am getting unlimited request from server . where is the dependency problem can’t get it
import { useEffect, useState } from "react"
const useProducts =()=>{
const [products, setProducts] = useState([])
const [loading, setLoading] = useState(false)
useEffect(()=>{
fetch(`http://localhost:5000/inventory`)
.then(res => res.json())
.then(data => setProducts(data))
setLoading(!loading)
},[products])
return [products, setProducts]
}
export default useProducts
**Here is my code . my project working but getting unlimited req. where is the problem. attached code here. please take a look **
getting req unlimited
ReactJS – trying to achieve tag filtering functionality to render only items that have a certain tag
After a few years of lurking without an account, I am today posting my first question.
I’ve been working on a personal project for a little while, to learn, trying to create a store-like website that has it’s inventory of items read from json files.
The functionality that I’m trying to achieve is something of a filter: type a tag in a search field and only the items that have that tag will be displayed.
I’ve successfully managed to create a functional search filter using useState & Array.filter() with the help of online searches, but this is because I’ve used it on strings.
For instance, one of my json files may have items looking like this:
[
{
"title": "Name of the First Product",
"description": "Short Description",
"image": "/assets/img/image_001.png",
"price": "50.00",
"currency": "$",
.
.
.
"tags": [ "tag1", "tag2", "tag3"]
},
{
"title": "Name of the Second Product",
"description": "Short Description",
"image": "/assets/img/image_001.png",
"price": "55.00",
"currency": "$",
.
.
.
"tags": [ "tag2", "tag3", "tag4"]
},
.
.
.
]
The filter functionality is working for strings. If I’m typing First Product in the search field, the correct item is rendered and nothing else is rendered.
However, this is not the case for arrays of tags. Nothing is rendered when I’m trying to search for a tag (array of strings).
As seen above, some of the tags may repeat, so I’m merging all the tags into one final string and eliminating the duplicates, before the filter function. For the sake of the example, let’s say it looks like the following (note: .toLowerCase() is already applied to each one of the tags in the const below):
const finalArrayOfTags = [ "tag1", "tag2", "tag3", "tag4", ... ];
The way I’m filtering is:
Array.filter(items => {
if (query === "") {
return item;
} else if (item.title.toLowerCase().includes(query.toLowerCase())) {
return item;
} else if (item.description.toLowerCase().includes(query.toLowerCase())) {
.
.
.
} else if (finalArrayOfTags.forEach(tag => tag.includes(query))) {
return item;
}}).map(item, index => (
<>
/// ... render the item component
</>
))}
The first 2 “else if”s are rendering the correct items, because they are looking inside a string.
The “else if” at the end doesn’t render anything, because it’s looking inside an array of strings and I can’t figure out how to split it out or iterate through them.
Does anyone have any advice for me ? 🙂
Transferring SPREADSHEET Data using Google App Script
I’M SEARCHING FOR A WAY ON HOW I CAN Transfer SPREADSHEET Data using Google App Script, from one spreadsheet to another one
thank you in advance
how to change `let` to change data in js?
I want to change a var, let, and const.
like this:
Var exactly = "bruh"; /* console.log("data saved") */
then
var exactly = "nicee"; /* console.error("data already saved") */
how to change a var or let?
Wscript iTunes.Application Object — Which Property Controls the “Sort As” Field for Album Title?
I have some Javascript files that I use to manage my library in iTunes in Windows. I’ve successfully edited Track Name, Album Name, and even the Year fields, thanks to knowing which properties to use for the SelectedTracks object, but I can’t seem to locate the property for the “Sort As” album field.
I found this link, which has proven to be a big help for the most common fields, but does anyone know where I can find that elusive “Sort As” album field? I’ve done a lot of searching, and can’t seem to locate it. Alternately, is there a way I can return all of the properties for a given object at the single track level? I found getOwnPropertyNames(), but it doesn’t appear to work at that level.
Thanks!

