首页 > 解决方案 > React 测试库 - 使用渲染时 TypeError 修剪不是函数

问题描述

我正在使用 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
}

标签: javascriptreact-testing-library

解决方案


问题是你错过了传递 to 的属性,testVariable所以<Child />如果你标记道具是可选的,那么你应该在继续之前检查它。此外,通过在上面的类中定义变量,您的代码看起来是错误的。

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

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();

推荐阅读