lkaric / nestjs-twilio

Injectable Twilio client for Nestjs.
https://www.npmjs.com/package/nestjs-twilio
MIT License
43 stars 11 forks source link

Mock twilio module #16

Closed qamalyanaren closed 3 years ago

qamalyanaren commented 3 years ago

How can I mock twillo module for testing?

rcaceiro commented 3 years ago

How can I mock twillo module for testing?

The same here

lkaric commented 3 years ago

@rcaceiro @qamalyanaren We had the same question about the testing here #10, if you need a more concrete example, please provide me with context so that I can help you

qamalyanaren commented 3 years ago

@rejvban I want to mock this function in the service https://user-images.githubusercontent.com/18355408/128837763-cdcc6a55-6aef-4ebf-91f4-f1a4ac0c920e.png

lkaric commented 3 years ago

@qamalyanaren Since this has become a rather reacurring question, I'm going to try to explain how it's tested in the library itself. But I think that this is more of a general testing question. File for reference!

Since I don't see the whole context, I'm going to go through the example with the assumption that you only want to test the twilio module https://github.com/rejvban/nestjs-twilio/blob/e846f88fd330b0531e2ed0414b77717ed4af6fbc/lib/__tests__/twilio.decorators.test.ts#L27-L37

First I created the mock injectable service containing the injected twilio client and then provided it to the testing module which is properly initializing the TwilioModule in order for the service to work. You should also be able to use your written service, just be cautious when initializing the module.

Then, from the test module, you can access the appropriate service, in this case, its client (TwilioClient) and a whole bunch of methods that that client provides.

https://github.com/rejvban/nestjs-twilio/blob/e846f88fd330b0531e2ed0414b77717ed4af6fbc/lib/__tests__/twilio.decorators.test.ts#L47-L57

I can vouch that this approach works, considering that we have automated tests that send an SMS to my personal phone each time the test passes each time that there's a change on the master branch.

Also sorry for the late reply, been really busy at work, hope I could help!

stale[bot] commented 3 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

rained23 commented 2 years ago

hi, can I know how can I mock the injected service ?, I don't want it to call the real client, I want to mock the injected dependency, with the above approach I cant override the function from the client. When I execute my test, I am getting this error

The requested resource /2010-04-01/Accounts/ACSid/Messages.json was not found

I tried to mock the client using the following

{ 
  provide: InjectableService, 
  useValue: { 
    client: { 
      messages: { create:  jest.fn().mockResolvedValue(true) } 
    } 
}

But still receiving the above error.