How to mock 'cross-fetch' GET POST & PUT methods - javascript

I have my code as
import fetch from 'cross-fetch'
const headers = {
Authorization: `Bearer abcdEFGH1234`,
Accept: 'application/json',
'Content-Type': 'application/json',
}
const getData = await fetch('https://api_base_url/rest/api/latest/queue/ProjectKey-PlanKey', {
method: 'GET',
headers: headers,
})
// convert the API Call response to Json
const getDataJson = await getData.json()
const putData = await fetch('https://api_base_url/rest/api/latest/queue/ProjectKey-PlanKey/comments', {
method: 'PUT',
headers: headers,
body: {message: "comment"},
})
// convert the API Call response to Json
const putDataJson = await putData.json()
cross-fetch does not seem to have methods directly like fetch.get or fetch.PUT, so the methods have to be passed via options.
The problem I am facing is how to mock these methods during testing with Jest.
I tried as below but it does not work
const mockFetchGet = jest.fn((arg1, arg2) => {
return new Promise((resolve) => {
resolve(true)
})
})
const mockFetchPost = jest.fn((arg1, arg2, arg3) => {
return new Promise((resolve) => {
resolve(true)
})
})
const mockFetchPut = jest.fn((arg1, arg2, arg3) => {
return new Promise((resolve) => {
resolve(true)
})
})
jest.mock('cross-fetch', () => {
return {
fetch: jest.fn().mockImplementation(() => {
return {
get: mockFetchGet,
post: mockFetchPost,
put: mockFetchPut,
}
}),
}
})
I get the error like below. Can anyone help? ANY GUIDANCE IN THIS IS HIGHLY APPRECIATED
TypeError: (0 , cross_fetch_1.default) is not a function
75 | )
76 |
> 77 | const mergePullRequest = await fetch(
| ^
78 | `https://api_base_url/rest/api/latest/queue/ProjectKey-PlanKey/merge`,
79 | {
80 | method: 'POST',

Related

react-native api call got stuck

I am doing a simple API call in a function. The API Response is fine in Postman it 280 ms to 340 ms. but in my Application it taks 5 to 10 mins. Here is my function.
const getSuggestions = async query => {
const filterToken = query.toLowerCase();
if (query.length < 3) {
setLoading(false);
return;
}
setLoading(true);
var myHeaders = new Headers();
myHeaders.append(
'Authorization',
'Basic xyzxyzxyzxyzxyzyzyzyzy',
);
myHeaders.append('Content-Type', 'application/json');
var raw = JSON.stringify({
query: filterToken,
language: 'en',
});
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
};
fetch(
'https://api.worldota.net/api/b2b/v3/search/multicomplete/',
requestOptions,
)
.then(response => response.json())
.then(response => {
const sections = [];
Object.keys(response.data).map((item, i) => {
sections.push({
title: item,
data: response.data[item],
});
});
setSuggestionsList(sections);
setLoading(false);
})
.catch(err => {
console.log(err);
setLoading(false);
});
};
when ever my search params are changed then i call this function. whats is the problem with my function. it was working fine last day. :(

Passing argument to async / await function returns "undefined"

When posting data to an API and get a response, if I hardcode the body data inside the fetch call (body: "XYZ12345") it works fine, this is an example:
const vatValidationRequest =
fetch(
'/api/vies/validateVAT.php', {
method: 'POST',
body: "XYZ12345",
headers: {
'Content-Type': 'application/text'
}
})
.then((response) => response.text())
.then((responseText) => {
return responseText;
});
const validateVAT = async () => {
const viesResponse = await vatValidationRequest;
console.log(viesResponse);
};
validateVAT();
However, if I try to pass the body data as an argument (body: vatNumber), the validateVAT() function returns "undefined". This is what's not working:
const vatValidationRequest = (vatNumber) => {
fetch(
'/api/vies/validateVAT.php', {
method: 'POST',
body: vatNumber,
headers: {
'Content-Type': 'application/text'
}
})
.then((response) => response.text())
.then((responseText) => {
return responseText;
});
}
const validateVAT = async (vatNumber) => {
const viesResponse = await vatValidationRequest(vatNumber);
console.log(viesResponse);
};
validateVAT("XYZ12345");
Any clues about how to pass the argument to the async function? thanks!
The problem is that you are not returning the response from the method. You should do this:
const vatValidationRequest = (vatNumber) => {
return fetch(
'/api/vies/validateVAT.php', {
method: 'POST',
body: vatNumber,
headers: {
'Content-Type': 'application/text'
}
})
.then((response) => response.text())
.then((responseText) => {
return responseText;
});
}
const validateVAT = async (vatNumber) => {
const viesResponse = await vatValidationRequest(vatNumber);
console.log(viesResponse);
};
validateVAT("XYZ12345");

TypeError: res.json is not a function (not able to get fetch data)

I m trying to GET response using fetch API not stuck in a error as I mentioned below. Here's my code
const DefaultLayout = () => {
let history = useHistory()
const callHomePage = async () => {
try {
const res = fetch('http://localhost:4000/api/authenticate', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
credentials: 'include',
})
console.log(res)
const data = await res.json()
console.log(data)
if (!res.status === 200) {
const error = new Error(res.error)
throw error
}
} catch (err) {
console.log(err)
history.push('login')
}
}
Error: TypeError: res.json is not a function
Promise {} shows pending
const DefaultLayout = () => {
let history = useHistory()
const callHomePage = async () => {
try {
const res = await fetch('http://localhost:4000/api/authenticate', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
credentials: 'include',
})
console.log(res)
const data = await res.json()
console.log(data)
if (!res.status === 200) {
const error = new Error(res.error)
throw error
}
} catch (err) {
console.log(err)
history.push('login')
}
}
You need to await the fetch statement and then call the .json method of the response.
const res = await fetch(...)
data = await res.json();
Read more: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

How to map this given api response in react js javascript

I am getting an error when i was calling an post request in use effect hook and i got the response as promise pending, but the object is there, please see the response and please provide a perfect code to map this response.
code
function Comment({ id }) {
const [data, setdata] = useState([]);
console.log(id);
useEffect(() => {
const query = `
query{
forumAnswerId(id:${id}){
forumAnswerBody
forumAnswerTime
forumAnswerCode1
forumAnswerCode2
forumAnswerCode3
forumAnswerAuthor
forumAnswerBoolean
forumAnswerCode1Title
forumAnswerCode2Title
forumAnswerCode3Title
}
forumComment(forumAnswerComment:${id}){
forumAnswerCommentPost
forumAnswerCommentBody
forumAnswerCommentAuthor
forumAnswerCommentTime
}
}
`;
const opts = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query }),
};
const res = fetch('http://127.0.0.1:8000', opts).then((res) => res.json());
setdata(res);
}, []);
return <div></div>;
}
export default Comment;
here you are:
fetch('http://127.0.0.1:8000', opts)
.then((res) => res.json())
.then(r=> setdata(r))
promise result cannot be accessed outside. You need to set data inside the then function
Using Promise
fetch('http://127.0.0.1:8000', opts).then((res) => setdata(res.json()));
Using Async await
const res=await fetch('http://127.0.0.1:8000', opts)
setdata(res.json())
useEffect(() => {
const fetchData = async () => {
const query = `
query{
forumAnswerId(id:${id}){
forumAnswerBody
forumAnswerTime
forumAnswerCode1
forumAnswerCode2
forumAnswerCode3
forumAnswerAuthor
forumAnswerBoolean
forumAnswerCode1Title
forumAnswerCode2Title
forumAnswerCode3Title
}
forumComment(forumAnswerComment:${id}){
forumAnswerCommentPost
forumAnswerCommentBody
forumAnswerCommentAuthor
forumAnswerCommentTime
}
};`
const opts = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query }),
};
const res = await fetch('http://127.0.0.1:8000', opts).then((res) => res.json());
setdata(res);
}
fetchData();
}, []);

Fetch API store custom header value for later use

I have the following:
let eTag: any
const request = (method: string) => (basePath: string) => async (path: string, data?: object) => {
const accessToken = await getAccessToken()
const opt: any = {
method,
headers: {
Authorization: `Bearer ${accessToken}`,
...(data && { eTag })
},
...(data && { body: data }),
}
return fetch(`${basePath}${path}`, opt).then(
res => {
eTag = res.headers.get('ETag')
return res.json()
}
)
}
I have managed to get the value form the customer header eTag but it doesn't seem to store it correctly.
I am getting the error of Unexpected end of JSON input in regards to res.json()
res.json() returns a promise. So you need the following:
let eTag: any
const request = (method: string) => (basePath: string) => async (path: string, data?: object) => {
const accessToken = await getAccessToken()
const opt: any = {
method,
headers: {
Authorization: `Bearer ${accessToken}`,
...(data && { eTag })
},
...(data && { body: data }),
}
return fetch(`${basePath}${path}`, opt).then(
async res => { //add async keyword
eTag = res.headers.get('ETag')
return await res.json() //add await here to return resolved json
}
)
}

Categories

Resources