What I've been trying is to test a react component with Jest (Enzyme) in a .tsx
file (i.e. Typescript), following this post and this post.
Here is a snippet of my code.
(EDIT: Thank you @WillJenkins! I updated this snippet after I read your advice)
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);
});
});
For some reason, MyComponent
after the as
keyword can't be found when I use it as the type of wrapper.instance()
.
If I hover over it, it says "Cannot find name 'MyComponent'.
"
(Strangely, MyComponent
within find()
) doesn't give any warning)
If I replace
let instance = wrapper.find(MyComponent).instance() as MyComponent;
with
wrapper.find(MyComponent).instance().getFoo = jest.fn()
..., it results in a different warning message, saying that "Property 'getFoo' does not exist on type 'Component<any, any, any>'"
If I put any
instead of MyComponent
, it doesn't show any warning but the test itself results in an type error (instance.update() is not a function
)
What is the correct type for instance()
? I can't find any clue in Jest and Enzyme's doc.
Any advice will be appreciated.