我正在使用 Typescript 和 hooks 开发 React 应用程序,并且我正在尝试使用 Enzyme 和 Jest 来测试功能组件。我无法使用 jest.spyOn 来测试组件中的方法。jest.spyOn 方法无法正确解析并在悬停时显示以下消息
“类型''validateBeforeSave”' 的参数不能分配给类型''context' | “setState” | “forceUpdate” | “render” | “componentDidMount” | “shouldComponentUpdate” | “componentWillUnmount” | “componentDidCatch” | “ getSnapshotBeforeUpdate" | ... 还有 6 个 ... | "UNSAFE_componentWillUpdate"'.ts(2345)"
我试图将实例转换为“任何”-
const instance = wrapper.instance() as any;
Run Code Online (Sandbox Code Playgroud)
这当然在编译时忽略了这个问题,但随后测试会抛出一个运行时错误,该函数在组件上不存在。
无法监视 validateBeforeSave 属性,因为它不是函数;给出未定义
// Some function Component
const SomeComponent = (props: IMyComponentProps) => {
const { classes } = props;
// Component has state
const [count, setCount] = useState(0);
function validateBeforeSave(){ …Run Code Online (Sandbox Code Playgroud)