简体   繁体   English

如何使用 sinon 存根模块?

[英]How to stub a module with sinon?

I need to stub hubspot module in order to test my apis.我需要存根 hubspot 模块以测试我的 api。

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() . 在这里,他们展示了如何存根类并通过其实例访问方法,但在我的情况下,我有多个属性,例如.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 .但它不起作用,它说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 .您可以在createCompany之外创建一个 HubspotClient 实例。 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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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