这是关于在规范中使用 React refs 的问题。具体来说,我在浏览器中看到的行为与在测试中运行时看到的行为不同。
// app_container.test.js
import React from 'react'
import ReactDOM from 'react-dom'
import AppContainer from "./app_container"
import { render, fireEvent, waitForElement, cleanup, wait } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import axiosMock from 'axios'
import { useAsync } from "react-use"
afterEach(cleanup);
test("renders", () => {
const { getByTestId } = render(<AppContainer />);
expect(getByTestId("app-container")).toHaveClass("app-container");
});
test("when mounted, it loads the rings", async () => {
jest.setTimeout(15000);
const { getByTestId } = render(<AppContainer />);
const container = getByTestId('app-container')
await wait(() => expect(getByText("Abc")).toBeInTheDocument());
})
// app_container.js 代码
import React from 'react'
import Ring from "./ring";
import LogoContainer from './logo_container'
const rings_data = [
{ key: 2,
name: "Abc",
blurb: "Lorem ipsum."
}
]
class AppContainer extends React.Component {
state = {
ringsLoaded: false,
}
constructor(props) {
super()
this.abc_logo_inner_ref = React.createRef()
this.rings = []
}
componentDidMount() {
setTimeout(() => {
console.log("the timeout has invoked the function ")
this.rings = rings_data
console.log("this.abc_logo_inner_ref.current= ", this.abc_logo_inner_ref)
// expecting the ref to be populated with {current: (html object)} but instead it is
// {current: null}
},1000)
}
render () {
const effect = this.effect
return (
<div data-testid="app-container" style={{height: "100vh"}}
className="app-container">
<LogoContainer ref={this.abc_logo_inner_ref}
/>
{ringsLoaded ?
<div>
{this.rings.map((ele, i) =>
<Ring
ref={this.marbles_refs_array[i]}
/>)
}
</div>
: ''}
</div>
)
}
}
export default AppContainer
发生的事情是这段代码在浏览器中对我来说很好。在 setTimeout 中调用该函数时,this.abc_logo_inner_ref 正确附加到由LogoContainer
我可以检查它(在我的浏览器中使用debugger
),它看起来像这样:
但是,当从我的 Jest 规范(上)运行时,不会填充 ref,即使我在测试本身中渲染组件(见上文),当我 console.log 在我的测试中输出这些 Ref 对象时
{current: null}
我的预期结果是一个正确填充的 Ref 对象,其中current
元素指向由 React 在呈现此组件时创建的 DOM 元素。