Error: Uncaught [TypeError: Cannot read property 'state' of undefined

Error: Uncaught [TypeError: Cannot read property 'state' of undefined

我正在使用 React 测试库,但出现以下错误

Error: Uncaught [TypeError: Cannot read property 'state' of undefined" in the last line of my Test.tsx file.

如何查看我的所有组件是否都已渲染?我所说的组件是指:根据我的 Abc.tsx 文件的全名、标题、日期和其他内容?应该使用什么参数才能呈现 ShowPage 的所有组件? 因为如果我只在 render 中渲染 <Abc/> 它给了我 错误:

No overload matches this call. Overload 1 of 2, '(props: Readonly): ShowPage', gave the following error. Property 'post' is missing in type '{}' but required in type 'Readonly'. Overload 2 of 2, '(props: ShowProps, context?: any): ShowPage', gave the following error. Property 'post' is missing in type '{}' but required in type 'Readonly'.

Test.tsx



export default class Abc extends React.Component < ShowProps > {
  render() {
    ;

    return (
      <div className="Post-description">
          <Title>{post.title}</Title>
          <hr/>
          <Name>
          {`${post.fullName}|${dateToString(currentDateTime)}`}
          </Name>
          <br/>
          <Question>{post.body}</Question>
          <hr/>
          <AllComments/>
      </div>
    ) 
  }
}

明白了。 this.state 应该在您的测试中未定义,因为测试用例不是反应的常规组件。 此外,您应该在测试时模拟 post 并将其作为道具传递到 ShowPage 组件中。然后你就可以走了。而且我不认为你需要 Router 和 Route 作为包装器,只要你不使用来自路由器的 API,即历史对象。

const post = {
  fullName: 'Muhammad Ali',
  title: 'Post title',
  body: 'Post body',
  updatedAt: '1/30/2020',
}
const {getByPlaceholderText, queryByTestId} = render(
   <ShowPage post={post}/>
);