Last active
March 16, 2023 11:32
-
-
Save Bolza/d2b4c548e2c18cad1d377f6af5902b9b to your computer and use it in GitHub Desktop.
Jest Cookbook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// TROUBLESHOOTING | |
// Check rendering happens after setting spy | |
// Simply mock a library function | |
jest.spyOn(realtimeSlice, 'sendMessage'); | |
// Click and wait | |
import { render, waitFor } from '@testing-library/react'; | |
import userEvent from '@testing-library/user-event'; | |
it('should render content of one accordion when clicked', async () => { | |
render(<InCallPanel users={Users.slice(0, 1)} />); | |
const user = userEvent.setup(); | |
await user.click(screen.getByRole('button')); | |
waitFor(() => { | |
expect(screen.getAllByRole('button').length).toBe(6); | |
expect(screen.getByTestId('buttonbar')).toBeDefined(); | |
}, | |
{ timeout: 300 }); // <- can be needed or not | |
}); | |
// Mock typing | |
import { screen, fireEvent } from '@testing-library/react'; | |
it('should add a newline when pressing SHIFT+ENTER when there is a some content', () => { | |
const onSubmit = jest.fn(); | |
renderWithTheme(<ChatInput placeholder='test' onSubmit={onSubmit} />); | |
const input: HTMLTextAreaElement = screen.getByPlaceholderText('test'); | |
act(() => { | |
fireEvent.change(input, { target: { value: 'Hello' } }); | |
fireEvent.keyPress(input, { | |
key: 'Enter', | |
code: 13, | |
charCode: 13, | |
shiftKey: true, | |
}); | |
}); | |
expect(input).toHaveValue('Hello\n'); | |
}); | |
// Mock default function from libraries | |
import isomorphicFetch from 'isomorphic-fetch' | |
jest.mock('isomorphic-fetch') | |
beforeEach(() => { | |
isomorphicFetch.mockImplementation(() => Promise.resolve({ | |
json: () => Promise.resolve(OrdersMockV2), | |
})) | |
}) | |
afterEach(() => { | |
jest.clearAllMocks() | |
}) | |
//Enzyme | |
wrapper = shallow(<CheckoutPayment/>) | |
wrapper.find(SubmitButton).simulate('click') | |
expect(wrapper.find(CheckoutCardDetails).prop('isSubmitCardEnabled')).toBe(false) | |
// Test Hook | |
const { result, waitForNextUpdate } = renderHook(() => useMyHook()) | |
await waitForNextUpdate() | |
expect(typeof result.current).toBe([get, set]) | |
// Mock AppSelector generically | |
jest.mock('../../hooks/useReduxToolkit', () => ({ | |
useAppSelector: (selector: () => unknown) => selector(), | |
})); | |
// Mock Redux | |
import { useDispatch, useSelector } from 'react-redux' | |
jest.mock('react-redux', () => ({ | |
...jest.requireActual('react-redux'), | |
useDispatch: jest.fn(() => true), | |
useSelector: jest.fn(), | |
})) | |
useSelector.mockReturnValue(true) | |
useDispatch.mockReturnValue(() => {}) | |
// Mock Hook | |
import { useMyHook } from './useMyHook' | |
jest.mock('../../hooks/useCall', () => ({ | |
useCall: jest.fn().mockReturnValue({ | |
participants: new Map([['1', Participant]]), | |
}), | |
})); | |
// or | |
jest.mock('./useMyHook', () => ({ | |
useMyHook: jest.fn() | |
})) | |
beforeEach(() => { | |
useMyHook.mockReturnValue('somevalue') | |
}) | |
// Render Component w/ react-testing library | |
import '@testing-library/jest-dom' | |
import { render, screen, fireEvent, } from '@testing-library/react' | |
render(<FiveRecipesAddRecipeButton />) | |
// Mock Component | |
jest.mock('./MyComponent', () => ({ | |
MyComponent: () => <div data-testid="myComponent" />, | |
})) | |
// Mock HOOK | |
import * as MyHook from 'myhook' | |
const mockedGetOptimizelyInstance = jest.spyOn(MyHook, './myHook') | |
myHook.mockImplementation(() => { }) // optional | |
describe('SomeFeature', () => { | |
afterEach(() => { jest.clearAllMocks() }) | |
beforeEach(() => { myHook.mockReturnValue(true) }) | |
describe('When myHook is true', () => { | |
//... | |
}) | |
}) | |
// Mock Window funcs | |
beforeEach(() => { | |
// eslint-disable-next-line no-proto | |
getItemSpy = jest.spyOn(window.localStorage.__proto__, 'getItem') | |
// eslint-disable-next-line no-proto | |
setItemSpy = jest.spyOn(window.localStorage.__proto__, 'setItem') | |
// eslint-disable-next-line no-proto | |
removeItemSpy = jest.spyOn(window.localStorage.__proto__, 'removeItem') | |
}) | |
// Mock Routing | |
beforeEach(() => { | |
state = { | |
routing: { | |
locationBeforeTransitions: { | |
query: { opt_features: 'flag=true' } | |
} | |
} | |
} | |
}) | |
// Mock Redux Selector | |
useSelector.mockImplementation(selector => selector(state)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment