How to pass a an argument to getByText in react Testing Library? - reactjs

Currently I'm doing this
getByText(/SomeText/i);
But I want to make a function and pass some text as an argument by first storing it in a variable. I tried doing it like this:
let x = "/SomeText/i";
getByText(x);
or
getByText(`/${x}/i`);
But none of the options work.

If you have
const x = "Some string"
To test for x using regex,
getByText(new RegExp(x, "i"))

Perhaps you are looking for passing exact: false?
// Match a substring of Hello World
getByText(container, 'llo Worl', { exact: false }) // substring match
You can also pass your own matching custom function.
getByText(container, (content, element) => content.startsWith('Hello'))
https://testing-library.com/docs/dom-testing-library/cheatsheet#text-match-options

Welcome to SO!
I haven't tested this, but it seems getByText needs a regular expression:
getByText(/SomText/i);
as an argument and not, as you put here, a string:
let x = "/SomeText/i";
Does your code work if you create a regex from your string, like this?
let x = new RegExp("/SomeText/i");

I think your issue is your trying to set a RegEx as though it's a string
// Doesn't need quotes
let x = /SomeText/i
getByText(x)
What you're asking getByText to find is literally /SomeText/i, which I imagine your document does not have in it

I had a similar scenario where I needed a variable:
const x = 'some text';
getByText(`${x}`);

Related

Should be an array, but typeof says it's an object, Chrome console displays it as an array

I have this problem which may sounds stupid but I don't really understand the whys.
I declare it as a variable: let [ randomQuoterState, setrandomQuoterState ] = useState([]); Then pass it into a component inside the return: <UserOutput set={setrandomQuoterState} current={randomQuoterState} number={1}/>
The following code is inside the component:
let toSet = [];
toSet[props.number] = quoteArray[Math.floor(Math.random() * quoteArray.length)];
let quote = props.current;
if (quote[props.number]){
delete quote[props.number];
console.log("deleted")
}else {
console.log("this does not exist");
}
console.log(typeof(toSet[props.number]));
console.log(toSet[props.number].lenght)
console.log(toSet[props.number]);
quote[props.number] = toSet[props.number][Math.floor(Math.random() * toSet[props.number].lenght)];
props.set(quote);
The Consol displays it as an array, but the typeof function says its an object, and it doesn't have a length property.
I would appreciate any help or explanation, I thought about it a lot, but I couldn't come up with anything.
Arrays are objects in Javascript. In fact, there is no array type.
To see if it is an array, you should try console.log((toSet[props.number]).constructor.name) and do your checks against toSet[props.number] instanceof Array.
Do not use (toSet[props.number]).constructor.name == 'Array' in your comparisons, because you could have something that has inherited from Array but whose constructor name is different.
In JavaScript both object and array are of type Object.
In case you want to determine exact type, you can use constructor property.
const data = {};
data.contructor.name === 'Object'; // Returns True
const data = [];
data.contructor.name === 'Object'; // Returns True
data.contructor.name === 'Object'; // Returns False
Above can used to determine String, Date etc as well.
Alternatively you can use libraries like lodash which has function for these things.
However that is overkill I guess.
Hope it helps.

unexpected result in a query in laravel

I’m a beginner in Laravel but have a problem at first. I wrote this query and I’m waiting for Sonya Bins as result but unexpectedly I see ["Sonya Bins"]. what’s the problem?
Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
return view('products',compact('articles'));
});
pluck will return array if you want to get only single value then use value
// will return array
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
//will return string
$articles=DB::table('users')->where('id','2')->value('name');
// output Sonya Bins
here is an example from the documentation:
if you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
Read more about it here
Hope it helps.
Thanks
pluck() used to return a String before Laravel 5.1, but now it returns an array.
The alternative for that behavior now is value()
Try this:
Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->value('name');
return view('products',compact('articles'));
});
I think it's easier to use the Model + find function + value function.
Route::get('products', function () {
$articles = User::find(2)->value('name');
return view('products',compact('articles'));
});
pluck will return the collection.
I think id is your primary key.
You can just get the first record, and call its attribute's name:
DB::table('users')->where('id','2')->first()->name;
or
DB::table('users')->find(2)->name;
First thing is that you used invalid name for what you pass to view - you don't pass articles but user name.
Second thing is that you use get method to get results instead of first (or find) - you probably expect there is only single user with id = 2.
So to sum up you should use:
$userName = DB::table('users')->find(2)->name;
return view('products',compact('userName'));
Of course above code is for case when you are 100% sure there is user with id = 2 in database. If it might happen there won't be such user, you should use construction like this:
$userName = optional(DB::table('users')->find(2))->name;
($userName will be null if there is no such record)
or
$userName = optional(DB::table('users')->find(2))->name ?? 'No user';
in case you want to use custom string.

