Reputation: 1053
Testcafe gives you the ability to mock the response of a request, which I am able to do.
I would like to implement a caching system for all GET/Ajax request.
This works fine if the URL is in the cache but for those that are not in the cache it returns an empty response.
This is because (I imagine) I am not calling res.setBody() on those URL not found in the cache.
export const requestMock = RequestMock()
.onRequestTo({ method: 'GET', isAjax: true })
.respond(async (req: Request, res: Response & { setBody: Function }) => {
const url: string = req.url
try {
const body: string = await cache.getItem(url)
if (body) {
res.setBody(body)
}
} catch (error) {
print.error(error)
}
})
How can I get the original Response.body
this way I can res.setBody(originalBody)
?
Upvotes: 0
Views: 403
Reputation: 437
This would require your code to actually go and fetch the data first and add it to cache for future requests. But this is not mocking, this is just caching.
Consider using actual mocks, e.g. store responses to the requests in some JSON files (or whatever format you use there) and return contents of this file when the tested app is trying to make a request to the specific URL.
If you'd still like to go with the caching solution, inside of your respond
callback your code should check whether there is a response for that URL in the cache. If yes, then return body from cache (as you're doing right now). If no, make this request, add the response to the cache and return the response.
For making the request, you can use fetch
API (browser) or use some library like axios
(Node.js runtime).
Upvotes: 2