【发布时间】:2019-06-29 15:55:58
【问题描述】:
为 React 组件编写测试时,通常会在 beforeEach 块中初始化组件包装器(例如 wrapper),然后在后续测试中使用它。然而,为了做到这一点,你必须在赋值之前声明 wrapper 并给它一个明确的类型,否则 TypeScript 会抱怨缺少类型。不幸的是,这种类型的计算/写出可能非常复杂。
在下面的示例中,有什么方法可以“延迟”TypeScript 抱怨下面示例中缺少wrapper 的类型,并让它从分配wrapper 的位置推断类型?
或者,是否有更好的模式来布置变量以使输入更容易?
describe('suite', () => {
// will trigger a no implicit any error
// but it's quite complex to manually write out the type here
let wrapper;
beforeEach(() => {
const SomeElement = complexFunctionWithGenericParams(someParam);
// ideally, we want TS to infer the type of `wrapper` from this statement
wrapper = mountComponent(<SomeElement />);
})
it('does something', () => {
expect(wrapper.state.someField).toBe(5);
}
}
【问题讨论】:
标签: reactjs typescript enzyme