gpt4 book ai didi

reactjs - 使用 Enzyme 测试 React 组件。 typescript 找不到实例方法

转载 作者:搜寻专家 更新时间:2023-10-30 20:31:34 25 4
gpt4 key购买 nike

我想测试一个 React 类组件。

假设我的类中有一个方法可以根据当前状态和 Prop 计算一些东西。

import Component from './Component'

const wrapper = enzyme.shallow(<Component {...props} />);

it('does something', () => {
expect(wrapper.instance().someInstanceMethod(input)).toBe(true);
});

typescript 说 Property 'someInstanceMethod' is not defined on type Component<any, any> .我如何告诉 Typscript 我的类看起来如何以及它有哪些方法?

有这方面的好例子吗?

最佳答案

可以在shallow调用中设置组件类型。这是一些样板文件,但它使事情类型安全。好处是包装器是类型安全的,而不仅仅是您提取的实例。

import Component from './Component'

// Wrapper will know the type of the component.
const wrapper = enzyme.shallow<Component>(<Component {...props} />);

it('does something', () => {
expect(wrapper.instance().someInstanceMethod(input)).toBe(true);
// You can also get the state from the wrapper.
expect(wrapper.state().someComponentState).toBeTruthy();
});

关于reactjs - 使用 Enzyme 测试 React 组件。 typescript 找不到实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44625581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com