renderHook: Context Provider, state change in child function act() error
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 3/5
- Tempo estimado
- 1-2 dias
- Facilidade para iniciantes
- 25/100
- Tipo de issue
- Bug
- Clareza
- Precisa de esclarecimento
- Status de atividade
- Estagnada
- Stack de tecnologia
- javascript, react
- Domínio
- frontend, testing-qa
Direção de pesquisa
Comece pelo hook useUserSearch, seu helper FetchUsers, StoreProvider e a especificação de teste mostrada na issue. Execute o teste do hook com a resposta simulada do axios e acompanhe as atualizações assíncronas de estado; a issue não define uma alteração solicitada nem uma condição clara de conclusão.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
I have a custom hook that uses a Context Provider for global state management. I am passing a dispatch and data from the state taken from the context inside the hook to a function that will at the end of requesting data from an endpoint dispatch this data coursing a state update inside the context API Provider passed down to the custom hook.
The issue is when I test the custom hook with a wrapper of the Context Provider passed into renderHook() function, I get in the test run the dreaded "act()" error of:
Warning: An update to StoreProvider inside a test was not wrapped in act(...)
20 | .then((res) => {
> 22 | setLoading(false)
| ^
23 | dispatch({
24 | type: ActionTypesEnum.FETCH_USERS,
25 | payload: res.data
you can see the full explanation at: https://stackoverflow.com/questions/76157226/react-hooks-testing-library-context-provider-state-change-in-child-function-ac
The useUserSearch Hook:
const useUserSearch = (searchCriteria: string): SearchHookProps => {
// data from the context and stored in the state
const { dispatch, state } = useStateContext();
const { users } = state;
const [ userData, setUserData ] = useState<UserProps[]>([]);
const [ loading, setLoading ] = useState<boolean>(false);
const [ error, setError ] = useState<boolean>(false);
// connected to the pagination affected by the search
const [ currentPage, setCurrentPage ] = useState<number>(1)
const [ totalPages, setTotalPages ] = useState<number>(1)
const [ totalUserCount, setTotalUserCount ] = useState<number>(0)
const totalPerPage = 12
useEffect(() => {
if (users === null) FetchUsers(dispatch, searchCriteria, setLoading, setError);
}, [users]);
useEffect(() => {
if (searchCriteria.length > 0) FetchUsers(dispatch, searchCriteria, setLoading, setError);
}, [searchCriteria]);
return {
userData,
totalUserCount,
setCurrentPage,
currentPage,
totalPages,
loading,
error,
}
}
FetchUsers function:
const FetchUsers = (
dispatch: Dispatch<any>,
searchCriteria: string,
setLoading: Dispatch<SetStateAction<boolean>>,
setError: Dispatch<SetStateAction<boolean>>,) => {
const { global: { apiUrl } } = AppConfig
const search = `?q=${encodeURIComponent(searchCriteria)}`
setLoading(true)
axios.get(`${apiUrl}/users?q=${search}+in:login+type:user`)
.then((res) => {
setLoading(false)
dispatch({
type: ActionTypesEnum.FETCH_USERS,
payload: res.data
})
})
.catch(() => {
setLoading(false)
setError(true)
})
}
StoreProvider:
import React, { useContext, useReducer, useMemo, createContext } from 'react';
import Reducer from '../../Reducers';
import AppConfig from '../../Configs';
import { StateInterface, StoreInterface, ProviderInterface } from '../../Interfaces';
export const initialState: StateInterface = {
appConfig: AppConfig,
users: null,
};
export const StoreContext = createContext({
state: initialState,
} as StoreInterface);
export const useStateContext = () => useContext(StoreContext);
export const StoreProvider = ({ children }: ProviderInterface) => {
const [state, dispatch] = useReducer(Reducer, initialState);
const StoreProviderValue = useMemo(() => ({ state, dispatch }), [state, dispatch]);
return <StoreContext.Provider value={StoreProviderValue}>{children}</StoreContext.Provider>;
};
The Test spec file:
import React from 'react'
import { render, cleanup, waitFor, renderHook, act } from '@testing-library/react'
import axios from 'axios'
import usersMock from '../__mocks__/usersMock'
import { StoreProvider } from '../Providers'
import useUserSearch from './useUserSearch'
jest.mock('axios')
const mockedAxios = axios as jest.Mocked<typeof axios>;
describe('Test that <User />', () => {
const renderHookComponent = (searchCriteria: string) => {
const wrapper = ({ children }: any) => <StoreProvider>{children}</StoreProvider>
const { result, rerender, unmount } = renderHook(() => useUserSearch(searchCriteria), {
wrapper: wrapper as React.ComponentType<any>
})
return { result, rerender, unmount }
}
afterEach(() => {
cleanup()
})
it('renders the hook useUserSearch', async () => {
mockedAxios.get.mockResolvedValue(usersMock);
const { result } = renderHookComponent('test')
// await waitFor(() => {
// expect(result.current.userData.length).toBe(0)
// })
})
})
- Linguagem predominante
- JavaScript
- Estrelas
- 19.7k
- Forks
- 1.2k
- Métricas de merge de PRs
- Nenhum PR com merge em 30d
Preparar o ambiente
- Sem Dockerfile nem arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de testing-library/react-testing-library
-
fireEvent.select does not wrap its automatic native focus in actTalvez já em andamento @sergioperezcheco assumiu há 7 dias. Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 88/100
-
bug: calling configure() without reactStrictMode resets it to undefined, silently disabling strict modeTalvez livre de novo @suhailopensource assumiu há 77 dias e não há nenhum pull request aberto. Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 35/100
testing-library/react-testing-library#1466 · 1 comentário ·
-
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 30/100
testing-library/react-testing-library#1459 · 2 comentários ·
-
perf: optimize container lookup with early exitTalvez livre de novo @Ch-Abhinav-Chowdary assumiu há 303 dias e não há nenhum pull request aberto. Aberta
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 35/100
testing-library/react-testing-library#1430 · 1 comentário ·
-
`fireEvent.mouseEnter` does not forward `relatedTarget` (relatedTarget is the window instead)Talvez já em andamento @swarnim02 assumiu há 320 dias. Aberta
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 55/100
Todas as issues de testing-library/react-testing-library
Issues semelhantes
-
bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 68/100
Mantenedores costumam responder em até 1 dia
-
[scanner] check:spelling skips blog/ — posts and author metadata are never spell-checkedTalvez já em andamento @hivecommons-hive assumiu hoje. Abertaagent/scanner bug hive/covered-by-pr hive/hosted-available-lke648397-260827-5n31
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 72/100
cncf/endusers#1452 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Edit: HTVKey.vnAbertachannels:edit check:passed
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 72/100
Mantenedores costumam responder em até 6 dias
-
bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 72/100
MatAtBread/matbot#95 ·
Mantenedores costumam responder em até 1 dia
-
Status: Pending Review Type: Feature Request
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 82/100
OpenRefine/OpenRefine#8019 ·
Mantenedores costumam responder em até 1 dia