首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过Moxios在NodeJs中模拟外部端点

通过Moxios在NodeJs中模拟外部端点
EN

Stack Overflow用户
提问于 2019-06-03 15:51:31
回答 1查看 994关注 0票数 1

我正在尝试通过Moxios库在单元测试中模拟Twilio的一个外部端点。我还使用SuperTest库来提供测试的异常。

我的前端调用的内部终结点是:

代码语言:javascript
复制
router.get('/twilio', async (req, res, next) => {
   const result = await validatePhoneNumber(68848239, 'SG');
   res.status(200).json(result);
});

validatePhoneNumber是一个通过Axios调用外部端点的函数,我试图模拟这个函数,而不是在测试期间调用实际的端点:

代码语言:javascript
复制
const validatePhoneNumber = async (phone, code) => {
  const endpoint = `https://lookups.twilio.com/v1/PhoneNumbers/${phone}?CountryCode=${code}`;

  try {
    const { status } = await axios.get(endpoint, {
      auth: {
        'username': accountSid,
        'password': authToken
      }
    });

    console.log('twilio', phone, status);

    return {
      isValid: status === 200,
      input: phone
    };
  } catch (error) {
    const { response: { status } } = error;

    if (status === 404) {
      // The phone number does not exist or is invalid.
      return {
        input: phone,
        isValid: false
      };
    } else {
      // The service did not respond corrctly.
      return {
        input: phone,
        isValid: true,
        concerns: 'Not validated by twilio'
      };
    }
  }
};

和我的单元测试代码:

代码语言:javascript
复制
const assert = require('assert');
const request = require('supertest');
const app = require('../app');
const axios = require('axios');
const moxios = require('moxios');

describe('some-thing', () => {

    beforeEach(function () {
        moxios.install()
    })

    afterEach(function () {
        moxios.uninstall()
    })

    it('stub response for any matching request URL', async (done) => {

        // Match against an exact URL value
        moxios.stubRequest(/https:\/\/lookup.twilio.*/, {
            status: 200,
            responseText: { "isValid": true, "input": 68848239 }
        });

        request(app)
            .get('/twilio')
            .expect(200, { "isValid": true, "input": 68848239 }, done);
    });
});

如果在我的例子中,Moxios是模拟任何外部端点的正确方法,那么我将得到以下错误:

代码语言:javascript
复制
 Error: Timeout of 3000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (c:\Source\Samples\Twilio\myproject\test\twilio.test.js)

我将超时时间增加到10000,但仍然得到相同的错误。感谢任何提示或帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-26 22:02:40

我尝试了不同的方法,但我更喜欢使用axios-mock-adapter库来模拟任何通过Axios的请求。

示例:

代码语言:javascript
复制
const app = require('../app');
const axios = require('axios');
const request = require('supertest');
const MockAdapter = require('axios-mock-adapter');


describe('Valid phone number', () => {
    it('Should return data from response', (done) => {

        let mockAdapter = new MockAdapter(axios);

        mockAdapter.onGet(twilioEndpoint)
            .reply(200);

        request(app)
            .post('/api/validation')
            .set('Content-Type', 'application/json')
            .send(JSON.stringify(configuration))
            .expect(200, { "isValid": true, "input": "68848239" }, done);
    });
});

更多信息here

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56423137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档