React Testing Library toBeInTheDocument failing despite being in the DOM - reactjs

I have a test which basically contains the following code:
const row = await screen.findByText('Test Subject');
try {
expect(row).toBeInTheDocument();
} catch (e) {
screen.debug();
throw e;
}
The debug is for trying to track this down. findByText succeeds, and does find the element. I can log this out, and it appears. But when I do the expect, it fails SOMETIMES. It's unpredictable. I'm pretty certain the DOM isn't changing between calls, as I have logs out on every render and nothing logs out between the find and the assert.
I won't print the whole DOM tree, but on the catch debug, I can clearly see the row.
<tr
class="sc-jgrIVw bDPrDC"
>
<td
class="sc-jeqYYF hinrdE"
>
<div
class="sc-clIAKW jvtlES"
>
05-Dec-2022 12:08
</div>
</td>
<td
class="sc-jeqYYF ijUrhn"
>
<div
class="sc-clIAKW jvtlES"
>
<div
title="Test"
>
Test
</div>
</div>
</td>
<td
class="sc-jeqYYF ijUrhn"
>
<div
class="sc-clIAKW jvtlES"
>
Test Subject
</div>
</td>
</tr>
So as far as I can tell, RTL knows my DOM is there, the DOM log shows its there, but toBeInTheDocument throws. What could I be missing?

Related

There are any ways of suppressing single validateDOMNesting warning in React?

In my case I have something like this:
<div className="projects">
{getProjectList().map(p => (
<Link key={p.id}
className='project'
to={`/project/${p.id}`}
style={{border: '2px solid red'}}
>
#{p.id} - {p.name}
<div className="helpers">
<Button
icon="trash"
size="mini"
color="red"
onClick={e => {
e.preventDefault();
e.stopPropagation();
setDeleting(p);
}}
/>
<Button
size="mini"
color="red"
as={Link}
to={`/edit/${p.id}`}
>Edit</Button>
</div>
</Link>
))}
</div>
which visually is represented like this:
And I would prefer to keep it like this because it works as it is intended.
Additional explanation why I want it this way: I want to provide to user ability to click on both links with right mouse button and choose "Open Link in New Tab". To navigate to details of the projects and also navigate to edit form to change properties of the project (These are two different pages).
But in this case I have two times tag embedded in each other and React generate:
Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>.
any ways to suppress it?
I'm working on rendering emails with React and ran into the same issue because it's recommended to exclude <tbody> for some Email Service Providers (link)
I wasn't able to suppress the error directly, instead, I added a __isTest prop to my component and then only added <tbody> when __isTest === true:
return __isTest ? (
<table>
<tbody>
<tr>
<td>{children}</td>
</tr>
</tbody>
</table>
) : (
<table>
<tr>
<td>{children}</td>
</tr>
</table>
)
I would definitely prefer to be able to suppress the warning, but this is an alternative that may work in certain cases.
Just add /* eslint-disable */ in the file you want the warnings to be suppressed as explained in the official github repository how to hide unwanted warning.
Remember that's not best practice.

Links to external resource are empty in React

