When selecting dom elements use data-testid instead of using a class or id.
Testing Ui Business Logic
Separate the business logic from the view as much as possible. Create hooks, helpers & reducers to utilize this logic from the ui and test that code in isolation from it's ui.
Unit Testing
This is an example of how we structure our unit tests.
import mockAxios from'axios'import { isLoggedIn } from'./isLoggedIn'constUserData= { id:1, name:'UserName' }constmockUserData= id => {mockAxios.get.mockImplementationOnce(() =>Promise.resolve(id ? data :undefined))}describe('isLoggedIn', () => {describe('isLoggedIn', () => {it('should return true when passed a userId', () => {constuserId=1mockUserData(userId)expect(isLoggedIn(userId)).toBe(true) })it('should return false when userId is undefined', () => {constuserId=undefinedmockUserData(userId)expect(isLoggedIn(userId)).toBe(false) }) })})
Hook Testing
This is an example of how we structure our hook tests
import { renderHook } from'@testing-library/react-hooks'import { useIsComponentMounted } from'./useIsComponentMounted'constsetup= () => {returnrenderHook(() =>useIsComponentMounted())}describe('useIsComponentMounted hook', () => {it('should be true on render', () => {const { result } =setup()expect(result.current.current).toBe(true) })it('should false on unmount', () => {const { result,unmount } =setup()unmount()expect(result.current.current).toBe(false) })})