Karate UI自动化跨域测试的实现方法咨询
Karate UI跨域测试问题解决方法
问题描述
用户提供的Karate UI自动化测试代码如下:
Feature: Test Senetel Webapp Scenario: Login with incorrect credentials Given configure driver = {type: 'chrome', addOptions:["--remote-allow-origins=*"], port: 9515, executable: 'C://Program Files//Google//Chrome//Application//chrome.exe'} When driver 'https://fmsso-acpt.fanniemae.com/' And driver.maximize() And delay(3000) And input("#username","d33k4cnt") And input("#password","Dec_2023") And delay(3000) And click("//a[@id='signOnButton']") And delay(3000) And driver 'https://web.pr360b.sfbu.acpt.intgfanniemae.com/#/home' And delay(12000) And waitForUrl("https://web.pr360b.sfbu.acpt/#")
测试流程为:从登录页https://fmsso-acpt.fanniemae.com/登录后,跳转至首页https://web.pr360b.sfbu.acpt/#,但目前无法访问首页元素,确认是跨域问题。询问Karate UI是否支持跨域测试,若支持该如何实现。
解决方法
Karate UI完全支持跨域测试,通过配置Chrome浏览器启动参数即可解决,具体步骤如下:
- 添加跨域相关浏览器启动参数
在configure driver中补充Chrome的跨域禁用参数,修改后的配置如下:
Given configure driver = { type: 'chrome', addOptions: [ "--remote-allow-origins=*", "--disable-web-security", "--allow-running-insecure-content", "--disable-site-isolation-trials" ], port: 9515, executable: 'C://Program Files//Google//Chrome//Application//chrome.exe' }
--disable-web-security:禁用浏览器的同源策略,允许跨域访问--allow-running-insecure-content:允许从HTTPS页面加载HTTP内容(适用于混合内容场景)--disable-site-isolation-trials:禁用站点隔离,避免跨域页面的隔离限制
- 优化测试代码中的冗余操作
原代码中手动指定跳转首页的driver 'https://web.pr360b.sfbu.acpt.intgfanniemae.com/#/home'属于冗余操作,登录后页面会自动跳转,应改为等待跳转完成,同时替换delay为更可靠的waitFor操作:
Feature: Test Senetel Webapp Scenario: Login with incorrect credentials Given configure driver = { type: 'chrome', addOptions: [ "--remote-allow-origins=*", "--disable-web-security", "--allow-running-insecure-content", "--disable-site-isolation-trials" ], port: 9515, executable: 'C://Program Files//Google//Chrome//Application//chrome.exe' } When driver 'https://fmsso-acpt.fanniemae.com/' And driver.maximize() And input("#username","d33k4cnt") And input("#password","Dec_2023") And click("//a[@id='signOnButton']") # 等待登录后跳转的首页URL,无需手动打开 And waitForUrl("https://web.pr360b.sfbu.acpt/#", 15000) # 等待首页元素加载完成,替代固定delay And waitFor('//*[@id="home-page-element"]', 10000)
- 去掉不必要的
delay,改用waitForUrl和waitFor等待元素/URL,提升测试稳定性 - 避免手动跳转已自动导航的页面,符合真实用户操作流程
内容的提问来源于stack exchange,提问作者Haseeb Urrahman
相关产品推荐
相关产品推荐

