Jas*_* FB 6 reactjs jestjs react-testing-library react-ref
这是一个关于在规范中使用 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());
})
Run Code Online (Sandbox Code Playgroud)
// 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
Run Code Online (Sandbox Code Playgroud)
发生的情况是这段代码在浏览器中对我来说工作得很好。当在 setTimeout 中调用该函数时, this.abc_logo_inner_ref 被正确附加到由LogoContainer
我可以检查它(在我的浏览器中使用debugger
),它看起来像这样:
但是,当从我的 Jest 规范(上面)运行时,即使我在测试本身中渲染组件(见上文),引用也不会填充,当我 console.log 测试中的输出时,我得到了这些 Ref 对象
{current: null}
Run Code Online (Sandbox Code Playgroud)
我的预期结果是一个正确填充的 Ref 对象,其中current
element 指向 React 在渲染此组件时创建的 DOM 元素。
归档时间: |
|
查看次数: |
1123 次 |
最近记录: |