wrapper context is not shared with `renderHook`
@Lucatonello ya está trabajando en esto.
Desde el 2/12/2024.
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 35/100
- Tipo de issue
- Nueva funcionalidad
- Claridad
- Bastante claro
- Estado de actividad
- Estancado
- Stack tecnológico
- javascript, react
Línea de trabajo
Comienza con el comportamiento del wrapper de renderHook y las aserciones de waitFor mostradas en el issue. Traza cómo las llamadas independientes a renderHook montan sus wrappers y compáralo después con una única llamada a renderHook que contenga varias funciones de hook. La implementación debería establecer una forma compatible de probar de manera independiente instancias de hook relacionadas, o documentar la limitación y el enfoque de pruebas recomendado.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
I have a hook that does some complicated things with state[^1]. Specifically, it works like this:
const [pizza, setPizza] = usePizza()
console.log(pizza)
// { my: { slice: "slice22" }, other: { slice: "slice19" } }
const [slice] = usePizza(pizza => pizza.my.slice)
console.log(slice)
// "slice22"
When the user calls setPizza, a new pizza object gets set globally. But the second instance of the hook usePizza(pizza => pizza.my.slice) does not re-render unless that "slice" of the global pizza object specifically changed. (In other words, if pizza.my.slice returns the same value as before ("slice22"), any component using that hook will not re-render.)
This property of not re-rendering unless necessary is a critical part of the hook. I want to test it. To do that, I need to do something like this:
const wrapper = (
... common context here (from Tanstack Query)
)
// for the moment, let's pretend I have methods `.toHaveRenderedOnce` and `.toHaveRenderedTwice`
test('it only re-renders a slice when it changes', () => {
const {result: fullPizza} = renderHook(() => usePizza(), {wrapper})
const {result: mySlice} = renderHook(() => usePizza(pizza => pizza.my.slice), {wrapper})
const {result: otherSlice} = renderHook(() => usePizza(pizza => pizza.other.slice), {wrapper})
const updatedPizza = { my: { slice: "slice22" }, other: { slice: "slice55" }}
const [pizza, setPizza] = fullPizza.current
setPizza(updatedPizza)
await waitFor(() => {
expect(fullPizza.current[0]).toEqual(updatedPizza)
})
// my slice did not change; it should render once
await waitFor(() => {
expect(mySlice.current[0]).toEqual("slice22")
expect(mySlice).toHaveRenderedOnce() // notional
})
// other slice changed; it should render twice
await waitFor(() => {
expect(otherSlice.current[0]).toEqual("slice55")
expect(mySlice).toHaveRenderedTwice() // notional
})
})
There are (at least) two problems here. The first is that there's no way to check how many times the hook rendered, but that's a different problem (for which I may have a rudimentary solution).
The second problem, and the subject of this issue, is that it seems that the wrapper context is not shared between my two hooks. This line does not work:
await waitFor(() => {
expect(otherSlice.current[0]).toEqual("slice55")
})
// this value is never picked up when I change it in the other hook
So, even though the wrapper itself is the same instance, the two hooks don't seem to be sharing the same React context. I can do this instead:
const {result} = renderHook(() => [
() => usePizza(),
() => usePizza(pizza => pizza.my.slice),
() => usePizza(pizza => pizza.other.slice)
], {wrapper})
This solves the wrapper issue; changes in usePizza() are reflected in the other slice (usePizza(pizza => pizza.other.slice)). But unfortunately now all three instances of the hook are rendered in tandem, so they always all have the same number of renders. I can't verify that usePizza(pizza => pizza.my.slice) doesn't re-render.
I suppose it makes sense that the context is isolated between different calls to renderHook, or we might leak state in between tests. But then how can I test this functionality? Is there a way using this library to test that a change inside one hook instance either does or does not trigger an update/re-render in another related hook instance?
[^1]: Specifically, I'm using Tanstack Query's select data transformation, similar to the idea of useContextSelector.
- Lenguaje dominante
- JavaScript
- Estrellas
- 19.7k
- Forks
- 1.2k
- Métricas de merge de PR
- Sin PR fusionados en 30 d
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de testing-library/react-testing-library
-
fireEvent.select does not wrap its automatic native focus in actPosiblemente ocupada @sergioperezcheco la tomó hace 4 días. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
-
bug: calling configure() without reactStrictMode resets it to undefined, silently disabling strict modeQuizá libre de nuevo @suhailopensource la tomó hace 74 días y no hay ningún pull request abierto. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 35/100
testing-library/react-testing-library#1466 · 1 comentario ·
-
Dificultad 4/5 3-5 días Aptitud para principiantes 30/100
testing-library/react-testing-library#1459 · 2 comentarios ·
-
perf: optimize container lookup with early exitQuizá libre de nuevo @Ch-Abhinav-Chowdary la tomó hace 300 días y no hay ningún pull request abierto. Abierto
Dificultad 1/5 Menos de una hora Aptitud para principiantes 35/100
testing-library/react-testing-library#1430 · 1 comentario ·
-
`fireEvent.mouseEnter` does not forward `relatedTarget` (relatedTarget is the window instead)Posiblemente ocupada @swarnim02 la tomó hace 317 días. Abierto
Dificultad 3/5 1-2 días Aptitud para principiantes 55/100
Todos los issues de testing-library/react-testing-library
Issues similares
-
[dsh-plugin.org | dsh-plugin-hub] plugin distribution incomplete: yjh051108/dsh-routing-suiteAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 71/100
yjh051108/dsh-routing-suite#227 ·
-
needs-triage release-watch
Dificultad 1/5 Menos de una hora Aptitud para principiantes 76/100
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
dusk-network/exu#17 ·
-
Dificultad 1/5 Menos de una hora Aptitud para principiantes 88/100
jspreadsheet/ce#1809 ·
-
documentation
Dificultad 1/5 Menos de una hora Aptitud para principiantes 91/100
githubnext/gh-aw-workshop#4458 ·
Los mantenedores suelen responder en 1 día