1

I have a function that makes an API request and receives data in json format.

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);
        });
    });
};

I want to write a test for this function.

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

How to verify that my function works as it should?

Since at the moment I get an error.

AssertionError: expected {} to deeply equal {}
MegaRoks
  • 898
  • 2
  • 13
  • 30
  • 1
    Possible duplicate of [chai test array equality doesn't work as expected](https://stackoverflow.com/questions/17526805/chai-test-array-equality-doesnt-work-as-expected) – Dez Sep 02 '19 at 08:13

2 Answers2

2

getDataAboutWeather is an asynchronous function which means it returns a Promise. I would change the test to:

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

To test your function, you need to check if the API JSON is equal to the expected JSON. You can use the function below.

_.isEqual(object, other);

More information on this: How to determine equality for two JavaScript objects?

txemsukr
  • 1,017
  • 1
  • 10
  • 32