Reputation: 683
When writing React app, I have one class that has several static methods, that every executes axios request and return Promise.
My component uses the class to fetch data and render them. Now I'd like to mock the whole class, not one or two methods, because all of them are in use.
Sample ServerManager.ts
:
export class ServerManager {
static getUsers(): Promise<User[]> {
return Axios.get(userPath)
.then((response: Promise<AxiosResponse>): User[] => response.data);
}
// lot of similar methods
}
Sample component:
export function SomeComponent() {
const [users, setUsers] = React.useState<User[]>([]);
Promise.all([
ServerManager.getUsers().then(setUsers), //...
]).then();
return <div>
{users.length ? <div>{users.length}</div>}
</div>;
}
I'd like to fully test this component not changing its logic. Best solution would be to create MockServerManager
, that imported would replace the original, but doing so makes ServerManager
not defined.
EDIT:
I have created such a mock inside the __mocks__
directory:
export class MockServerManager {
static getUsers(): Promise<User[]> {
return Promise.resolve([user]);
}
// ... more methods
}
jest.mock('../../src/ServerManager', () => ({
ServerManager: MockServerManager
}));
Bot now... the promises never ends. The test is waiting for the promise unless it timeout.
Sample test:
describe('SomeComponent', (): void => {
it('renders', async (): Promise<void> => {
// when
const wrapper: ShallowWrapper = shallow(<SomeComponent/>);
await ServerManager.getUsers().then(() => {
// then
expect(wrapper).toMatchSnapshot();
});
});
});
Upvotes: 0
Views: 443
Reputation: 412
Try importing ServerManager in MockServerManager component because it usually shows this error when we're not importing the component into our base component i.e MockServerManager or it's because you're using props in that component and not declaring the property of props.
Upvotes: 1