I want to check if inside my component exists a button.
import React, {useState} from 'react';
const Text = ({text}) => {
const [state, setState]= useState(0);
const add = () => {
setState(state+1)
};
return (
<div>
<h1>Hello World</h1>
<h2>Hello {text}</h2>
<h2>Count {state}</h2>
<button role="button" onClick={add}>Increase</button>
</div>
);
};
export default Text;
For that test i created:
test('check counter', ()=> {
const { getByText } = render(<Text />);
const button = getByText("Increase");
expect(button.toBeTruthy())
});
After running the test i get TypeError: button.toBeTruthy is not a function
.
Why this errror appears and how to solve the issue?
In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements.
We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.
var element = document. getElementById('elementId'); if (typeof(element) != 'undefined' && element != null) { // Exists. }
JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.
You have a mistake; The toBeTruthy() is not a function from the button is a function from the expect method.
test('check counter', ()=> {
const { getByText } = render(<Text />);
const button = getByText("Increase");
expect(button).toBeTruthy()
});
Just one short note on how to improve this a little bit. Instead of using toBeTruthy()
jest-dom
utility library provides the .toBeInTheDocument()
matcher, which can be used to assert that an element is in the body of the document, or not. This can be more meaningful than asserting truthfulness in this case.
Also it would be better to get the button by role instead of text since it is a preferable way by priority.
test('check counter', ()=> {
const { getByRole } = render(<Text />);
const button = getByRole('button');
expect(button).toBeInTheDocument()
});
I would suggest a better way to test this would be to make use of the "data-testid" attribute for the element
<div>
<h1>Hello World</h1>
<h2>Hello {text}</h2>
<h2>Count {state}</h2>
<button role="button" data-testid="required-button" onClick={add}>Increase</button>
</div>
test('check counter', ()=> {
const { getByTestId } = render(<Text />);
const button = getByTestId("required-button");
expect(button).toBeInTheDocument();
});
The reason i would do this is getByText would be true for any occurrence of the word Increase in the page
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With