【问题标题】:React Testing Library - TypeError trim is not a function when using renderReact 测试库 - 使用渲染时 TypeError 修剪不是函数
【发布时间】:2021-01-20 14:48:11
【问题描述】:

我正在使用 Jest + React 测试库创建一个简单的测试。但是,当我尝试渲染它时,它会在解码代码中崩溃。这很奇怪,因为应用程序运行平稳。似乎道具未定义或为空。

测试文件:

test('renders learn react link', () => {
  const { container } = render(<App />);
});

应用:

import React from 'react';
import logo from './logo.svg';
import './App.css';
import { Child} from './Child';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
          <Child/>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

应用之子:

import * as React from "react";

export class Child extends React.Component<TheProps>{
     const testString = this.props.testVariable.trim();

     render(){
            return(
                <div>Just a simple div</div>
            )
        }
}

interface TheProps{
     testString : string
}

【问题讨论】:

    标签: javascript react-testing-library


    【解决方案1】:

    这里的问题是你错过了将testVariable 的属性传递给&lt;Child /&gt; 所以如果你标记这个属性是可选的,那么你应该在继续之前检查它。此外,通过在上面的类中定义变量,您的代码看起来是错误的。

    无论如何,您都可以定义默认属性或对属性进行空检查:

    export class Child extends React.Component<TheProps> {
        // set default props
        static defaultProps = {
            testVariable: ""
        }
    
        render() {
            const testString = this.props.testVariable.trim();
            return (
                <div>Just a simple div</div>
            )
        }
    }
    

    或空检查:

    const testString = this.props.testVariable?.trim();
    

    【讨论】:

    • 我也推荐使用功能组件,它比使用类更容易,然后你也可以利用钩子。
    • 但是如果我不想进行空检查,我应该怎么做呢?然后我应该在我的测试中传递参数吗?我会记住功能组件:)。
    • 因为现在我们确定 testVariable 在运行测试时为空。但这不是最佳做法对吧?
    • 您必须确定是否需要哪些道具。如果需要,您必须提供。否则,您只需提供默认值或空值检查
    • 嗯,好吧,我怎样才能在我的测试中将这些道具发送给孩子?因为我正在渲染 。会是这样吗? :
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2020-03-12
    • 2018-07-08
    • 2023-02-10
    • 2021-04-28
    • 2020-05-30
    • 1970-01-01
    相关资源
    最近更新 更多