简体   繁体   中英

How to mock imported function in ts-mock

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:

在此处输入图像描述

Service:

在此处输入图像描述

Test:

在此处输入图像描述

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

在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM