lundi 16 novembre 2020

Did I properly mock the API Call?

I'm not sure if I got it right so please - feel free to provide any kind of explanation.

I'm trying to write a test for the function responsible for calling the API. I know that the good practice is to mock the API function instead of calling the real API. I've done it and my test is passing but can I be really sure that I'm not calling the real API? How do I check that ?

domain.js

export const getCountriesData = () => {
    return fetch("https://restcountries.eu/rest/v2/all").then((response) =>
    response
      .json()
      .then((data) => {
        return data;
      })
      .catch((err) => console.log(err))
  );
}

domain.test.js

const testData = [
    {name: 'Poland', capital: 'Warsaw', borders: ['BLR', 'DEU'], region: 'Europe', alpha3Code: "POL"},
    {name: 'Afghanistan', capital: 'Tokio', borders: ['CHN', 'UZB'], region: 'Asia', alpha3Code: "AFG"},
    {name: 'United States of America', capital: 'Washington', borders: ['CAN', 'MEX'],region: 'Americas', alpha3Code: "USA"},
    {name: 'Germany', capital: 'Berlin', borders: ['POL', 'BEL'], region: 'Europe', alpha3Code: "DEU"},
    {name: 'Belarus', capital: 'Minsk', borders: ['LVA', 'LTU'], region: 'Europe', alpha3Code: "BEL"}
];

global.fetch = jest.fn(()=> 
    Promise.resolve({
        json: ()=> Promise.resolve(testData)
    })
    
)

describe('Api call test', ()=> {
    it('Should call the mocked API call', async ()=> {
        const data = await getCountriesData();
        expect(data).toEqual(testData);
    })
})

Please let me know if that's the correct way of doing such a test :) Thanks !

Aucun commentaire:

Enregistrer un commentaire