In a React app I have a Table tbody of which looks the following way:
<tbody>
{
this.state.datasets.map((datasetName, idx) => {
return (<tr>
<td>
<div className={"pretty p-default p-curve"}>
<input id = {"datasetCheckBox" + idx}
checked = {this.state.checkBoxSelected === datasetName}
type="radio" name="datasetName"
onChange={(e) => this.checkBoxSelected(datasetName, e)}/>
<div className={"state p-primary"}>
<label>{idx}</label>
</div>
</div>
</td>
<td>{datasetName}</td>
<td>{datasetsJSON["datasets"][datasetName]["region"]}</td>
<td>{datasetsJSON["datasets"][datasetName]["authors"]}</td>
<td>
<a href={datasetsJSON["datasets"][datasetName]["link"]}>{datasetName}</a>
</td>
</tr>)
}, this)
}
</tbody>
The link is shown with an empty href even though other parameters of the table from datasetsJSON["datasets"][datasetName] are set correctly. I tried using React Router and the only piece of code that redirected to links is in the answer here:
React-Router External link
But in the answer to the question above if I set path="/", when the table loads, it is just redirecting me straight away to the first link. I would expect then that for each link the path should be different, but supplying datasetsJSON["datasets"][datasetName]["link"] as a path does not work either. Why is the simple link a empty? How could I fix it?
I solved it by using onClick method instead of href link attribute. In the table I have:
<td onClick = {() => this.articleClicked(datasetName)}>
<span role="button"><a>{datasetName}</a></span>
</td>
Then, onClick method:
articleClicked = (datasetName) => {
let url = datasetsJSON["datasets"][datasetName]["link"];
window.open(url);
}
<span role="button"> is needed for the cursor to show hand when the user is hovering over the link. It is bootstrap thing.

ng-repeat over 11k rows crashing

I'm trying to do a table (with a lot of data) with Angular, the table is already done with PHP but to add a filter is easier using Angular. PHP takes 10secs to draw the entire table of 11k rows, but Angular keeps going on and on, even Firefox tells me that a script is unasnwered. If I click continue, the message is shown again, if I click cancel the page does nothing, if I press debug it continues running but nothing is shown.
At first, I thought that drawing +11k rows in HTML with the ng-repeat was too much and that was causing the problem, so I added a limitTo (50) and also added a infinite scroll div. But it's still not showing anything and keeps on loading.
Here is some code:
<div ng-app='mainApp'>
<div ng-init='values=[".$angularString."]' ng-controller='seeTickets as tickets'>
<div infinite-scroll='tickets.loadMore()' infinite-scroll-distance='1'>
Filtro: <input type='text' ng-model='globalSearch.$'/><br><br>
<script type='text/javascript'>
var app = angular.module('mainApp', []);
app.controller('seeTickets', function(){
this.totalDisplayed = 50;
this.loadMore = function(){
this.totalDisplayed += 50;
}
});
</script>
<table>
<tr ng-repeat="value in values | filter:globalSearch | limitTo:tickets.totalDisplayed">
<td> {{value.id_ticket}} </td>
<td> {{value.ticket_date}} </td>
<td> {{value.ticket_subject}} </td>
<td> {{value.ticket_from}} </td>
<td> {{value.ticket_to}} </td>
<td> {{value.ticket_priority}} </td>
</tr>
</table>
</div>
</div>
</div>
Am I doing something wrong? Is there a way to work this out? Why it's keep on loading even if I set limitTo?
Add track by $index to ng-repeat like this:
<tr ng-repeat="value in values | filter:globalSearch | limitTo:tickets.totalDisplayed track by $index">
...
</tr>

react ref with focus() doesn't work without setTimeout (my example)

I have encounter this problem, the .focus() only works with setTimeout if i take it out and it stop working. can anyone explain me what's the reason for that, possible i am doing it incorrectly and how can i fix the problem.
componentDidMount() {
React.findDOMNode(this.refs.titleInput).getElementsByTagName('input')[0].focus();
}
works example with setTimeout
componentDidMount() {
setTimeout(() => {
React.findDOMNode(this.refs.titleInput).getElementsByTagName('input')[0].focus();
}, 1);
}
JXS
<input ref="titleInput" type="text" />
and i have followed this example React set focus on input after render
render function
render() {
const {title, description, tagtext, siteName} = (this.state.selected !== undefined) ? this.state.selected : {};
const hasContentChangedYet = this.hasContentChangedYet(title, description);
return (
<div>
<h2 className={styles.formMainHeader}>Edit Meta-Data Form</h2>
<table className={styles.formBlock}>
<tbody>
<tr>
<td className={styles.tagEditLabel}>
Tag
</td>
<td className={styles.inputFieldDisableContainer}>
{tagtext}
</td>
</tr>
<tr>
<td className={styles.tagEditLabel}>
Site
</td>
<td className={styles.inputFieldDisableContainer}>
{siteName}
</td>
</tr>
<tr>
<td className={styles.tagEditLabel}>
Title
</td>
<td className={styles.inputFieldContainer}>
<ReactInputField
ref="titleInput"
id="title"
defaultValue={(title) ? title : ''}
onChange={this.onInputChange}
placeholder="Title"
clearTool={true} />
</td>
</tr>
<tr>
<td className={styles.tagEditLabel}>
Description
</td>
<td className={styles.inputFieldContainer}>
<ReactInputField
id="description"
defaultValue={(description) ? description : ''}
onChange={this.onInputChange}
placeholder="Description"
clearTool={true} />
</td>
</tr>
</tbody>
</table>
<div className={styles.formFooter}>
<button id="save-button" className={styles.saveButton} disabled={!hasContentChangedYet} onClick={() => this.handleSavePressed()}>
Save
</button>
<button id="form-cancel-button" className={styles.cancelButton} onClick={this.actions.form.cancelUpdateToTagData}>
Cancel
</button>
</div>
</div>
);
}
After seeing the update to the question, I realise that you have deeply nested HTML passed to the render function, and the input element of your interest will indeed not be available at the time of the componentDidMount call on the ancestor element. As stated in the React v0.13 Change Log:
ref resolution order has changed slightly such that a ref to a component is available immediately after its componentDidMount method is called; this change should be observable only if your component calls a parent component's callback within your componentDidMount, which is an anti-pattern and should be avoided regardless
This is your case. So either you have to break down the HTML structure into separately rendered elements, as described here, and then you would access the input element in its own componentDidMount callback; or you just stick with the timer hack you have.
Use of componentDidMount makes sure the code runs only when the component on which it is called is mounted (see quote from docs further down).
Note that calling React.findDOMNode is discouraged:
In most cases, you can attach a ref to the DOM node and avoid using findDOMNode at all.
Note
findDOMNode() is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction.
findDOMNode() only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling findDOMNode() in render() on a component that has yet to be created) an exception will be thrown.
And from the docs on the ref string attribute:
Assign a ref attribute to anything returned from render such as:
<input ref="myInput" />
In some other code (typically event handler code), access the backing instance via this.refs as in:
var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();
Alternatively, you could eliminate the need of the code, and use the JSX autoFocus attribute:
<ReactInputField
ref="titleInput"
autoFocus
... />
Using setTimeout() is a bad idea and using componentDidMount() is irrelevant. You may find the answer to your question in the following example:
In a parent component I render a primereact Dialog with an InputText in it:
<Dialog visible={this.state.visible} ...>
<InputText ref={(nameInp) => {this.nameInp = nameInp}} .../>
...
</Dialog>
Initially, this.state.visible is false and the Dialog is hidden.
To show the Dialog, I re-render the parent component by calling showDlg(), where nameInp is the ref to InputText:
showDlg() {
this.setState({visible:true}, ()=>{
this.nameInp.element.focus();
});
}
The input element gets the focus only after rendering has been accomplished and the setState callback function called.
Instead of using the setState callback, in some cases you may simply use:
componentDidUpdate(){
this.nameInp.element.focus();
}
However, componentDidUpdate() is being called every time you (re)render the component, including in case the InputText is hidden.
See also: https://reactjs.org/docs/react-component.html#setstate

How to correctly wrap few TD tags for JSXTransformer?

