Protractor でブラウザのウインドウの制御をする
目的
Protractor を使って UI のテスト時に、ブラウザのウインドウの制御をしたい。
ケース例
あるリンクボタンを押したら、別ウインドウを開く。その時、その開かれたタブ画面の URL とコンテンツの確認をする。確認が終わったらウインドウを閉じる。
書き方
describe('テスト', function() {
it('リンクボタンをクリックしたら別タブを開くよ', function() {
// given
browser.get('http://localhost:5000/#/hoge');
browser.waitForAngular();
// when
element(by.id('sample-link')).click();
// then
browser.getAllWindowHandles().then(function (handles) {
var newWindowHandle = handles[1];
// 開いた別ウインドウに移動
browser.switchTo().window(newWindowHandle).then(function () {
// 開いたウインドウの URL チェック
expect(browser.driver.getCurrentUrl()).toBe('http://testtest.com');
// 開いたウインドウ内のアサーションとか
element(by.id('testdayo')).getText().then(function(data) {
expect(data).toEqual('わっしょい');
});
// テストが終わったら別ウインドウを閉じて、もとのウインドウに戻る
browser.driver.close().then(function () {
browser.switchTo().window(handles[0]);
});
});
});
新規にタブを開く
describe('テスト', function() {
it('新規にタブを開くよ', function() {
// given
browser.get('http://localhost:5000/#/hoge');
browser.waitForAngular();
// when
browser.actions()
.sendKeys(protractor.Key.chord(protractor.Key.CONTROL, protractor.Key.SHIFT ,"n"))
.perform();
// then
browser.getAllWindowHandles().then(function (handles) {
var newWindowHandle = handles[1];
// 開いた別ウインドウに移動
browser.switchTo().window(newWindowHandle).then(function () {
// URL を指定して開く
browser.get('http://testtest.com');
// 開いたウインドウの URL チェック
expect(browser.driver.getCurrentUrl()).toBe('http://testtest.com');
// 開いたウインドウ内のアサーションとか
element(by.id('testdayo')).getText().then(function(data) {
expect(data).toEqual('わっしょい');
});
// テストが終わったら別ウインドウを閉じて、もとのウインドウに戻る
browser.driver.close().then(function () {
browser.switchTo().window(handles[0]);
});
});
});