reactjs - Testing fetch using Jest- React Native -
i have common api class use handling api calls in react native. make call , json/ error , return it. see code below.
// general api acces data web import apiconstants './apiconstants'; export default function api(path,params,method, sssid){ let options; options = object.assign({headers: { 'accept': 'application/json', 'content-type': 'application/json' }},{ method: method }, params ? { body: json.stringify(params) } : null ); return fetch(apiconstants.base_url+path, options).then( resp => { let json = resp.json(); if (resp.ok) { return json; } return json.then(err => { throw err; }).then( json => json ); }); }
but when write jest test mock api folllows in tests folder.
test('should login',() => { global.fetch = jest.fn(() => new promise((resolve) => { resolve( { status: 201, json: () => (mock_data_login) }); })); return api(apiconstants.login,{'un':'test1','pwd':'1234'},'post', null).then((data1)=>{ expect(data1).tobedefined(); expect(data1.success).toequal(true); expect(data1.message).toequal('login success'); }); });
it fails
typeerror: json.then not function
when change fetch return this, test passes.
return fetch(apiconstants.base_url+path, options).then( resp => { let json = resp.json(); return json }); }
why type error error popping up? can't change api module, because redux saga code change. should do?
in code, json object , not promise, undefined. that's complain getting because trying use undefined function. problem not in test in code ha san error. try following instead.
return fetch(apiconstants.base_url+path, options) .then(resp => resp.json()) .then( json => json) .catch((error) => error); });
Comments
Post a Comment