在 Cypres.config.ts 内发出同步请求

Nic*_*ico 3 javascript typescript axios cypress

我正在使用 Cypress 12.13.0,并且我正在尝试使用在测试会话开始之前执行内容的钩子。我需要在任何测试和任何规范文件之前执行一些操作。根据 cypress 文档,执行此操作的正确位置是文件cypress.config.ts

import { defineConfig } from 'cypress';

export default defineConfig({
    e2e: {
        setupNodeEvents(on): void {
            on('before:run', () => {
                // Stuff here will be executed at the beginning of the Cypress session
                console.log('foo');
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

这正如我预期的那样。但现在我想在之后同步执行请求console.log('foo');。我没有找到一种简单的方法来做到这一点,因为大多数函数都依赖于async方法。我可以得到这个,但最终结果仍然是异步的:

function performRequest() {
    axios
        .get(apiUrl)
        .then((response) => {
            return response.data;
        })
        .catch((error) => {
            console.error('Error:', error.message);
        });
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是在 Cypress 会话之前使用 shell 脚本来执行我需要的相同操作,但该解决方案感觉不太专业。

Lol*_*ola 5

您可以进行before:run回调async,然后使用await.

function performRequest() {
    return axios                              // return the implicit promise here
        .get(apiUrl)
        .then((response) => {
            return response.data;
        })
        .catch((error) => {
            console.error('Error:', error.message);
        });
}

import { defineConfig } from 'cypress';

export default defineConfig({
    e2e: {
        setupNodeEvents(on): void {
            on('before:run', async () => {           // make this function async

                const data = await performRequest()  // await synchronously

            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)