简体   繁体   中英

Test Javascript calls to api with jest

I am trying to test the call to github api using jest to see if the results are returned (the aim of this is to test my unit testing skills). But for some reasons, my code works fine but still fails my test. My suspicion is that i most likely don't understand how to write these kind of test. Below is my code

const functions = {
    getUserRepo: async (username) => {
    const url = `https://api.github.com/users/${username}/repos`;
    console.log(url);
    let result = [];
    await axios.get(url)
        .then(function (response) {
            response.data.forEach(value => result.push(value.name));
            return result;
        })
        .catch(function (error) {
            return error;
        });
    }
}  

This code above returns the right results in an array format but fails the test below

describe('Check repos from git api', () => {
test('Should return user repos', async () => {
    await functions.getUserRepo('whitehox')
        .then((response) => {
            expect(response.data).toEqual([ '57','decafreelance','decases','eexport','exportchat','flisch', 'gitprac', 'itravelcentral', 'pollark', 'portfolio', 'startereit', 'talkative', 'team-portfolio'])
        })
    });
});

Please what is the issue with this test and how do i fix it?

Two things need to be fixed.

You need to return the result from your function. It can be simplified to this:

const functions = {
  getUserRepo: (username) => {
    const url = `https://api.github.com/users/${username}/repos`;
    console.log(url);
    return axios.get(url)  // <= return the result
      .then(function (response) {
        return response.data.map(value => value.name);
      })
      .catch(function (error) {
        return error;
      });
  }
}

...which makes response the array so test it directly:

describe('Check repos from git api', () => {
  test('Should return user repos', async () => {
    await functions.getUserRepo('whitehox')
      .then(response => {
        // response **is** the array
        expect(response).toEqual(['57', 'decafreelance', 'decases', 'eexport', 'exportchat', 'flisch', 'gitprac', 'itravelcentral', 'pollark', 'portfolio', 'startereit', 'talkative', 'team-portfolio', 'YorubaIndigenous']);  // Success!
      })
  });
});

(...and there is also a new repo called 'YorubaIndigenous' , I added it to the expected value).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM