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

标签 reactjs typescript enzyme

我想测试一个 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/

相关文章:

javascript - 在 enzyme / react 单元测试中模拟形式变化不会改变字段值

reactjs - 即使在 React 中选中,复选框也总是传递 false

javascript - 如何处理导致不需要的组件重新安装的 react History.Push()?

reactjs - React 在渲染之前在服务器中获取数据

javascript - typescript :对象到类

Typescript:根据参数不同的返回类型

reactjs - 使用 jest 进行 React 测试不支持 webpack 别名中的 moduleNameMapper

javascript - TypeScript 错误 - 类型 'Ticket[] | undefined' 不是数组类型

javascript - 解析字符串以提取JSON数组

javascript - onBlur 未在 Jest 测试用例、React App 中调用