You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fireEvent dispatches DOM events, whereas user-event simulates full interactions, which may fire multiple events and do additional checks along the way.
import'@testing-library/jest-dom'import{fireEvent,render,screen}from'@testing-library/react'importuserEventfrom'@testing-library/user-event'importReactfrom'react'import{MemoryRouter}from'react-router'importSubmitButtonfrom'components/layout/SubmitButton/SubmitButton'importThumbnailDialogfrom'components/pages/Offers/Offer/Thumbnail/ThumbnailDialog'describe('un seul composant',()=>{for(letindex=0;index<500;index++){it('should '+index,()=>{// Givenrender(<SubmitButtonisLoading={false}>{'Enregistrer'}</SubmitButton>)// WhenuserEvent.click(screen.getByText('Enregistrer'))// 4s// fireEvent.click(screen.getByText('Enregistrer')) // 3.1s// Thenexpect(true).toBe(true)})}})describe('plusieurs composants enfant',()=>{for(letindex=0;index<50;index++){it('should '+index,()=>{// Given<MemoryRouter><ThumbnailDialogsetIsModalOpened={jest.fn()}setPreview={jest.fn()}setThumbnailInfo={jest.fn()}/></MemoryRouter>// WhenuserEvent.click(screen.getByLabelText('Importer une image depuis l’ordinateur'))// 65s// fireEvent.click(screen.getByLabelText('Importer une image depuis l’ordinateur')) // 49s// Thenexpect(true).toBe(true)})}})
beforeEach(()=>{jest.spyOn(document,'querySelector').mockReturnValue({appendChild: jest.fn(),})})it('should ...',()=>{// givenconstscript=document.createElement('script')script.src='//js.scripts.com/bundle-min.js'// when// Montage du composant// thenexpect(document.querySelector('form').appendChild).toHaveBeenCalledWith(script)})
Un peu de tout
// Ne pas utilier jest.mock() en en-tête de fichier car cela veut dire qu'il y a du couplage fort.asyncfunctionexemplesDeMocks(navigator: Navigator){navigator.geolocation.getCurrentPosition((position)=>{console.log(position)history.go(1)})constresponse=awaitfetch('une/url',{method: 'POST'})constdata=awaitresponse.json()constitemFromSession=sessionStorage.getItem('login')return{
data,href: location.href,
itemFromSession,varEnv: process.env.NODE_ENV,}}describe('test plein de truc',()=>{it.only('test plein de truc',async()=>{// GIVEN// jest.spyOn pour les fonctions d'un objetjest.spyOn(history,'go').mockImplementationOnce(jest.fn())jest.spyOn(console,'log').mockImplementationOnce(jest.fn())jest.spyOn(sessionStorage.__proto__,'getItem').mockReturnValueOnce('NerOcrO')// @ts-ignorejest.spyOn(global,'fetch').mockResolvedValueOnce({json: ()=>Promise.resolve({})})constposition={coords: {accuracy: 9075.79126982149,altitude: null,altitudeAccuracy: null,heading: null,latitude: 1,longitude: 2,speed: null,},timestamp: 1670251498462,}constmockedNavigator: Navigator={
...navigator,geolocation: {
...navigator.geolocation,getCurrentPosition: (success: PositionCallback)=>success(position),},}// Object.defineProperty pour les attributs d'un objetObject.defineProperty(window,'location',{value: {href: 'local'},writable: true,})// Mieux vaut injecter les variables d'environnements en dépendance// @ts-ignoreprocess.env.NODE_ENV='exemple'// WHENconstresult=awaitexemplesDeMocks(mockedNavigator)// THENexpect(history.go).toHaveBeenCalledWith(1)expect(console.log).toHaveBeenCalledWith(position)expect(global.fetch).toHaveBeenCalledWith('une/url',{method: 'POST'})expect(sessionStorage.getItem).toHaveBeenCalledWith('login')expect(result).toStrictEqual({data: {},href: 'local',itemFromSession: 'NerOcrO',varEnv: 'exemple',})// Ne fonctionne pas et c'est normal car getCurrentPosition() n'est pas un mock mais un fake.// expect(mockedNavigator.geolocation.getCurrentPosition).toHaveBeenCalled()})})
it('vérifie que lerreur nest pas lancée',()=>{// given// pour ne pas afficher le rendu dans le testjest.spyOn(console,'log').mockImplementation(jest.fn())// whenconstresult=fonctionQuiLanceUneException(fonctionQuiLanceVraimentUneException(false))// thenexpect(result).toBe(1)})it('vérifie que lerreur est attrapée',()=>{// whenconstresult=fonctionQuiLanceUneException(fonctionQuiLanceVraimentUneException())// thenexpect(result).toBe(2)})it('vérifie le message',()=>{try{fonctionQuiLanceVraimentUneException()()// ça n'est pas ce message dans le toBe car l'erreur de ma fonction est appelée avantthrownewError('ne devrait pas passer ici')}catch(error){expect(error.message).toBe('toto')}})it('vérifie que lerreur est lancée',()=>{// c'est eslint qui me demande de remplir toThrow alors que ça ne fait pas la différenceexpect(()=>fonctionQuiLanceVraimentUneException()()).toThrow('')})
import{handleEditPasswordSubmit}from'../handleEditPasswordSubmit'import*asconfigfrom'utils/config'constformValues={}consthandleSubmitFail=jest.fn()consthandleSubmitSuccess=jest.fn()describe('when response from API',()=>{beforeEach(()=>{jest.spyOn(config,'API_URL').mockReturnValue('my-localhost')})it('should call fetch properly',async()=>{// Givenjest.spyOn(global,'fetch').mockResolvedValue({json: ()=>Promise.resolve({}),})// whenawaithandleEditPasswordSubmit(formValues,handleSubmitFail,handleSubmitSuccess)// Thenexpect(global.fetch).toHaveBeenCalledWith('my-localhost/users/current/change-password',{body: JSON.stringify(formValues),credentials: 'include',headers: {'Content-Type': 'application/json',},method: 'POST',})})it('should call success function',async()=>{// Givenjest.spyOn(global,'fetch').mockResolvedValue({json: ()=>Promise.resolve({}),ok: true,})// whenawaithandleEditPasswordSubmit(formValues,handleSubmitFail,handleSubmitSuccess)// Thenexpect(handleSubmitSuccess).toHaveBeenCalledTimes(1)})})describe('when status is 400',()=>{it('should call fail function',async()=>{// Givenjest.spyOn(global,'fetch').mockResolvedValue({json: ()=>Promise.resolve({errors: ['error message']}),status: 400,})// whenawaithandleEditPasswordSubmit(formValues,handleSubmitFail,handleSubmitSuccess)// Thenexpect(handleSubmitFail).toHaveBeenCalledWith({errors: ['error message']})})})describe('when status is other that 400',()=>{it('should stop the app',async()=>{// Givenjest.spyOn(global,'fetch').mockResolvedValue({json: ()=>Promise.resolve({}),ok: false,status: 582,statusText: 'Error',})try{// WhenawaithandleEditPasswordSubmit(formValues,handleSubmitFail,handleSubmitSuccess)thrownewError('ne devrait pas passer par ici')}catch(erreur){// Thenexpect(erreur).toBeInstanceOf([TON_EXCEPTION_400])}})})describe('when no response from API',()=>{it('should stop the app',async()=>{// Givenjest.spyOn(global,'fetch').mockRejectedValue(newError('API is down'))try{// WhenawaithandleEditPasswordSubmit(formValues,handleSubmitFail,handleSubmitSuccess)thrownewError('ne devrait pas passer par ici')}catch(erreur){// Thenexpect(erreur.message).toBe('API is down')expect(erreur).toBeInstanceOf([TON_EXCEPTION_500])}})})