[英]How to test the function correctly
我有一个函数,它发出API
请求并以json
格式接收数据。
async function getDataAboutWeather(url) {
return await new Promise(resolve => {
request(url, (err, res, body) => {
if (err) {
throw new Error(err);
};
const info = JSON.parse(body);
resolve(info);
});
});
};
我想为这个函数编写一个测试。
describe('getDataAboutWeather function', () => {
it('The request should success', () => {
const link = 'http://ip.jsontest.com';
expect(getDataAboutWeather(link)).to.eql({});
});
});
如何验证我的功能是否正常工作?
从那时起我就收到了错误。
AssertionError: expected {} to deeply equal {}
getDataAboutWeather是一个异步函数,这意味着它返回一个Promise。 我会把测试改为:
it('The request should success', async () => {
const link = 'http://ip.jsontest.com';
expect(await getDataAboutWeather(link)).to.eql({});
});
要测试您的函数,您需要检查API JSON是否等于预期的JSON。 您可以使用以下功能。
_.isEqual(object, other);
有关此内容的更多信息: 如何确定两个JavaScript对象的相等性?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.