How do I get the text from the li tag

How do I get the text from the li tag? I want to find the text "Password is required." only, not the text inside strong tag.
<li><strong>Error:</strong> Password is required.</li>
You need to show your code for somebody to give a complete answer. I guess that you already know how to do something like the following
WebElement something = driver.FindElement(By.CssSelector(?))
string s = something.Text;
The next bit seems to be where you are stuck. There you need to parse the string s. That is nothing to do with Selenium-Webdriver. You could do something like
string[] s2 = s.split(new string[] {">","<"});
were the last element in s2 would be your answer here. This would be totally non generic though. Is this a situation in which you always want to purge html?
Here is the method developed in python.
def get_text_exclude_children(element):
return driver.execute_script(
"""
var parent = arguments[0];
var child = parent.firstChild;
var textValue = "";
while(child) {
if (child.nodeType === Node.TEXT_NODE)
textValue += child.textContent;
child = child.nextSibling;
}
return textValue;""",
element).strip()
How to use in this:
liElement = driver.find_element_by_xpath("//li")
liOnlyText = get_text_exclude_children(liElement)
print(liOnlyText)
Please use your possible strategy to get the element, this method need an element from which you need the text (without children text).

Angular 2 / Typescript - how to check an array of objects to see if a property has the same value?

This question does it in Javascript, but I would have thought in Typescript I could do some kind of map/filter operation to do the same thing.
I have an array of objects called Room. Each Room has a property called Width (which is actually a string, eg '4m', '5m', '6.5m').
I need to check the entire array to see if all the widths are the same.
Based on that question I have this, but I was wondering if TypeScript has something better:
let areWidthsTheSame = true;
this.qp.rooms.forEach(function(room, index, rooms) {
if (rooms[index] != rooms[index+1]) areWidthsTheSame = false;
});
Any ideas?
FYI the linked question has a comment that links to these performance tests, which are interesting in the context of this question:
This can be done in the following way:
const widthArr = rooms.map(r => r.width);
const isSameWidth = widthArr.length === 0 ? true :
widthArr.every(val => val === widthArr[0]);
We first convert the rooms array to an array of widths and then we check if all values in widths arrays are equal.

initialized without binding with angular

I need to initialized without binding.
I've tried the following. But I did not succeed
$scope.emptyRow = $scope.newsCategories[1];
$scope.newsCategories[1].Name = "yes";
$scope.emptyRow.Name = "test";
alert($scope.emptyRow.Name); // alert => test
alert($scope.newsCategories[1].Name);// alert => test
I need this :
$scope.emptyRow = $scope.newsCategories[1];
$scope.newsCategories[1].Name = "yes";
$scope.emptyRow.Name = "test";
alert($scope.emptyRow.Name); // alert => test
alert($scope.newsCategories[1].Name);// alert => yes
How to do this?
This has nothing to do with binding, but rather basic javascript.
The line: $scope.emptyRow = $scope.newsCategories[1];
is explicitly saying that you want $scope.emptyRow and $scope.newsCategories[1] to be pointing to the exact same object. Hence, when you change a child value of either (like Name), it will effect the other.
It looks like you want to be able to copy the object in question. For that you can use angular.copy(). An example use in your case would be:
$scope.emptyRow = angular.copy($scope.newsCategories[1]);
Read here for more info.

Resources