【发布时间】:2019-10-23 01:32:04
【问题描述】:
我一直在尝试的是在 .tsx 文件(即 Typescript)中使用 Jest(酶)测试反应组件,遵循 this post 和 this 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'.”
(奇怪的是,MyComponent 在find() 内)没有给出任何警告)
如果我替换
let instance = wrapper.find(MyComponent).instance() as MyComponent;
与
wrapper.find(MyComponent).instance().getFoo = jest.fn()
...,它会导致不同的警告消息,说"Property 'getFoo' does not exist on type 'Component<any, any, any>'"
如果我输入 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