簡體   English   中英

在無頭Chrome中針對Angular應用程序運行Selenium測試

[英]Run Selenium tests against an Angular application in headless Chrome

我正在嘗試針對Angular應用程序創建Selenium測試。 我希望這些測試能在我的連續集成版本中運行,因此有必要以無頭模式運行它們。 我正在嘗試使用無頭Chrome。

我創建了兩個簡單的Selenium測試。 一個測試訪問我的本地Angular應用程序,另一個測試訪問Google。 當我使用Chrome GUI運行它們時,它們都可以完美運行,但是當我切換到無頭Chrome時,Angular測試失敗。

我在Angular測試中打印出頁面源,使用Chrome GUI時,所有HTML都可以正確顯示,但是當我切換為無頭時,頁面源僅顯示空的headbody標簽。

為什么會發生這種情況,我該如何解決?

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ExampleSeleniumTest {

    @LocalServerPort
    private int port;

    @Autowired
    private WebDriver driver;

    @Test // Always works
    public void testGoogle() {
        driver.get("http://www.google.com");
        WebElement element = driver.findElement(By.name("q"));
        element.sendKeys("Cheese!");
        element.submit();

        List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));

        for (WebElement webElement : findElements) {
            System.out.println(webElement.getAttribute("href"));
        }
        Assert.assertTrue(findElements.size > 0);
    }


    @Test // Breaks in headless mode
    public void testLocalAngular() {
        driver.get("localhost:" + port);
        String pageSource = driver.getPageSource();
        // Page source empty in headless mode
        System.out.println(pageSource);
        String title = driver.findElement(By.className("mat-card-title")).getText();
        Assert.assertEquals("My Starter", title);
    }
} 

這些測試取決於以下配置

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@ComponentScan(basePackageClasses = MyStarterApplication.class)
public class SeleniumConfig {

    @Value("${selenium.headless:#{true}}")
    private boolean headless;   

    @EventListener(classes = ApplicationReadyEvent.class)
    public void prepareDriver() {
        // Using https://github.com/bonigarcia/webdrivermanager
        ChromeDriverManager.getInstance().setup();
    }

    @Bean(destroyMethod = "quit")
    public WebDriver webDriver() {
        ChromeOptions options = new ChromeOptions();
        if (headless) {
            options.addArguments("headless");
            options.addArguments("window-size=1200x600");
        }
        WebDriver driver = new ChromeDriver(options);
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        return driver;
    }

}

該問題是由以下原因引起的:

driver.get("localhost:" + port);

我需要指定協議。 如果使用以下命令,我的測試用例將起作用:

driver.get("http://localhost:" + port);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM