简体   繁体   中英

How to test retries to an API call using testcafe

I am using Testcafe for my integration tests, and I want to test the scenario where my app retries an API call after receiving an error. I am using the async-retry library to make my calls. Retry is a utility I created to wrap the API call so I could wrap boilerplate code for calling async-retry:

 const response = await Retry( () => { return fetch( buildUrl(env, csrf, '/api/myCustomCall', queryParams), options ); }, 'getRecommendations', { onRetry: () => { console.log('RETRYING'); } } );

For posterity, this is the Retry utility:

 import retry, { AsyncRetryOptions } from 'async-retry'; export const Retry = ( func: () => Promise<any>, name: string, opts: AsyncRetryOptions = {} ): Promise<any> => { const retryOptions = { retries: opts.retries || 3, factor: opts.factor || 2, minTimeout: opts.minTimeout || 3000, maxTimeout: opts.maxTimeout || Infinity, randomize: opts.randomize || true, onRetry: (error: Error, attempt: number) => { console.error( `${new Date().toString()} - ${name} failed ${attempt} times, trying again` ); } }; return retry(func, retryOptions); };

This is my test:

 test.requestHooks( RequestMock() .onRequestTo(/myCustomCall/) .respond({ error: 'Bad value for request parameter' }, 400, responseHeaders) )('Recommendation request retries 3 times', async (t) => { await playgroundInit(t); await t.expect(recommendationLogger.requests.length).eql(4); });

playgroundInit is a utility function that does things like login and navigating to the page I am testing. When I was developing, I used the Chrome devtools to block the API request in order to test the retries, which was successful. I saw the retries working. However, I'd like to mimic this in my test to automate this behavior. How do you mock a request in testcafe to trigger retries?

As I understand it, you are making your API call from the TestCafe test code, but not from the tested page.

In this case, the RequestMock mechanism will not be applied. RequestMock works from API calls that were made from the website page. In your case, you initiate a request yourself, so the TestCafe proxy does not process it.

If you wish to make RequestMock work you can try making your API calls from the browser but not test side. To do this, you can use the ClientFunction mechanism that allows you to inject JS code to the website page.

Since TestCafe 1.20.0, you can use the dedicated t.request method to send requests in your tests. Sending such requests will trigger request hooks that you set in your test (if these requests fulfill the request hooks' parameters). You can learn more about TestCafe API testing in the guide .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM