天道酬勤,学无止境

TestCafe how to reload actual page

Is there a way to reload the actual tested page I'm visiting in TestCafe and not the site that TestCafe is running under. I've tried using:

await t.eval(() => location.reload(true));

but that just reloads the server page that TestCafe uses. So for example, if I test www.google.com, the URL in the browser after I launch TestCafe will be something like http://172.16.0.152:58486/Qf6eMxOvA/https:/www.google.com/ That is the site that reloads when I execute the code above. Is there a way to force just reloading www.google.com to actually simulate reloading the tested page?

评论

await t.eval(() => location.reload(true));

You are right, you should use the code provided above to reload your test page.

Please check out the following example. The example works as expected: we check the local storage value after the page reload.

test.js:

import { ClientFunction } from 'testcafe';

fixture `fixture`
    .page `http://devexpress.github.io/testcafe/example`;

const getLocalStorageItem = ClientFunction(key => localStorage.getItem(key));

test('local storage', async t => {
    await t.eval(() => localStorage.setItem('key', 'value'));
    await t.expect(getLocalStorageItem('key')).eql('value');
    await t.wait(2000);
    await t.eval(() => location.reload(true));
    await t.wait(2000);
    await t.expect(getLocalStorageItem('key')).eql('value');
});

Result:

Running tests in:
- Chrome 74.0.3729 / Windows 10.0.0

fixture
√ local storage


1 passed (9s)

Do try to avoid eval and wait in general. Make use of Testcafe's ClientFunction instead. I use something like this in my base page object:

  async refresh () {
    await ClientFunction(() => {
      document.location.reload();
    })();
  }

