输入react-test-renderer单元测试:componentWillUnmount clearTimeoutthistimer;
import React from 'react'; import { create } from 'react-test-renderer';
class MyComponent extends React.Component { constructor(props) { super(props); this.timer = null; }
componentDidMount() { this.timer = setTimeout(() => { console.log('Timer has expired'); }, 1000); }
componentWillUnmount() { clearTimeout(this.timer); }
render() { return
My Component
;
}
}
describe('MyComponent', () => {
test('should clear timeout on unmount', () => {
const component = create(
// Check if timer is set before unmounting
expect(instance.timer).not.toBeNull();
// Unmount component
component.unmount();
// Check if timer is cleared after unmounting
expect(instance.timer).toBeNull();
}); });
原文地址: https://www.cveoy.top/t/topic/hJk4 著作权归作者所有。请勿转载和采集!