Description
react-hooks-testing-library
version: 3.2.1react-test-renderer
version: 16.9.0react
version: 16.9.0node
version: 12.9.0npm
(oryarn
) version: yarn v1.21.1
Relevant code or config:
// test.js
import React from "react"
window.doSomethingWithThisDiv = element => {
const newEl = document.createElement("div")
newEl.innerText = "hello world"
element.appendChild(newEl)
}
const context = React.createContext(null)
export const Provider = ({ children }) => {
const myRef = React.useRef(null)
const [showDiv, setShowDiv] = React.useState(false)
const contextValue = React.useMemo(() => {
return {
showDiv,
setShowDiv
}
}, [showDiv, setShowDiv])
React.useEffect(() => {
if (showDiv) {
window.doSomethingWithThisDiv(myRef.current)
}
}, [showDiv])
return (
<context.Provider value={contextValue}>
{showDiv && <div ref={myRef} />}
{children}
</context.Provider>
)
}
export const useTest = () => {
return React.useContext(context)
}
// test.spec.js
import React from "react"
import sinon from "sinon"
import { renderHook } from "@testing-library/react-hooks"
import { Provider, useTest } from "test"
describe("testing context", () => {
it("works", () => {
const spy = sinon.spy(window, "doSomethingWithThisDiv")
const { result } = renderHook(useTest, {
wrapper: ({ children }) => <Provider>{children}</Provider>
})
result.current.setShowDiv(true)
expect(spy.callCount).to.equal(1)
})
})
What you did:
NODE_ENV=test mocha --opts path/to/opts test.spec.js
What happened:
Error message due to the ref being null in the effect in test.js
warning Error: Uncaught [TypeError: Cannot read property 'appendChild' of null]
Reproduction:
See the code snippets above
Problem description:
Apologies for the super contrived example, but I was luckily able to reproduce the same issue I am seeing in my much more complicated application. Basically I am testing some features of a React context which exposes some state and an API to interact with that data. I am doing so by testing a custom hook which exposes the context to its users. In the Provider, in addition to the children it renders, there is some conditional UI which renders when some state is set to true, this particular div is assigned a ref so that it can be referenced later in an effect (in my real application I mount a sign in widget to this div from a third party identity provider). What is weird is that when I run this example live, I can see the ref is set just fine, but when running the unit tests the ref's value is always null even when the state is set to true.