React Testing Library - TypeError trim is not a function when using render

笑着哭i 提交于 2021-02-08 12:11:58

问题


I am creating a simple test with Jest + React Testing Library. However, when I try to render my it crashes in de code. This is strange because the application does run smoothly. It seems like the props are undefined or empty.

Test file:

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

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;

Child of 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
}


回答1:


The issue is here you have missed to pass the property of testVariable to <Child /> so if you mark the prop is optional, then you should check it before proceed anything. Additionally, you code looks wrong by defining a variable inside a class like above.

Anyway you can either define your default property or null check the property:

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>
        )
    }
}

Or null checking:

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


来源:https://stackoverflow.com/questions/65811875/react-testing-library-typeerror-trim-is-not-a-function-when-using-render

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!