[英]React Testing Library - TypeError trim is not a function when using render
I am creating a simple test with Jest + React Testing Library.我正在使用 Jest + React 测试库创建一个简单的测试。 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
}
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.问题是你错过了将
testVariable
的属性传递给<Child />
所以如果你标记道具是可选的,那么你应该在继续之前检查它。 Additionally, you code looks wrong by defining a variable inside a class like above.此外,通过在 class 中定义变量,您的代码看起来是错误的,就像上面一样。
Anyway you can either define your default property or null check the property:无论如何,您可以定义默认属性或 null 检查属性:
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:或 null 检查:
const testString = this.props.testVariable?.trim();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.