【发布时间】:2019-06-03 07:51:31
【问题描述】:
我试图在Moxios 库的单元测试中模拟Twilio 的外部端点。我也在使用SuperTest 库来提供测试的异常。
前端调用的我的内部端点是:
router.get('/twilio', async (req, res, next) => {
const result = await validatePhoneNumber(68848239, 'SG');
res.status(200).json(result);
});
而validatePhoneNumber 是一个函数,它通过Axios 调用外部端点,我试图模拟它而不是在测试期间调用实际端点:
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'
};
}
}
};
还有我的单元测试代码:
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 是模拟任何外部端点的正确方法,我会收到以下错误:
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,但仍然出现同样的错误。 感谢任何提示或帮助。
【问题讨论】:
-
你解决了吗?
-
@Vickycoder 是的,我找到了一种方法。我正在使用 axios-mock-adapter 库。 github.com/ctimmerm/axios-mock-adapter
标签: node.js unit-testing mocking moxios