I have a component called SearchBox which is used inside SearchSection which is in turn used in MyComponent. SearchBox has a method that uses setTimeout().
SearchBox.tsx
import React from 'react';
export class SearchBox extends React.Component {
private timer: (ReturnType<typeof setTimeout> | null) = null;
public asyncmethod() {
if (this.timer !== null) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
doSomething();
}, 1000);
console.log('using original class method');
}
render() {
return (
<div>
...
...
{this.asyncmethod()}
...
...
</div>
);
}
}
SearchSection.tsx
import React from 'react';
import { SearchBox } from './SearchBox';
export class SearchSection extends React.Component {
render() {
return <SearchBox />;
}
}
MyComponent.tsx
import React from 'react';
import { SearchSection } from './SearchSection';
export class MyComponent extends React.component {
render() {
return <SearchSection />;
}
}
Now I want to test MyComponent using react-testing-library and I want to mock SearchBox with overridden class method that does not use setTimeout. I tried the following
testUtil.tsx
import { SearchBox } from './SearchBox';
class MockedSearchBox extends SearchBox {
public asyncMethod() {
doSomething();
console.log('using mocked class method');
}
}
MyComponent.test.tsx
import { MockedSearchBox } from './testUtil.tsx'
import { render } from '@testing-library/react';
import { MyComponent } from './MyComponent';
describe('My component', () => {
jest.mock('./SearchBox', () => {
return {
SearchBox: MockedSearchBox
}
});
test('that my component shows text', () => {
const { getByText } = render(<MyComponent />);
expext(getByText('Search mock text')).toBeDefined();
});
});
But this is not working. The original class method is being called even after writing above code. What am I doing wrong?