微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 twilio-node 包中模拟 Twilio 客户端

如何解决从 twilio-node 包中模拟 Twilio 客户端

我目前使用 Twilio Node Helper Library 执行各种 API 调用,无论是创建助手/服务、列出它们、删除它们以及上传任务、示例、字段以创建聊天机器人时的各种其他事情在 Twilio Autopilot 上。

其中一些功能的示例包括

async function createAssistant(name,client){
    var assistantUid = ""
    await client.autopilot.assistants
                .create({
                    friendlyName: name,uniqueName: name
                    })
                .then(assistant => assistantUid = assistant.sid);
    return assistantUid 
}

 async function getAccount(client){
    var valid = true
    try {
      await client.api.accounts.list()
    } catch (e) {
      valid = false
    }

    return valid
  }


async function connectToTwilio(twilioAccountSid,twilioAuthToken) {
  try{
    var client = twilio(twilioAccountSid,twilioAuthToken);
  } catch (e){
    throw new TwilioRequestError(e)
  }

  var valid = await getAccount(client)
  if(valid && client._httpClient.lastResponse.statusCode === 200){
    return client
  } else{
    throw new Error("Invalid Twilio Credentials")
  }
  
}

其中 client 是从 require("twilio")(twilioAccountSid,twilioAuthToken) 返回的客户端对象。

我想知道模拟这个 API 的最佳方式是什么,让我模拟创建助手,返回他们的 uniqueNames 等。

我想知道我可以定义一些像

class TwilioTestClient{

   constructor(sid,token){
        this.sid = sid
        this.token = token
        this.assistants = TwilioAssistant()
        this.services = TwilioServices()
   }
}

其中 TwilioAssitant 和 TwilioServices 将是附加类。

任何帮助将不胜感激!

解决方法

我在嘲笑 Twilio 上挣扎了很长时间。事实上,我之前设计了我的应用程序,以便我可以模拟围绕 Twilio 节点助手的包装器,以避免模拟实际的库。但是最近对架构的更改意味着这不再是一种选择。今天早上我终于模拟了 Twilio 节点助手库的工作。我不熟悉您使用的 Twilio 库的各个部分,但我希望这里的示例对您有所帮助。

我们有一个功能可以检查电话号码是否是手机号码,称之为 isMobile.js

const Twilio = require("twilio");

const isMobile = async (num) => {
    const TwilioClient = new Twilio(process.env.TWILIO_SID,process.env.TWILIO_AUTH_TOKEN);

    try {
        const twilioResponse = await TwilioClient.lookups.v1
            .phoneNumbers(num)
            .fetch({ type: "carrier",mobile_country_code: "carrier" });

        const { carrier: { type } = {} } = twilioResponse;
        return type === "mobile";
    } catch (e) {
        return false;
    }
};

module.exports = isMobile;


然后在 __mocks__/twilio.js

中为 Twilio 构建一个模拟
const mockLookupClient = {
    v1: { phoneNumbers: () => ({ fetch: jest.fn(() => {}) }) }
};

module.exports = class Twilio {
    constructor(sid,token) {
        this.lookups = mockLookupClient;
    }
};

在测试文件 isMobile.test.js

jest.mock("twilio");

const Twilio = require("twilio");

const isMobile = require("./isMobile");

const mockFetch = jest.fn();
const mockPhoneNumbers = jest.fn(() => ({
    fetch: mockFetch
}));

describe("isMobile",() => {
    const TwilioClient = new Twilio(process.env.TWILIO_SID,process.env.TWILIO_AUTH_TOKEN);
    const lookupClient = TwilioClient.lookups.v1;
    lookupClient.phoneNumbers = mockPhoneNumbers;

    beforeEach(() => {
        mockFetch.mockReset();
    });

    test("is a function",() => {
        expect(typeof isMobile).toBe("function");
    });

    test("returns true for valid mobile number",async () => {
        const validMobile = "+14037007492";

        mockFetch.mockReturnValueOnce({
            carrier: { type: "mobile",mobile_country_code: 302 },// eslint-disable-line camelcase
            phoneNumber: validMobile
        });
        expect(await isMobile(validMobile)).toBe(true);
    });

    test("returns false for non-mobile number",async () => {
        const invalidMobile = "+14035470770";

        mockFetch.mockReturnValueOnce({
            carrier: { type: "not-mobile",mobile_country_code: null },// eslint-disable-line camelcase
            phoneNumber: invalidMobile
        });

        expect(await isMobile(invalidMobile)).toBe(false);
    });
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。