I'm using React v15.4, babel-jest v18 and enzyme v2.5.1
I have a simple React Component:
MyComponent.js
import React, { useState, useEffect, useCallback } from 'react';
import Loader from '../components/Loader';
import axios from 'axios';
const MyComponent = () => {
const [loading, setLoading] = useState(true);
const [inputs, setInputs] = useState();
const getData = useCallback(() => {
axios.get('http://jsonplaceholder.typicode.com/todos/1')
.then(res => {
console.log(res.data)
setInputs(res.data);
setLoading(false);
}).catch(error => {
console.log(error);
setLoading(false);
});
},[]);
useEffect(() => {
getData();
},[getData]);
return(
<div>
<Loader isLoading={loading} />
{(inputs && !loading) &&
<>
<h2>User Information</h2>
<p>{inputs.id}</p>
<p>{inputs.userId}</p>
<p>{inputs.title}</p>
<p>{inputs.completed}</p>
</>}
</div>
);
};
export default MyComponent;
MyComponent.test.js
import {render} from '@testing-library/react';
import MyComponent from '../components/MyComponent';
import React from "react";
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
test('My Component', () => {
render(<MyComponent />)
const widget = mount(<MyComponent />);
widget.find('h2').text().contains('User Information')
})
The Jest test should pass but I'm getting an error:
Method “text” is only meant to be run on a single node. 0 found instead.
OR how can I initialize state value to test if h2 tag is present in dom or not?