如何在TestCafe的page方法中引用JavaScript变量?
Hey there! The issue with your current code is that you’re not using JavaScript template literals correctly—you need to wrap the variable in ${} instead of just $url. Let’s fix that, plus show you an even cleaner way to handle this:
Correct Template Literal Approach
const url = "myreallylongurl"; test.page`${url}`('check email', async t => { // Your test logic here });
Even Simpler Alternative: Pass the Variable Directly
TestCafe’s page method accepts plain string variables too, so you can skip template literals entirely if you prefer:
const url = "myreallylongurl"; test.page(url)('check email', async t => { // Your test logic here });
Bonus Tip for Scalability
If you have multiple tests using different URLs, store them in a dedicated constants file (like test-urls.js) to keep your test code tidy and make updates easier:
// test-urls.js export const TEST_URLS = { login: "myreallylongloginurl", dashboard: "myreallylongdashboardurl" };
Then import and use them in your test files:
import { TEST_URLS } from './test-urls.js'; test.page(TEST_URLS.dashboard)('check email', async t => { // Test logic here });
This way, all your URLs live in one place, and your test lines stay focused on the test name itself.
内容的提问来源于stack exchange,提问作者Vladimir_314159

