Did I properly mock the API Call?

半腔热情 提交于 2021-01-29 08:08:10

问题


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 !

来源:https://stackoverflow.com/questions/64864737/did-i-properly-mock-the-api-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!