如何使用 testcafe 测试 API 调用的重试

发布于 2025-01-16 23:08:57 字数 1979 浏览 0 评论 0原文

我正在使用 Testcafe 进行集成测试,并且我想测试我的应用程序在收到错误后重试 API 调用的场景。我正在使用异步重试库来拨打电话。 Retry 是我创建的一个实用程序,用于包装 API 调用,以便我可以包装用于调用异步重试的样板代码:

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

对于后代,这是 Retry 实用程序:

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);
};

这是我的测试:

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 是一个实用函数,可以执行登录和导航到我正在测试的页面等操作。我在开发时,使用Chrome devtools来阻止API请求,以测试重试,结果成功。我看到重试有效。但是,我想在我的测试中模仿这一点以自动化此行为。如何模拟 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

固执像三岁 2025-01-23 23:08:57

据我了解,您是从 TestCafe 测试代码而不是从测试页面进行 API 调用。

在这种情况下,RequestMock机制将不会被应用。 RequestMock 通过从网站页面进行的 API 调用来工作。在您的情况下,您自己发起请求,因此 TestCafe 代理不会处理它。

如果您希望 RequestMock 工作,您可以尝试从浏览器而不是测试端进行 API 调用。为此,您可以使用 ClientFunction 机制,该机制允许您将 JS 代码注入到网站页面。

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.

梦开始←不甜 2025-01-23 23:08:57

从 TestCafe 1.20.0 开始,您可以使用专用的 t.request 方法来 在测试中发送请求。发送此类请求将触发您在测试中设置的请求挂钩(如果这些请求满足请求挂钩的参数)。
您可以在指南中了解有关 TestCafe API 测试的更多信息。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文