javascript - 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
}
解决方案
问题是你错过了传递 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();
推荐阅读
- php - 使用 route() 时 Laravel 刀片“未定义变量”错误
- javascript - 从表中获取数据并保存到数据库
- powershell - 如何在 Powershell 中执行相当于 $PROGPATH/program 的 bash?
- python - 如何在seaborn中替换x标签?
- angular - 路由器导航无法正常工作
- python - 如何在熊猫数据框中提取单个单词(不是包含它的更大单词)?
- kubernetes - 无法从 GKE 连接到 www.googleapis.com
- voip - 从包含 RFC 2833 RTP 事件的 RTP 流中保存音频
- c# - 如何使用 google api v3 将文件上传到(共享驱动器)?
- javascript - 如何将 AJAX 表单提交合并到 Bouncer.js 中?