I have an array with items and I want to make something like this:
<tr>
(until have items in array
<td></td><td></td>)
</tr>
But if I do that, I get an JSXTransformer error :
Adjacent XJS elements must be wrapped in an enclosing tag
Working version:
{rows.map(function (rowElement){
return (<tr key={trKey++}>
<td className='info' key={td1stKey++}>{rowElement.row[0].value}</td><td key={td2ndKey++}>{rowElement.row[0].count}</td>
<td className='info' key={td1stKey++}>{rowElement.row[1].value}</td><td key={td2ndKey++}>{rowElement.row[1].count}</td>
<td className='info' key={td1stKey++}>{rowElement.row[2].value}</td><td key={td2ndKey++}>{rowElement.row[2].count}</td>
<td className='info' key={td1stKey++}>{rowElement.row[3].value}</td><td key={td2ndKey++}>{rowElement.row[3].count}</td>
<td className='info' key={td1stKey++}>{rowElement.row[4].value}</td><td key={td2ndKey++}>{rowElement.row[4].count}</td>
.......
</tr>);
})}
I tried this one. But with <div> enclosing tag it doesn't work fine.
Answer here:
Uncaught Error: Invariant Violation: findComponentRoot(..., ...$110): Unable to find element. This probably means the DOM was unexpectedly mutated
<tbody>
{rows.map(function (rowElement){
return (<tr key={trKey++}>
{rowElement.row.map(function(ball){
console.log('trKey:'+trKey+' td1stKey'+td1stKey+' ball.value:'+ball.value+' td2ndKey:'+td2ndKey+' ball.count:'+ball.count);
return(<div key={divKey++}>
<td className='info' key={td1stKey++}>{ball.value}</td><td key={td2ndKey++}>{ball.count}</td>
</div>);
})}
</tr>);
})}
</tbody>
Please, advise me how to properly wrap few TD tags!
I tried use a guide Dynamic Children, but JSXTransformer doesn't allow me do that.
The following error usually occurs when you are returning multiple elements without a wrapping element
Adjacent XJS elements must be wrapped in an enclosing tag
Like
return (
<li></li>
<li></li>
);
This doesn't work because you are effectively returning two results, you need to only ever be returning one DOM node (with or without children) like
return (
<ul>
<li></li>
<li></li>
</ul>
);
// or
return (<ul>
{items.map(function (item) {
return [<li></li>, <li></li>];
})}
</ul>);
For me to properly answer your question could you please provide a JSFiddle? I tried to guess what you're trying to do and heres a JSFiddle of it working.
When using the div as a wrapper its actually never rendered to the DOM (not sure why).
<tr data-reactid=".0.0.$1">
<td class="info" data-reactid=".0.0.$1.$0.0">1</td>
<td data-reactid=".0.0.$1.$0.1">2</td>
<td class="info" data-reactid=".0.0.$1.$1.0">1</td>
<td data-reactid=".0.0.$1.$1.1">2</td>
<td class="info" data-reactid=".0.0.$1.$2.0">1</td>
<td data-reactid=".0.0.$1.$2.1">2</td>
<td class="info" data-reactid=".0.0.$1.$3.0">1</td>
<td data-reactid=".0.0.$1.$3.1">2</td>
</tr>
EDIT: React 16+
Since React 16 you can now use fragments.
You would do it like this now
return <>
<li></li>
<li></li>
<>;
Or you can use <React.Fragment>, <> is shorthand for a HTML fragment, which basically is just a temporary parent element that acts as a container, once its appended to the document it no longer exists.
https://reactjs.org/docs/fragments.html
https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
So you have pairs of <td> elements which you want to return from a .map. The easiest way to do this is to just wrap them in an array.
<tr>
{data.map(function(x, i){
return [
<td>{x[0]}</td>,
<td>{x[1]}</td>
];
})}
</tr>
Don't forget the comma after the first </td>.
With the release of React 16, there is a new component called Fragment.
If are would like to return a collection of elements/components without having to wrap them in an enclosing element, you can use a Fragment like so:
import { Component, Fragment } from 'react';
class Foo extends Component {
render() {
return (
<Fragment>
<div>Hello</div
<div>Stack</div>
<div>Overflow</div>
</Fragment>
);
}
}
Here is how you will do it
<tbody>
{this.props.rows.map((row, i) =>
<tr key={i}>
{row.map((col, j) =>
<td key={j}>{col}</td>
)}
</tr>
)}
</tbody>

Resources