I know what need to be corrected in the testcases. I tried changing the testcases using fireevent.change to give input to elements, which by doing to all testcases all are passed. But I need an improvisation or correction to my code so that it works fine for original testcases. As you can see only null values is taken as the input for elements in testcases. We are receiving output as Invalid URL. Can someone help me out here?
Below is the react application UI.
enter image description here
Here is URL VALIDATOR FUNCTIONAL COMPONENT CODE
import React , {useState} from "react";
// import '../UrlValidator.css';
function UrlValidator(){
const [domain,setDomain] = useState("");
const [path,setPath] = useState("");
const [method,setMethod] = useState("GET");
const [body,setBody] = useState("");
const [message,setMessage] = useState("");
const [color,setColor] = useState('');
const urlPatternValidation = (Domain) => {
const regex = new RegExp('(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?');
if(!Domain.includes('com')){
return false;
}
return regex.test(Domain);
};
const handleSubmit = (e)=>{
e.preventDefault();
if(!urlPatternValidation(domain)){
setMessage('Invalid URL!Please recheck your URL');
setColor('red');
}
else if(body && path){
// var temp = domain + '/'+ path.split(' ').join('/');
// setMessage(temp);
// setColor('#4EDD4D');
// try{
// var obj = JSON.parse(body);
// var res = message + '?';
// for(let key in obj){
// res= res+ key+'='+obj[key];
// }
try{
var obj = JSON.parse(body);
var temp = domain + '/'+ path.split(' ').join('/');
setMessage(temp);
setColor('#4EDD4D');
var res = temp + '?';
for(let key in obj){
res= res+ key+'='+obj[key];
}
if(!(method==="POST" || method==='PUT')){
setMessage(res);
setColor('#4EDD4D');
}
}
catch(Exception){
setColor('red');
if (method==="POST" || method==='PUT'){
setMessage('Error in the body');
}
else{
setMessage('Error in the Body of the Query Params');
}
}
}
else if(path && body===""){
if (method==="POST" || method==='PUT'){
setColor('red');
setMessage('Error in the Body');
}
else{
setMessage(domain+ '/'+ path.split(' ').join('/'));
setColor('#4EDD4D');
}
}
else if(body===""){
if (method==="POST" || method==='PUT'){
setMessage('Error in the Body');
setColor('red');
}
}
}
return (
<form className='template' data-testid='submit' onSubmit={handleSubmit}>
<div className='message' data-testid='message' style={{backgroundColor:color}}>{message}</div>
<label>Domain</label><br></br>
<input type="text" data-testid='domain' placeholder='Enter the domain URL' onChange={e=>{setDomain(e.target.value)}}></input><br></br>
<label>Path</label><br></br>
<input type="text" data-testid='path' placeholder='Enter the path variables separated by comma' onChange={e=>{setPath(e.target.value)}}></input><br></br>
<label>Method</label><br></br>
<select title="method" data-testid='method' onChange={e=>{setMethod(e.target.value)}}>
<option id ="GET" value="GET">GET</option>
<option id ="POST" value="POST">POST</option>
<option id ="PUT" value="PUT">PUT</option>
<option id="DELETE" value="DELETE">DELETE</option>
</select><br></br>
<label>Body</label><br></br>
<textarea id="Body" data-testid='body' placeholder="Enter the Query Params as an Object" onChange={e=>{setBody(e.target.value)}}></textarea>
<br></br>
<input type='submit' value="Validate"></input>
<br></br>
</form>
);
}
export default UrlValidator;
and below are the testcases which are being tested using the above component code .
import UrlValidator from "./components/UrlValidator";
import { render, screen, cleanup, fireEvent } from '#testing-library/react';
describe('Test URL Validator', () => {
test('testcase1', () => {
render(<UrlValidator />);
const inputDomain = screen.getByTestId('domain');
const inputPath = screen.getByTestId('path');
const inputMethod = screen.getByTestId('method');
const inputBody = screen.getByTestId('body');
const form = screen.getByTestId('submit');
expect(inputDomain).toBeTruthy();
expect(inputPath).toBeTruthy();
expect(inputMethod).toBeTruthy();
expect(inputBody).toBeTruthy();
fireEvent.submit(form, {
target : [
{value : 'www.google.com'},
{value : 'search all'},
{value : 'GET'},
{value : ''},
]
});
const message = screen.getByTestId('message');
expect(message.textContent).toBe('www.google.com/search/all');
});
test('testcase2', () => {
render(<UrlValidator />);
const inputDomain = screen.getByTestId('domain');
const inputPath = screen.getByTestId('path');
const inputMethod = screen.getByTestId('method');
const inputBody = screen.getByTestId('body');
const form = screen.getByTestId('submit');
expect(inputDomain).toBeTruthy();
expect(inputPath).toBeTruthy();
expect(inputMethod).toBeTruthy();
expect(inputBody).toBeTruthy();
fireEvent.submit(form, {
target : [
{value : 'www.google.com'},
{value : 'search all'},
{value : 'GET'},
{value : '{\"Name\":\"Max\"}'},
]
});
const message = screen.getByTestId('message');
expect(message.textContent).toBe('www.google.com/search/all?Name=Max');
});
test('testcase3', () => {
render(<UrlValidator />);
const form = screen.getByTestId('submit');
const inputMethod = screen.getByTestId('method');
fireEvent.change(inputMethod, {target : {value : 'POST'}})
fireEvent.submit(form, {
target : [
{value : 'www.google.com'},
{value : 'posts'},
{value : 'POST'},
{value : '{\"Name\":\"Max\"}'}
]
});
const message = screen.getByTestId('message');
expect(message.textContent).toBe('www.google.com/posts');
})
test('testcase4', () => {
render(<UrlValidator />);
const inputDomain = screen.getByTestId('domain');
const inputPath = screen.getByTestId('path');
const inputMethod = screen.getByTestId('method');
const body = screen.getByTestId('body');
const form = screen.getByTestId('submit');
fireEvent.change(inputDomain, {target : {value: 'www.google.com'}});
fireEvent.change(inputPath, {target : {value: 'search all'}});
fireEvent.change(inputMethod, {target : {value: 'POST'}});
fireEvent.submit(form, {
target : [
{value : 'www.google.com'},
{value : 'search all'},
{value : 'POST'},
{value : ''},
]
});
const message = screen.getByTestId('message');
expect(message.textContent).toBe('Error in the Body');
})
test('testcase5', () => {
render(<UrlValidator />);
const form = screen.getByTestId('submit');
const inputMethod = screen.getByTestId('method');
fireEvent.change(inputMethod, {target : {value : 'DELETE'}})
fireEvent.submit(form, {
target : [
{value : 'www.google.com'},
{value : 'posts'},
{value : 'DLETE'},
{value : ''}
]
});
const message = screen.getByTestId('message');
expect(message.textContent).toBe('www.google.com/posts');
});
test('testcase6', () => {
render(<UrlValidator />);
const inputDomain = screen.getByTestId('domain');
const inputPath = screen.getByTestId('path');
const inputMethod = screen.getByTestId('method');
const inputBody = screen.getByTestId('body');
const form = screen.getByTestId('submit');
expect(inputDomain).toBeTruthy();
expect(inputPath).toBeTruthy();
expect(inputMethod).toBeTruthy();
expect(inputBody).toBeTruthy();
fireEvent.submit(form, {
target : [
{value : 'www.google.com'},
{value : 'search all'},
{value : 'GET'},
{value : '{\"Name\":\"Max\"'},
]
});
const message = screen.getByTestId('message');
expect(message.textContent).toBe('Error in the Body of the Query Params');
});
})
Only testcase 4 is passing and here is the proof to that
FAIL src/App.test.js
Test URL Validator
× testcase1 (52 ms)
× testcase2 (10 ms)
× testcase3 (13 ms)
√ testcase4 (14 ms)
× testcase5 (8 ms)
× testcase6 (12 ms)
● Test URL Validator › testcase1
expect(received).toBe(expected) // Object.is equality
Expected: "www.google.com/search/all"
Received: "Invalid URL!Please recheck your URL"
33 |
34 | const message = screen.getByTestId('message');
> 35 | expect(message.textContent).toBe('www.google.com/search/all');
| ^
36 |
37 | });
38 |
at Object.<anonymous> (src/App.test.js:35:37)
● Test URL Validator › testcase2
expect(received).toBe(expected) // Object.is equality
Expected: "www.google.com/search/all?Name=Max"
Received: "Invalid URL!Please recheck your URL"
64 |
65 | const message = screen.getByTestId('message');
> 66 | expect(message.textContent).toBe('www.google.com/search/all?Name=Max');
| ^
67 |
68 | });
69 |
at Object.<anonymous> (src/App.test.js:66:37)
● Test URL Validator › testcase3
expect(received).toBe(expected) // Object.is equality
Expected: "www.google.com/posts"
Received: "Invalid URL!Please recheck your URL"
86 |
87 | const message = screen.getByTestId('message');
> 88 | expect(message.textContent).toBe('www.google.com/posts');
| ^
89 |
90 | })
91 |
at Object.<anonymous> (src/App.test.js:88:37)
● Test URL Validator › testcase5
expect(received).toBe(expected) // Object.is equality
Expected: "www.google.com/posts"
Received: "Invalid URL!Please recheck your URL"
138 |
139 | const message = screen.getByTestId('message');
> 140 | expect(message.textContent).toBe('www.google.com/posts');
| ^
141 |
142 | });
143 |
at Object.<anonymous> (src/App.test.js:140:37)
● Test URL Validator › testcase6
expect(received).toBe(expected) // Object.is equality
Expected: "Error in the Body of the Query Params"
Received: "Invalid URL!Please recheck your URL"
169 |
170 | const message = screen.getByTestId('message');
> 171 | expect(message.textContent).toBe('Error in the Body of the Query Params');
| ^
172 |
173 | });
174 |
at Object.<anonymous> (src/App.test.js:171:37)
The root cause of the issue is you are checking a state value i.e domain befor it got update/not updated at all
if(!urlPatternValidation(domain)){
setMessage('Invalid URL!Please recheck your URL');
setColor('red');
}
In your tests you are not updating state values , instead submitting the form
const inputDomain = screen.getByTestId('domain');
const inputPath = screen.getByTestId('path');
const inputMethod = screen.getByTestId('method');
const inputBody = screen.getByTestId('body');
const form = screen.getByTestId('submit');
expect(inputDomain).toBeTruthy();
expect(inputPath).toBeTruthy();
expect(inputMethod).toBeTruthy();
expect(inputBody).toBeTruthy();
fireEvent.submit(form, {
target : [
{value : 'www.google.com'},
{value : 'search all'},
{value : 'GET'},
{value : ''},
]
});
You can try like this
const formData = new FormData(event.currentTarget);
const domain = formData.get("domain") //name of the element
//write your logic from here
Related
const cartsSlice = createSlice({
name: CARTS,
initialState,
reducers: {
increaseCartItemQuantityById: (state, { payload }: PayloadAction<{ cartItemId: number }>) => {
const targetIndex = state.carts.value.findIndex(
(cartItem) => cartItem.id === payload.cartItemId,
);
if (targetIndex === -1) throw new Error('mismatched id');
state.carts.value[targetIndex].quantity = state.carts.value[targetIndex].quantity + 1;
},
I want to test whether a reducer throws an error well. So I try to test using thThrow, thThrowError etc..
I tried it
it('throw error test', () => {
const MISMATCHED_ID = 1;
const error = new Error('mismatched id');
expect(
cartsReducer(
cartsReducerInitialState,
increaseCartItemQuantityById({ cartItemId: MISMATCHED_ID }),
),
)
.toThrowError(error); // fail
.toThrow(error); // fail
.toThrowErrror('mismatched id'); // fail
.toThrowErrror(/mismatched id/); // fail
.toHaveErrorMessage(/mismatched id/); // fail
.toHaveErrorMessage('mismatched id'); // fail
});
});
All these ways are failed... It only returned this message
FAIL store/modules/carts/tests/cartsReducer.test.ts
● › increaseCartItemQuantityById › throw error test
mismatched id
37 | },
38 | } as CartsReducerState,
> 39 | reducers: {
| ^
40 | addCartItem: (state, { payload }: PayloadAction<{ newCartItem: CartItem }>) => {
41 | state.carts.value = [...state.carts.value, payload.newCartItem];
42 | },
at increaseCartItemQuantityById (store/modules/carts/slice.ts:39:43)
at recipe (node_modules/#reduxjs/toolkit/src/createReducer.ts:280:20)
at Immer.produce (node_modules/immer/src/core/immerClass.ts:94:14)
at node_modules/#reduxjs/toolkit/src/createReducer.ts:279:18
at Array.reduce (<anonymous>)
at reducer (node_modules/#reduxjs/toolkit/src/createReducer.ts:246:25)
at Object.reducer [as cartsReducer] (node_modules/#reduxjs/toolkit/src/createSlice.ts:325:14)
at Object.<anonymous> (store/modules/carts/__tests__/cartsReducer.test.ts:55:32)
So basically I am able to get the text for all the buttons but I am getting the error which says Undefined when asserting that it's true. Please I need help, let me know if more information is needed. Thank you
async isNoticationsEnabled(type: string) {
const notificationType = await this.getNotificationsTypeByText(type);
const selectContainer = await notificationType.$$('.NotificationTypeSchedule__selectContainer');
const sms = selectContainer[1];
const mobilePush = selectContainer[2];
const webPush = selectContainer[3];
const enabled = [];
enabled.push(sms, mobilePush, webPush)
for (let i = 0; i < enabled.length; i++) {
const elements = enabled[i];
if(await elements?.getText() === 'On') {
return true;
}
}
}
Output:
expect(received).toBe(expected) // Object.is equality
Expected: true
Received: undefined
42 | expect(await NotificationsTabs.isNotificationSectionDisplayed()).toBe(true)
43 | await NotificationsTabs.scrollTo('Note Mentions')
> 44 | expect(await NotificationsTabs.isNoticationsEnabled('Note Mentions')).toBe(true);
| ^
45 | });
46 | });
I am learning unit testing with Jest,
This is the function I trying to test.
import axios from "axios";
export const call = async () => {
return axios.get("https://www.example.com").then((resp) =>{
const response = resp.data
let userData = {
title : response.title ? response.title : "",
url : response.url ? response.url : "",
date : response.date ? response.date : " ",
id : response.id ? response.id : "",
email: response.email ? response.email : ""
}
return Promise.resolve(userData)
})
}
here is the test.js file ---
import axios from "axios"
import {call} from './components/call'
jest.mock('axios')
const expectedResult = {
title:"hello"
}
const resp ={
data : expectedResult
}
describe("test", ()=>{
test("demo-test", async ()=>{
axios.get.mockResolvedValueOnce(resp)
const response = await call()
expect(response).toEqual(expectedResult)
console.log("axios.get() returns >>>", axios.get.mock.results[0]);
expect(axios.get).toHaveBeenCalledWith("https://www.example.com")
})
})
Here is the error I am getting
expect(received).toEqual(expected) // deep equality
- Expected - 0
+ Received + 4
Object {
+ "date": " ",
+ "email": "",
+ "id": "",
"title": "hello",
+ "url": "",
}
16 | axios.get.mockResolvedValueOnce(resp)
17 | const response = await call()
> 18 | expect(response).toEqual(expectedResult)
| ^
19 |
20 | console.log("axios.get() returns >>>", axios.get.mock.results[0]);
21 | expect(axios.get).toHaveBeenCalledWith("https://google.com")
FAIL src/call.test.js (7.597 s)
In the call.js, when userData dosen't have ternary conditions then the test passes. But when I put ternary condition the test gets failed with the above error. Please help me. How to resolve this issue.
I have 2 modals and they are similar. One of works but the other one sometimes works sometimes doesn't. Both codes are same just the models is different but i coulnd't find any result.
This is error;
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
174 | }
175 | setVals(data.form);
176 |
177 | setInputList(
| ^ 178 | JSON.parse(data.form.cabinTeam, data.form.cabinTeamLicence)
179 | );
This is code;
useEffect(() => {
setDisabled(false);
setVals(initVals);
setInputList([{ cabinTeam: "", cabinTeamLicence: "" }]);
if (id) {
axios.get(`/twoA/${id}`).then(({ data }) => {
if (data.form !== null && data.form !== undefined) {
if (data.form.opearationDate !== null) {
data.form.opearationDate = moment(data.form.opearationDate).format(
"DD/MM/YYYY"
);
}
setVals(data.form);
setInputList(
JSON.parse(data.form.cabinTeam, data.form.cabinTeamLicence)
);
setDisabled(true);
}
});
}
}, [id]);
const [inputList, setInputList] = useState([
{ cabinTeam: "", cabinTeamLicence: "" },
]);
const handleInputChange = (e, index) => {
const { name, value } = e.target;
const list = [...inputList];
list[index][name] = value;
setInputList(list);
};
const handleRemoveClick = (index) => {
const list = [...inputList];
list.splice(index, 1);
setInputList(list);
};
const handleAddClick = () => {
setInputList([...inputList, { cabinTeam: "", cabinTeamLicence: "" }]);
};
Good afternoon, I'm pretty new to React since mostly was doing NodeJS stuff before and I come with a problem that I currently don't know how to connect my backend with frontend parts together.
GOAL: I wan't to create a price alert which is going to send me a email notification.
I have a Dropdown Where I can write a Symbol Name and Price and Set it up. I wan't to create an alert when Price is getting bigger than writed in DropDown. F
Example: I Open a DropDown - write ADABTC in first textarea 500 click Set button and
I already have email notification script ready I was using - NodeMailer Package
I'm also using Binance API to receive the Price
Here is my ReactJS Code part.(Event.jsx)
import React, { useState, useEffect } from "react";
const assets = [
"ADABTC",
"AIONBTC",
"ALGOBTC",
"ARDRBTC",
"KAVABTC",
"ETHBTC",
"ETCBTC"
];
export default function App() {
const [queries, setQueries] = useState([]);
const [symbol, setSymbol] = useState("");
const [price, setPrice] = useState("");
const [dropdown, setDropdown] = useState([]);
const onChangeSymbol = e => {
setSymbol(e.target.value);
};
const onChangePrice = e => {
setPrice(e.target.value);
};
var today = new Date();
var date =
today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
var time =
today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date + " " + time;
const onClick = () => {
if (symbol !== "" && price !== "") {
setQueries(queries => {
return [
...queries,
`${symbol}` + " " + `${price}` + " " + "(" + dateTime+")"
];
});
setSymbol("");
setPrice("");
}
};
useEffect(() => {
if (symbol !== "" && symbol !== assets.find(rec => rec === symbol)) {
setDropdown(assets.filter(rec => rec.indexOf(symbol) > -1));
} else {
setDropdown([]);
}
}, [symbol]);
return (
<div id="DropDownArea" className="DropDownField">
<div id="PriceAlertHistory">
<h6>Price Alert History</h6>
</div>
<ul>
{queries.map(query => (
<li>{query}</li>
))}
</ul>
<input
type="text"
placeholder="Symbol"
value={symbol}
onChange={onChangeSymbol}
/>
<input
type="number"
placeholder="Price"
value={price}
onChange={onChangePrice}
/>
<button type="submit" onClick={onClick}>
Set
</button>
<ul>
{dropdown.length !== 0
? dropdown.map(asset => {
return (
<li
onClick={() => {
setSymbol(asset);
setDropdown([]);
}}
>
{asset}
</li>
);
})
: false}
</ul>
</div>
);
}
Here is my NodeJS Code which is receiving data from Binance API.(Databases.js)
const getBTCData = async symbol => {
let data = await fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=1d&limit=1`).then(res => res.json());
const btcusdtdata = data.map(d => {
return {
Open: parseFloat(d[1]),
}
});
let volume = await fetch(`https://api.binance.com/api/v3/ticker/24hr?symbol=${symbol}`).then(res => res.json());
const volumedata = data.map(d => {
return {
Volume: parseFloat(volume.quoteVolume)
}
});
console.log(btcusdtdata[0]);
};
This is NodeMailer script(Email.js)
require('dotenv').config()
"use strict"; // This is ES6 specific. Help's to run code faster(IMPORTANT FOR NOTIFICATION SYSTEM)
const nodemailer = require("nodemailer");
async function main() {
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: process.env.DB_USER, // OUR ALARM EMAIL
pass: process.env.DB_PASS, // OUR ALARM PASSWORD
},
});
let info = await transporter.sendMail({
from: process.env.DB_USER, // sender address
to: process.env.DB_RECEIVER, // list of receivers
subject: `Asset is UP`, // Subject line
text: "ASSET IS UP", // plain text body
});
console.log("Message sent: %s", info.messageId);
}
main().catch(console.error);