【问题标题】:Mock modules that has a class and other attributes具有类和其他属性的模拟模块
【发布时间】:2018-12-20 06:59:59
【问题描述】:

我正在尝试模拟 twilio 模块,但这很痛苦。我是 Jest 的新手,我已经阅读过文档,但不清楚我应该如何模拟一个类和一个类型。

这是我要模拟的代码:

const Twilio = require('twilio')
const client = new Twilio('sid', 'auth')
const response = new Twilio.twiml.VoiceResponse()

构造函数new Twilio的部分做得很好:

jest.mock('twilio', () => class {
  constructor (accountSid, authToken) {
    this.conferences = {
      list () {
        return mockTwilioListConferences()
      }
    }
  }
})

但是我如何模拟 new Twilio.twiml.VoiceResponse() 部分?

【问题讨论】:

  • 为什么需要模拟VoiceResponse?它不发出外部请求,只是为您生成 XML。
  • @philnash 因为我已经模拟了整个模块 twilio。我不知道如何从模块中模拟一个函数。

标签: unit-testing twilio jestjs


【解决方案1】:

这里是 Twilio 开发者宣传员。

免责声明,我没有尝试过,但我认为这是有效的。

Twilio 类上的 twiml 属性就是这样一个属性。在您的模拟中,您会立即返回一个新的匿名类,但如果您在返回之前将该属性添加到该类本身,您应该会发现它是您模拟的一部分。

例如:

jest.mock('twilio', () => {
  const mockClass = class {
    constructor (accountSid, authToken) {
      this.conferences = {
        list () {
          return mockTwilioListConferences()
        }
      }
    }
  }
  mockClass.twiml = {
    // complete your mock implementation here
  }
  return mockClass;
);

让我知道这是否有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2021-07-15
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多