JS の使い方: Selenium を使用してテストを自動化する

WBOY
リリース: 2024-08-29 11:08:44
オリジナル
365 人が閲覧しました

How to JS: Automate testing with Selenium

JavaScript で Selenium を使用してブラウザ テストを自動化する方法

Web 開発者にとって、アプリケーションが正しく機能することを確認するには、自動化されたブラウザ テストが必須です。この投稿では、Web ページを開いてボタンをクリックするという単純なブラウザ タスクを自動化するために、JavaScript を使用して Selenium をセットアップする方法を説明します。

前提条件

この手順を進めるには、次のものが必要です:

  • Node.jsnpm がインストールされています。
  • Google ChromeChromeDriver がインストールされています (または別のブラウザーとそのドライバー)。

ステップ 1: プロジェクトをセットアップする

まず、プロジェクト用に新しいフォルダーを作成します。ターミナルを開いて次を実行します:

mkdir selenium-test
cd selenium-test
ログイン後にコピー

次に、新しい Node.js プロジェクトを初期化します。

npm init -y
ログイン後にコピー

このコマンドは、プロジェクトの依存関係を追跡する package.json ファイルを生成します。

ステップ 2: Selenium WebDriver をインストールする

npm を使用して Selenium WebDriver と ChromeDriver をインストールします。

npm install selenium-webdriver chromedriver --save
ログイン後にコピー

これらのパッケージは、Selenium で Chrome を自動化するために必要なライブラリとツールを提供します。

ステップ 3: Selenium スクリプトを作成する

プロジェクト フォルダーに test.js という名前の新しいファイルを作成します。このスクリプトは Web ページを開き、ボタンがクリック可能になるのを待ってからクリックします。

const { Builder, By, until } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

// Helper function to pause the script
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function runTest() {
  // Configure Chrome to suppress unwanted prompts
  let options = new chrome.Options();
  options.addArguments('--no-default-browser-check', '--no-first-run', '--disable-default-apps', '--disable-infobars');

  let driver = await new Builder()
    .forBrowser('chrome')
    .setChromeOptions(options)
    .build();

  try {
    // Open the target webpage
    await driver.get('https://example.com'); // Change this URL to the site you want to test

    // Wait for an element to load
    await driver.wait(until.elementLocated(By.className('sample-class')), 10000);
    console.log('Found element with class "sample-class".');

    // Generic wait for 6 seconds to handle any dynamic content
    await sleep(6000);

    // Wait for the button to be clickable
    await driver.wait(until.elementLocated(By.id('sample-button')), 10000);

    // Re-locate the button to ensure it’s still in the DOM
    let button = await driver.findElement(By.id('sample-button'));
    console.log('Button located:', button);

    // Click the button
    await button.click();
    console.log('Button clicked successfully.');

    // Wait for the next page or action to load
    await driver.wait(until.urlContains('new-page'), 10000);
    console.log('Navigation to new page was successful.');

  } catch (error) {
    console.error('Error during the test:', error);
  } finally {
    // Always close the browser
    await driver.quit();
  }
}

runTest();
ログイン後にコピー

ステップ 4: スクリプトを実行する

スクリプトを実行するには、次のコマンドを実行します:

node test.js
ログイン後にコピー

Chrome が開き、スクリプトで定義されたアクションが実行されます。コンソールで各ステップの進行状況を示すログを確認してください。

トラブルシューティング

  • StaleElementReferenceError: これは、要素が見つかった後に DOM が変更されたときに発生します。これを回避するには、要素を操作する直前に要素を常に再配置してください。
  • タイムアウト: 要素のロードに時間がかかる場合は、driver.wait() のタイムアウトを増やします。

結論

これで、Selenium と JavaScript を使用した自動ブラウザ テストの基本的なセットアップが完了しました。この設定は、より複雑な操作、チェック、検証手順を含めるように簡単に拡張できます。

ブラウザのバージョンに合わせてドライバーを常に最新の状態に保ち、CI/CD 環境ではヘッドレス モードの使用を検討してください。

Azure でホストしたい場合は、私の他の投稿をチェックしてください: https://dev.to/iamrule/how-to-azure-host-a-selenium-javascript-node-application-in-azure-and -send-email-notifications-on-failures-2aio

テストをお楽しみください!

以上がJS の使い方: Selenium を使用してテストを自動化するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!