当isLoading状态更改组件时,我想构建测试。 我知道在类组件中可以通过setState和酶来实现,但是我想知道如何在这里实现。
const Spacex = () => {
const [open, setOpen] = useState(false);
const [upComingLaunches, setUpComingLaunches] = useState([]);
const [Launchpad, setLaunchpad] = useState([])
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
let tempData;
SpaceXNextLaunche()
.then(data => {
setUpComingLaunches(data);
tempData = data;
return LaunchPad()
}).then(dataLaunch => {
const foundTheLaunch = dataLaunch.docs.filter((Launch, index) => {
return tempData.id === Launch.id
});
setLaunchpad(foundTheLaunch);
setIsLoading(false);
})
}, [])
if (isLoading) return <LoadingComp />
return (
<div>
<div className="upcoming-launches">
<h1 className={styles.title}>upcoming launche</h1>
<div className={styles.CountDownWarrper}>
{Object.keys(upComingLaunches).length > 0 ?
<Card className={styles.CountDownCard}>
<div className={styles.MissionName}>{upComingLaunches.name}</div>
<div className={styles.gridBadges}>
<div className={styles.CountDown}><CountDownClock upComingLaunches={upComingLaunches} /></div>
<div className={styles.badgeFlex}><img className={styles.badge} src={upComingLaunches.links["patch"]["small"]} alt="mission patch" /></div>
</div>
<GoogleMap
mapVisiblity={(e) => setOpen(!open)}
open={open}
placeName={Launchpad[0].launchpad.full_name} />
</Card>
: null}
</div>
</div>
</div>
)
}
export default Spacex;
答案 0 :(得分:2)
测试功能组件的正确方法是测试实际功能的行为,而不是其实现。在您的情况下,这将模拟SpaceXLaunche()
以在超时后返回其数据,例如:
function SpaceXLauncheMock() {
return new Promise(resolve => {
setTimeout(resolve(data), 1500);
});
}
const SpaceXLaunche = jest.spyOn(SpaceXLaunche.prototype, 'SpaceXLaunche')
.mockImplementation(SpaceXLauncheMock);
然后,您将测试isLoading
的结果-最初LoadingComp
的存在或不存在,并在超时后再次测试(不要忘记将done
设置为{测试用例的参数):
expect(component.contains(<LoadingComp />)).toBe(true);
setTimeout(() => {
expect(component.contains(<LoadingComp />)).toBe(false);
done();
}, 2000);