【问题标题】:How to test the function correctly如何正确测试功能
【发布时间】:2020-01-05 06:35:31
【问题描述】:

我有一个函数可以发出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 {}

【问题讨论】:

标签: javascript node.js testing


【解决方案1】:

getDataAboutWeather 是一个异步函数,这意味着它返回一个 Promise。我会将测试更改为:

it('The request should success', async () => {
        const link = 'http://ip.jsontest.com';
        expect(await getDataAboutWeather(link)).to.eql({});
    });

【讨论】:

    【解决方案2】:

    要测试您的函数,您需要检查 API JSON 是否等于预期的 JSON。您可以使用下面的功能。

    _.isEqual(object, other);
    

    更多信息:How to determine equality for two JavaScript objects?

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 2022-11-29
      • 2015-06-13
      • 2011-10-08
      • 1970-01-01
      • 2019-07-17
      相关资源
      最近更新 更多