I am looking to test nested fetches. So far I can test the result of the first fetch but can't access the other one. I have tried nesting the next fetch call in the first but that does not seem to work. The second SpyOn function call creates a jasmine errors saying I can't have multiple spys for the same function.
Jasmine test
let response = new Response(
JSON.stringify({
test: "test",
})
);
// creating a fetch spy
spyOn(window, "fetch").and.returnValue(Promise.resolve(response));
// make call to fetch
callFirstFetch().then((result) => {
expect(window.fetch).toHaveBeenCalledWith("/test");
spyOn(window, "fetch").and.returnValue(Promise.resolve(response));
done();
});
and the nested fetch code looks like
function firstFetch(() => {
return fetch("/test")
.then(response => {
response.json();
return secondFetch();
})
});
function secondFetch(() => {
return fetch("/test2")
.then(response => {
response.json();
console.log('done');
})
});
firstFetch();
I am looking to test nested fetches. So far I can test the result of the first fetch but can't access the other one. I have tried nesting the next fetch call in the first but that does not seem to work. The second SpyOn function call creates a jasmine errors saying I can't have multiple spys for the same function.
Jasmine test
let response = new Response(
JSON.stringify({
test: "test",
})
);
// creating a fetch spy
spyOn(window, "fetch").and.returnValue(Promise.resolve(response));
// make call to fetch
callFirstFetch().then((result) => {
expect(window.fetch).toHaveBeenCalledWith("/test");
spyOn(window, "fetch").and.returnValue(Promise.resolve(response));
done();
});
and the nested fetch code looks like
function firstFetch(() => {
return fetch("/test")
.then(response => {
response.json();
return secondFetch();
})
});
function secondFetch(() => {
return fetch("/test2")
.then(response => {
response.json();
console.log('done');
})
});
firstFetch();
Share
Improve this question
edited Feb 14, 2021 at 22:44
Mohammad Yaser Ahmadi
5,0514 gold badges20 silver badges44 bronze badges
asked Feb 14, 2021 at 22:33
user2301893user2301893
1211 silver badge3 bronze badges
2
-
What's wrong with
expect(window.fetch).toHaveBeenCalledWith("/test"); expect(window.fetch).toHaveBeenCalledWith("/test2");
or count the # calls tofetch
? – Randy Casburn Commented Feb 14, 2021 at 22:52 - Why would you want to test mocked return data from an API that is internal. It is a waste of time/resources testing the internals. – Randy Casburn Commented Feb 14, 2021 at 23:48
1 Answer
Reset to default 6This is how you can mock your fetch api call:
const okResponse = new Response(JSON.stringify({}), { status: 200, statusText: 'OK', });
spyOn(window, 'fetch').and.resolveTo(okResponse);
And then test it like this:
expect(window.fetch).toHaveBeenCalledWith(requestUrl, options);