then in your test, call it with something like myPage.refresh()

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Testcafe - Test command line argument outside test case
    As I'm getting familiar with Testcafe, I'm trying to use a command line argument to give the user more information on how to run tests. For that reason, I'm using the minimist package. However, I cannot print or use any variables outside the test cases. Please find below my code. import { Selector } from 'testcafe'; import minimist from 'minimist'; const args = minimist(process.argv.slice(2)); const env = args.env; console.log('*** A SAMPLE CONSOLE OUTPUT ***'); // does not print fixture `Getting Started` .page `http://devexpress.github.io/testcafe/example`; test('My first test', async t => {
  • How to share a global variable between test files from a test in TestCafe?
    I'm manually setting auth cookies for my login purpose and I would like to share the Auth token across my tests. The very first time I have to perform a login in a test and then I have to save the auth token in a variable and share it across the test files. Here is the code snippet to explain what and how I'm trying to do: loginTest.js : let authToken = null; fixture`Login test` .page(inputData.url) .beforeEach(async (t) => { const nextMonth = new Date(); nextMonth.setMonth(nextMonth.getMonth() + 1); await t.navigateTo(inputData.url).then(await setCookie('AUTH_COOKIE_ID', authToken, nextMonth)
  • 如何将灯塔与 testcafe 集成?(how to integrate lighthouse with testcafe?)
    问题 我需要在调用lighthouse传递connection参数 https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/index.js#L41 async function lighthouse(url, flags = {}, configJSON, connection) { // verify the url is valid and that protocol is allowed if (url && (!URL.isValid(url) || !URL.isProtocolAllowed(url))) { throw new LHError(LHError.errors.INVALID_URL); } // set logging preferences, assume quiet flags.logLevel = flags.logLevel || 'error'; log.setLevel(flags.logLevel); const config = generateConfig(configJSON, flags); connection = connection || new ChromeProtocol(flags.port, flags.hostname); //
  • How do I debug a Testcafe browser running in a testcafe/testcafe docker container?
    Got a test for a React app's login function in a Page class: async login(t) { console.log('starting login...'); debugger; this.logBrowserMessages(t); await this.loginModal({ visibilityCheck: true }); await t .expect(this.loginModal.visible) .ok() // then log the user in etc... And the test, which passes when running locally but fails in the container test.requestHooks(mock)('user can log in', async t => { await page.login(t); // Make sure test user's orders render. await t.expect(page.orders.childNodeCount).gt(1, { timeout: 10000 }); The test passes locally but fails (the login doesn't work)
  • 如何确定如何将网站导航文本/链接与配置进行比较(How to determine how to compare website navigation text/links to config)
    问题 我正在尝试使用 TestCafe/JavaScript 创建一个测试,它将网站的顶部菜单文本/链接与存储在配置中的预期数据进行比较。 我对 TestCafe 有一些经验,但仍在学习。 当我设置函数并调用它时,我输入了函数而不是其中的循环,正如 FOR 循环内的 console.log 没有打印到控制台所证明的那样。 我已经调试了一段时间,无法弄清楚。 网址:https://wdwthemeparks.com 配置文件(位于项目中的./config/default.json5) // Expected Desktop top menu links "top_menu_nav": { "All": "/all/", "News": "/news/", "Press Releases": "/press/", "Rumors": "/rumors/", "About": "/about/", "Contact": "/contact/", "Refurbishments": "/refurbishments/", }, } 选择器和相关函数(位于项目中的 ./page-objects/header.js) const config = require('../config/config.js'); import { Selector, t } from 'testcafe'
  • 如何使用 testcafe 测试基于传单的地图?(How to test leaflet based maps using testcafe?)
    问题 我们正在使用 TestCafe 构建一系列测试。 我们如何测试传单控件中的点或路径是否正确呈现? 更具体地说,我们正在尝试测试地图中圆形标记的纬度数据。 但是,在 testcafe 脚本的范围内,我们没有任何传单地图/标记对象可用。 参考: 单元测试传单映射 回答1 我在入门演示页面 https://leafletjs.com/examples/quick-start/ 上为传单控件中的路径元素创建了一个简单的断言示例 import { Selector } from 'testcafe'; fixture `fixture` .page `https://leafletjs.com/examples/quick-start/`; test('test', async t => { await t .switchToIframe('iframe') .expect(Selector('path').withAttribute('stroke', 'red').getAttribute('d')).eql('M141.20355555554852,171.94704600190744a42,42 0 1,0 84,0 a42,42 0 1,0 -84,0 '); }); 请向我们提供您的测试页面示例,以便我们能够为您提供更具体的内容。
  • How to log Google Analytics calls in Testcafe?
    I am trying to automatically test tracking code and I am using the RequestLogger from Testcafé. I succeeded to intercept calls to example.com and localhost but not to https://www.google-analytics.com/. What could be the reason? Expected This test should be green Test code import { RequestLogger } from 'testcafe'; const logger_ga = RequestLogger('https://www.google-analytics.com/'); fixture `localhost` .page('http://localhost:8000') test .requestHooks(logger_ga) ('logs calls to Google Analytics', async t => { await t.click("#ga-button"); console.log(logger_ga.requests); // is empty due to
  • How do I make a TestCafe test fail when angularjs throws an error?
    When angularjs throws an error, it's caught in a try/catch and then an exception handler logs it as console.error. As a result, testcafe does not make a test fail whenever this happens, but we would like this to be considered a failing test. We tried to follow a suggestion in this thread and wrote this code: fixture `Getting Started` .page `http://localhost:${port}/`; const handleErrors = ClientFunction(() => { console.error = msg => {throw new Error(msg)}; }); test('Test', async t => { await handleErrors(); //visit page with error, go somewhere else, return to page await t .expect(Selector(
  • TestCafe - 浏览器总是在两次测试之间以全新的方式启动。 如何覆盖它以便浏览器记住缓存、用户设置和存储(TestCafe - The browser always starts in clean slate between the tests. How to override this so that browser remembers cache, user settings and storage)
    问题 测试之间的浏览器始终以全新的方式打开。 登录在我的应用程序中被记住,因为身份验证仍然存在,但是由于浏览器总是以全新的方式打开,我必须在所有灯具的挂钩之前执行登录。 有什么方法可以打开浏览器,以便记住用户设置、缓存、本地和会话存储? 回答1 TestCafe 不提供在测试之间存储页面状态的方法,而是鼓励编写独立的测试。 但是,Roles API 可能会满足您的一些需求(有关更多详细信息,请参阅此评论)。 回答2 这就是我使用 Role API 解决的方法。 Login.js 页面对象文件 const loginBtn = Selector('[type="submit"]'); const password = Selector('input[placeholder="Password"]'); const userName = Selector('input[placeholder="Email"]'); export const login = Role(`http://example.com/login`, async t => { await t .typeText(userName, `abc`) .typeText(password, `password`) .click(loginBtn); }); 然后我在我的夹具文件中调用了这个 const Login
  • Testcafe:有没有办法在页面之间保持登录会话完好无损?(Testcafe: Is there a way to keep the logged-in session intact between pages?)
    问题 我正在使用 Instagram 来解释我的场景。 我在 Instagram 中使用 testUser id 登录。 我循环浏览一组 Instagram 帐户(例如:https://www.instagram.com/some_page/)。 此类直接 URL 是从 JSON 文件传递​​的。 我验证了此页面上的某些内容,然后转到下一页以执行相同的验证集。 我的问题是,为每个数据执行登录块。 我无法在 Fixture 部分给出它。 无论如何,当我在页面之间移动时,是否可以保持登录会话完好无损。 角色代码 const testUser = Role('https://www.instagram.com/accounts/login/', async t => { /* some code */ }, { preserveUrl: true }); Fixture 和 BeforeEach: fixture`Instaa Test` .page`https://www.instagram.com/` .before(async t => { }) .beforeEach(async t => { await t.setTestSpeed(0.3) await t.useRole(testUser) await t.maximizeWindow() }) 测试块: dataSet
  • testcafe RequestLogger not intercepting api calls
    For some reason, I cannot get testcafe's RequestLogger to log any of the API calls that I am making. I've read nearly all of the articles and questions on the RequestLogger and everything is pointing to what appears to be the same as the below code as working. Not sure what I'm doing wrong, any help would be great. References: https://devexpress.github.io/testcafe/documentation/test-api/intercepting-http-requests/logging-http-requests.html Cannot intercept outgoing AJAX request from page using Testcafe How to log Google Analytics calls in Testcafe? I am running locally and hitting an API that
  • Selenium Webdriver 的替代品 [关闭](Alternatives to Selenium Webdriver [closed])
    问题 关闭。 此问题不符合 Stack Overflow 准则。 它目前不接受答案。 想改善这个问题吗? 更新问题,使其成为 Stack Overflow 的主题。 3年前关闭。 改进这个问题 我使用 Selenium Webdriver for C# 和 Python 从网站获取数据元素,但网络抓取速度非常慢。 抓取 35000 个数据表花了我大约 1.5 天的时间。 使用 Selenium Webdriver 我可以执行 Javascript 来获取 Java 元素。 是否有一些可用的库不需要像 Webdriver 这样的东西来在网页上执行 Javascript 来检索元素并且也能够点击元素? 或者有没有更快的 Selenium 替代品? 回答1 我建议你使用 TestCafe。 TestCafe 是用于 Web 功能测试(e2e 测试)的免费开源框架。 TestCafe 基于 Node.js,根本不使用 WebDriver。 TestCafe 驱动的测试在服务器端执行。 为了获取 DOM 元素,TestCafe 提供了强大灵活的选择器系统。 TestCafe 可以使用 ClientFunction 功能在经过测试的网页上执行 JavaScript(请参阅我们的文档)。 TestCafe 测试真的非常快,你自己看看。 但由于内置智能等待系统,高速试运行不影响稳定性。
  • testcafe RequestLogger 不拦截 api 调用(testcafe RequestLogger not intercepting api calls)
    问题 出于某种原因,我无法让 testcafe 的 RequestLogger 记录我正在进行的任何 API 调用。 我已经阅读了几乎所有关于 RequestLogger 的文章和问题,所有内容都指向与以下代码相同的内容。 不知道我做错了什么,任何帮助都会很棒。 参考: https://devexpress.github.io/testcafe/documentation/test-api/intercepting-http-requests/logging-http-requests.html 无法使用 Testcafe 拦截来自页面的传出 AJAX 请求 如何在 Testcafe 中记录 Google Analytics 调用? 我在本地运行并访问也在本地运行的 API,前端在端口 3000 上,后端在端口 8080 上,API 位于:8080/api/admin。 我可以看到记录器被注入到测试中,但没有更新它,它只是一个带有初始道具的平淡对象,并且会在 t.expect 语句之后出错。 我想知道 beforeEach 是否破坏了某些东西,但我需要它来触发任何 API 调用,因为用户需要经过身份验证。 我可以看到调试时调用的 API 请求,我正在尝试拦截,但没有运气 testcafe 版本:1.0.0 || 0.23.3 测试代码 // have tried several
  • 使用 testCafe 'requestLogger' 检索 Chrome 性能日志失败(Using testCafe 'requestLogger' to retrieve chrome performance logs fails)
    问题 这是该线程的延续:TestCafe 中是否有一种方法可以验证 Chrome 网络调用? 这是我的 testCafe 尝试从 chrome 检索所有网络日志(即开发人员工具中的网络选项卡)。 我在控制台上打印任何内容时遇到问题。 const logger = RequestLogger('https://studenthome.com',{ logRequestHeaders: true, logRequestBody: true, logResponseHeaders: true, logResponseBody: true }); test ('My test - Demo', async t => { await t.navigateTo('https://appURL.com/app/home/students');//navigate to app launch await page_students.click_studentNameLink();//click on student name await t .expect(await page_students.exists_ListPageHeader()).ok('do something async', { allowUnawaitedPromise: true }) //validate list
  • TestCafe 可见性检查不等待元素出现(TestCafe visibilityCheck does not wait for element to appear)
    问题 我试图让 TestCafe 等待一个元素出现在 dom 中。 目前我正在使用 { visibleCheck: true } 但它似乎没有做任何事情,测试将超时并被视为失败。 目标: 转到页面等待 searchIconElement 加载 代码: fixture`Library /all`.page(page.libraryScreen).beforeEach(async t => { await t.useRole(page.adminUser); }); test('Search Bar', async t => { const searchIcon = Selector('div').withAttribute('class', 'CampaignsPage-fab1'); const searchIconElement = searchIcon.with({ visibilityCheck: true })(); const microAppNameInput = Selector('input').withAttribute('placeholder', 'Search'); const microAppTitle = Selector('div').withAttribute('class', 'SetCard-title ').innerText; await t
  • testcafe 是否支持测试rest api(Does testcafe support testing of rest api)
    问题 当您尝试直接测试 rest api url 时,测试会挂在 testcafe 浏览器中。 我正在尝试使用请求挂钩对我的其余 API 端点运行测试,但是当我从命令行运行测试时,浏览器会打开 API 端点并加载它并挂起。 测试未通过或失败并挂起。 其余 API 端点仅返回 JSON 响应。 const logger = RequestLogger('https://example.com/search/suggestions?search=testkeyword'); fixture `test` .page('https://example.com/search/suggestions?search=testkeyword'); test .requestHooks(logger) ('test', async t => { // Ensure that the response has been received and that its status code is 200. await t.expect(logger.contains(record => record.response.statusCode === 200)).ok(); const logRecord = logger.requests[0]; console.log(logRecord
  • 在TestCafe中测试运行期间累积所有JS警告和错误(Accumulate all JS warnings and errors during test runs in TestCafe)
    问题 我希望能够在测试运行期间从浏览器控制台访问所有 J​​S 警告和错误。 禁用“-e”(跳过 JS 错误)标志后,测试在第一个错误处停止,因此很明显它正在寻找它们。 启用此标志后,我希望能够看到在测试运行期间触发了哪些错误(最好是警告)。 我试过使用 ClientFunction 和 window.onerror 方法。 我也试过 -r 'reports' 标志——我只看到 TestCafe 错误,而不是来自被测页面的 JS 错误。 我已经尝试从 https://devexpress.github.io/testcafe/documentation/test-api/accessing-console-messages.html 尝试“访问控制台消息”,但这仅提供由 console.log 等抛出的消息(“注意此方法仅返回通过 console.error、console.warn、console.log 和 console.info 方法发布的消息。浏览器输出的消息(例如页面上发生未处理的异常时)将不会返回。") const installErrorHandler = ClientFunction(() => { window.onerror = error => { console.log("ERROR::::::"); console.log(error); }; })
  • TestCafe RequestLogger - 如何在对每个请求对象进行断言之前等待所有响应返回(TestCafe RequestLogger - How to wait for all responses to return before doing an assertion on each request object)
    问题 请参阅随附的屏幕截图。 我有一个 RequestLogger 可以捕获对/api/dynamic_reporting/filters/*/find端点的所有请求。 问题是,当我做断言时await t.expect(dynamicReportingFindRequest.requests[1].response.statusCode).eql(200,'Did not get 200 OK response') ,我收到错误Cannot read property 'statusCode' of undefined因为 xhr 仍在等待requests[1], requests[2]...并且尚未完成。 在对请求进行断言之前,如何等待所有响应返回? 回答1 我会根据 testcafe RequestLogger 不拦截 api 调用问题的想法建议以下解决方案: 这是一个简单的 node.js 服务器: var http = require('http'); http.createServer(function (req, res) { if (req.url.indexOf('test') > -1) { setTimeout(() => { res.writeHead(200, {'Content-Type': 'application/json'}); res.write(
  • Does testcafe support testing of rest api
    Tests hang in the testcafe browser when you try to test a rest api url directly. I am trying to run a test against my rest API endpoint using request hooks, but when I run the test from the command line, the browser opens the API endpoint and loads it and hangs. The test doesn't pass or fail and hangs. The rest API endpoint just returns a JSON response. const logger = RequestLogger('https://example.com/search/suggestions?search=testkeyword'); fixture `test` .page('https://example.com/search/suggestions?search=testkeyword'); test .requestHooks(logger) ('test', async t => { // Ensure that the
  • Using testCafe 'requestLogger' to retrieve chrome performance logs fails
    This is in continuation of this thread: Is there a way in TestCafe to validate Chrome network calls? Here is my testCafe attempt to retrieve all the network logs(i.e. network tab in developer tools) from chrome. I am having issues getting anything printed on console. const logger = RequestLogger('https://studenthome.com',{ logRequestHeaders: true, logRequestBody: true, logResponseHeaders: true, logResponseBody: true }); test ('My test - Demo', async t => { await t.navigateTo('https://appURL.com/app/home/students');//navigate to app launch await page_students.click_studentNameLink();//click on