how to test useeffect hook code example
Example 1: How to test useEffect in react testing library
import { List } from './';
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { render, waitForElement } from '@testing-library/react';
describe('59892259', () => {
let originFetch;
beforeEach(() => {
originFetch = (global as any).fetch;
});
afterEach(() => {
(global as any).fetch = originFetch;
});
it('should pass', async () => {
const fakeResponse = { title: 'example text' };
const mRes = { json: jest.fn().mockResolvedValueOnce(fakeResponse) };
const mockedFetch = jest.fn().mockResolvedValueOnce(mRes as any);
(global as any).fetch = mockedFetch;
const { getByTestId } = render(<List></List>);
const div = await waitForElement(() => getByTestId('test'));
expect(div).toHaveTextContent('example text');
expect(mockedFetch).toBeCalledTimes(1);
expect(mRes.json).toBeCalledTimes(1);
});
});
Example 2: react eznyme fetch api using hooks
import React from 'react'
import FetchData from './FetchData'
const fetchUsers = () =>
fetch('https://jsonplaceholder.typicode.com/users').then((res) => res.json())
function App() {
return (
<>
<FetchData fetchUsers={fetchUsers} />
</>
)
}
export default App
import React, { useState } from 'react'
function fetchData({ fetchUsers }) {
const [state, setState] = useState([])
React.useEffect(() => {
fetchUsers().then(setState)
}, [])
return (
<>
{state &&
state.map((val, id) => (
<ul key={id}>
<li>{val.name}</li>
</ul>
))}
</>
)
}
export default fetchData
import React from 'react'
import { shallow } from 'enzyme'
import FetchData from '../FetchData'
describe('Fetch All Data Hooks', () => {
let props
let wrapper
let useEffect
const users = [
{ id: 1, name: 'jamal' },
{ id: 2, name: 'karyo' },
{ id: 3, name: 'mirdad' }
]
beforeEach(() => {
useEffect = jest.spyOn(React, 'useEffect').mockImplementationOnce((f) => f())
props = { fetchUsers: jest.fn().mockResolvedValue(users) }
wrapper = shallow(<FetchData {...props} />)
})
afterAll(() => {
jest.clearAllMocks()
})
it('result all users', () => {
expect(useEffect).toHaveBeenCalled()
expect(props.fetchUsers).toHaveBeenCalled()
expect(props.fetchUsers).toHaveBeenCalledTimes(1)
expect(jest.isMockFunction(props.fetchUsers)).toBeTruthy()
})
it('find render all users exits count', () => {
expect(wrapper.find('ul > li')).toHaveLength(3)
expect(
wrapper.containsAllMatchingElements([
<ul>
<li>jamal</li>
</ul>,
<ul>
<li>karyo</li>
</ul>,
<ul>
<li>mirdad</li>
</ul>
])
).toBeTruthy()
})
})