Skip to content

Instantly share code, notes, and snippets.

@daisy1754
Created December 17, 2013 09:23
Show Gist options
  • Save daisy1754/8002254 to your computer and use it in GitHub Desktop.
Save daisy1754/8002254 to your computer and use it in GitHub Desktop.
Selenium WebDriverとJSCoverを組み合わせて使うサンプル
/**
* Selenium WebDriverを使ってテストしてるときに,JSCoverによってテスト対象のJavaScriptのカバレッジを測定する
*/
class MyAwesomeTest {
private static Thread server;
private static WebDriver driver = getInstrumentedDriver();
// JSCover起動用オプション
// 3129ポートを利用してプロキシとして起動する
private String[] args = new String[]{
"-ws",
"--port=3129",
"--proxy",
"--local-storage",
// カバレッジ測定除外設定,今回はjquery関係のファイルは無視
"--no-instrument-reg=.*jquery.*",
"--report-dir=" + getReportDir()
};
protected String[] getArgs() {
return args;
}
@Before
public void setUp() throws IOException {
File jsonFile = new File("js-cover-report/jscoverage.json");
if (jsonFile.exists())
jsonFile.delete();
// プロキシサーバの遅延初期化
if (server == null) {
server = new Thread(new Runnable() {
public void run() {
try {
Main.main(getArgs());
} catch (IOException e) {
throw new RuntimeException("Err", e);
}
}
});
server.start();
}
}
// JSCoverプロキシを利用する用設定したFirefoxDriverインスタンスの取得
public static WebDriver getInstrumentedDriver() {
Proxy proxy = new Proxy().setHttpProxy("localhost:3129");
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);
return new FirefoxDriver(cap);
}
protected String getReportDir() {
return "js-cover-report";
}
@Test
public void awesomeTestAndSaveJSCoverage() {
driver.get("http://localhost/your_test_target");
/* 何かしらのテスト */
// JSCoverのカバレッジ一覧ページを開く
driver.get("http://localhost/jscoverage.html");
// 画面を自動で操作して"Store Report"ボタンを押下,カバレッジ測定結果を記録する
new WebDriverWait(driver, /* 最大2秒待つ,この値は適当 */ 2).until(
ExpectedConditions.elementToBeClickable(By.id("storeTab"))).click();
new WebDriverWait(driver, 2).until(
ExpectedConditions.elementToBeClickable(By.id("storeButton"))).click();
new WebDriverWait(driver, 2).until(
ExpectedConditions.textToBePresentInElement(By.id("storeDiv"), "Coverage data stored at"));
// 測定結果をWebDriverで開く
driver.get("file:///" + new File(getReportDir() + "/jscoverage.html").getAbsolutePath());
// この先は人間が見てもいいし,WebDriverを使ってさらに自動化しても良い
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment