How to mock imported function in ts-mock

1.1k Views Asked by At

I'm new to typescript and playing around with aws-lambda.

I'm trying to unit test my handler so I need to mock the service class so it will return some mocked data

Below I have a simple function that gets the data from the domain service.

Handler:

enter image description here

Service:

enter image description here

Test:

enter image description here

When I run the test using npx mocha, it shows:

enter image description here

1

There are 1 best solutions below

0
On

It looks like you have a function call where you need to pass a reference to the mock's function:

mockito.when(mockedService.getAllDomain()).thenResolve([]);

should be:

mockito.when(mockedService.getAllDomain).thenResolve([]);
                                       ^ Without the function call brackets ()

As an aside, it's more idiomatic with mocha to use something like sinon for mocking. I mention this because I'm not sure if the library you've found is suitable for mocking dependencies - I think you will need to refactor your code to allow injecting the mock created by ts-mockito.