Skip to content
Advertisement

Jest – mock a named class-export in typescript

I have a node module which exports a few classes, one of which is Client, which I use to create a client (having a few APIs as methods).

I’m trying to test my module which uses this node module as a dependency using Jest. However, I’ve been unable to successfully mock the one method (say search()) in the Client class.

Here is my spec for myModule:

JavaScript

This, however, doesn’t create a mock at all and triggers a nock error since the search API tries to connect to the url (given through params).

I’ve also tried mocking the Client class like the following. While successfully creating a mock for the Client class and also the search API (verified that search() is also mocked through console logs), it gives me an error while I try to check if search() has been called.

JavaScript

I’m not sure what I’m doing wrong. Thank you in advance.

Advertisement

Answer

Mocking whole module

Try moving jest.mock to the top of file

JavaScript

Mocking only Client

Create search constant and track it.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement