简体   繁体   中英

How to stub a module with sinon?

I need to stub hubspot module in order to test my apis.

I need to test this code:

const createCompany = async company => {
  const hubspotClient = new hubspot.Client({
    apiKey: HUBSPOT_KEY
  });

  //stuff
  const companyObj = {
    properties: {
      //my properties
    }
  };

  return await hubspotClient.crm.companies.basicApi.create(companyObj);
};

Here They show how to stub a class and access a method through its instance, but in my case I have multiple properties like .crm.companies.basicApi.create() .

I tried doing:

getDataStub = sinon
  .stub(hubspot.Client.prototype, 'crm.companies.BasicApi.create')
  .resolves(fakeResponse);

But it doesn't work and it says TypeError: Cannot stub non-existent own property crm.companies.basicApi.create .

Do you have any hint on how to fix that?

You can create a HubspotClient instance outside of createCompany . Then export that instance so in the test file you could stub methods of it.

const hubspotClient = new hubspot.Client({
    apiKey: HUBSPOT_KEY
  });
// ...
const createCompany = async company => {
    // ...
    return await hubspotClient.crm.companies.basicApi.create(companyObj);
}
// ...
stub(hubspotClient.crm.companies.basicApi, 'create');

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