【问题标题】:Typescript: Type of a React component cannot be found in a test fileTypescript:在测试文件中找不到 React 组件的类型
【发布时间】:2019-10-23 01:32:04
【问题描述】:

我一直在尝试的是在 .tsx 文件(即 Typescript)中使用 Jest(酶)测试反应组件,遵循 this postthis post

这是我的代码的 sn-p。

编辑:谢谢@WillJenkins!我在阅读了您的建议后更新了这个sn-p)

describe('MyComponent', ()=>{
  const mockStore = createMockStore([thunk]);
  let store = mockStore({});      

  it('should render ChildComponent if getFoo is true', () => {
    let wrapper = mount(
        <Provider store={store}>
            <MyComponent />
        </Provider>
    );

    let instance = wrapper.find(MyComponent).instance() as MyComponent;
    // "MyComponent" shows a warning message,
    // saying "Cannot find name 'MyComponent'."

    instance().getFoo = jest.fn();
    instance().getFoo.mockImplementation(() => true);

    instance.update();

    expect(instance.contains(<ChildComponent />)).toBe(true);
  });
});

由于某种原因,as 关键字后面的MyComponent 在我用作wrapper.instance() 的类型时找不到。

如果我将鼠标悬停在它上面,它会显示“Cannot find name 'MyComponent'.

(奇怪的是,MyComponentfind() 内)没有给出任何警告)

如果我替换

let instance = wrapper.find(MyComponent).instance() as MyComponent;

wrapper.find(MyComponent).instance().getFoo = jest.fn()

...,它会导致不同的警告消息,说"Property 'getFoo' does not exist on type 'Component&lt;any, any, any&gt;'"

如果我输入 any 而不是 MyComponent,它不会显示任何警告,但测试本身会导致类型错误 (instance.update() is not a function)

instance() 的正确类型是什么?我在 Jest and Enzyme 的文档中找不到任何线索。

我们将不胜感激。

【问题讨论】:

  • 您是否正在从.jsx 文件中导入组件,例如测试文件顶部的import Component from './Component'?在您的情况下,它将是 import MyComponent from './MyComponent' 其中 ./MyComponent 应该是您的 MyComponent.jsx 文件的相对路径(不要在导入时包含扩展名)
  • @PedroMaiaCosta,这个组件被导入为import { MyComponent } from '../MyComponent'。我确定路径是正确的,因为将其更改为其他任何内容都会发出警告消息,这是由 TypeScript 引起的。

标签: reactjs typescript jestjs enzyme


【解决方案1】:

您的包装器不是&lt;MyComponent&gt;,而是&lt;Provider&gt;

您需要使用find 在已挂载的树中找到您的MyComponent

let instance = wrapper.find(MyComponent).instance();

【讨论】:

  • 感谢您的评论!然而不幸的是,使用 (let instance = wrapper.find(MyComponent).instance()) 行并没有解决问题。 TypeScript 现在抱怨 Property 'getFoo' does not exist on type 'Component&lt;any, any, any&gt;' 就在这行之后。
猜你喜欢
  • 2019-11-18
  • 1970-01-01
  • 1970-01-01
  • 2017-10-19
  • 1970-01-01
  • 2017-02-16
  • 2016-08-30
  • 2019-12-13
  • 2017-06-03
相关资源
最近更新 更多