React 测试库 - TypeError 修剪不是使用渲染时的功能 [英] React Testing Library - TypeError trim is not a function when using render
问题描述
我正在使用 Jest + React 测试库创建一个简单的测试.但是,当我尝试渲染它时,它会在代码中崩溃.这很奇怪,因为应用程序运行流畅.似乎道具未定义或为空.
测试文件:
test('renders learn react link', () => {const { 容器 } = 渲染(<App/>);});
应用:
从'react'导入React;从'./logo.svg'导入标志;导入'./App.css';从'./Child'导入{子};功能应用(){返回 (<header className="App-header"><p>编辑 <code>src/App.tsx</code>并保存以重新加载.</p><孩子/>);}导出默认应用程序;
应用的子级:
import * as React from "react";导出类 Child 扩展 React.Component{const testString = this.props.testVariable.trim();使成为(){返回(<div>只是一个简单的div</div>)}}接口道具{测试字符串:字符串}
解决方案 问题是你错过了将 testVariable
的属性传递给 <Child/>
因此,如果您将道具标记为可选,那么您应该在进行任何操作之前检查它.此外,通过在上述类中定义变量,您的代码看起来是错误的.
无论如何,您可以定义默认属性或空检查属性:
export class Child extends React.Component{//设置默认道具静态默认道具 = {测试变量:"}使成为() {const testString = this.props.testVariable.trim();返回 (<div>只是一个简单的div</div>)}}
或空检查:
const testString = this.props.testVariable?.trim();
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
}
解决方案 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();
这篇关于React 测试库 - TypeError 修剪不是使用渲染时的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文