无法在笑话中从react组件触发回调函数



我正试图为我用React制作的一个简单的天气web应用程序编写一些笑话测试。当我运行测试时,它会创建组件的快照,看起来不错,但当我试图触发点击事件时,我会得到一个类型错误:

TypeError: tree.props.handleClick is not a function

我用笑话文档编写了这个测试,我认为这就是你触发点击事件的方式。我是否没有正确引用单击功能?我是写测试的新手,所以欢迎任何关于为React with jot写测试的信息!

反应代码

import React from "react"
import { useEffect, useState } from 'react'
// import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
const CityEntry = ({ weatherDatum, deleteLocation }) => {
const capitalizeFirstLetter = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
const handleClick= () => {
deleteLocation(weatherDatum.id)
}
return (
<div className="city">
<p className="location flex-item">{capitalizeFirstLetter(weatherDatum.location)} </p>
<p className="temp flex-item">{weatherDatum.temperature}  &#x2109;</p>
<p className="feels-like flex-item">Feels like: {weatherDatum.feelsLike}</p>
<p className="description flex-item">{capitalizeFirstLetter(weatherDatum.description)}</p>
<p><img className="icon flex-item" src={`https://openweathermap.org/img/w/${weatherDatum.icon}.png`}></img></p>
<button className="delete" onClick={handleClick}>Delete</button>
</div>
)
}
export default CityEntry;

Jest测试代码

import renderer from 'react-test-renderer';
import CityEntry from '../src/Components/CityEntry.js'
it('deletes a city entry when clicked', () => {
const component = renderer.create(
<CityEntry weatherDatum={{ id: '', lat: '', lon: '', location: '', temperature: '', feelsLike: '', description: '', icon: '' }} />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot()
renderer.act(() => {
tree.props.handleClick()
});
tree = component.toJSON();
expect(tree).toMatchSnapshot()
})

创建的小丑快照

exports[`deletes a city entry when clicked 1`] = `
<div
className="city"
>
<p
className="location flex-item"
>

</p>
<p
className="temp flex-item"
>
℉
</p>
<p
className="feels-like flex-item"
>
Feels like: 
</p>
<p
className="description flex-item"
/>
<p>
<img
className="icon flex-item"
src="https://openweathermap.org/img/w/.png"
/>
</p>
<button
className="delete"
onClick={[Function]}
>
Delete
</button>
</div>
`;

组件的JSON表示仅用于断言。不能使用它来操纵组件的状态。JSON不能包含函数,它只是静态数据。

要模拟按钮单击,您需要使用TestInstance上可用的方法。

最好触发按钮上的实际单击处理程序,以便调用其他deleteLocation函数。

import renderer from 'react-test-renderer';
import CityEntry from '../src/Components/CityEntry.js'
it('deletes a city entry when clicked', () => {
const component = renderer.create(
<CityEntry weatherDatum={{ id: '', lat: '', lon: '', location: '', temperature: '', feelsLike: '', description: '', icon: '' }} />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot()
renderer.act(() => {
component.root.findByType('button').props.onClick();
});
tree = component.toJSON();
expect(tree).toMatchSnapshot()
})

顺便说一下,您可以考虑使用React测试库。react-test-rendererAPI的水平非常低,大多数人觉得这更符合人体工程学。我看到的最近创建的大多数React测试套件都是这样的。

从哲学上讲,它也阻止了你要做的事情,即抓住道具并直接操纵它们。这是因为好的测试只会像真正的用户一样与元素交互。

最新更新