概觀

為了使用 Nightwatch 執行行動應用程式測試,需要安裝一些東西

  1. Appium
  2. 命令列工具
  3. 各平台的 SDK
  4. 虛擬裝置

但是,Nightwatch 透過 Mobile Helper 工具簡化了所有這些設定。

Mobile Helper Github

設定新專案

當您執行時

npm init nightwatch <directory-name>

第一個呈現的問題會是

? Select testing type to setup for your project (Press <space> 
to select,<a> to toggle all,<i> to invert selection,and 
<enter> to proceed)
❯◯ End-to-End testing
 ◯ Component testing
 ◉ Mobile app testing

請確保已選取「行動應用程式測試」。其餘的將是一系列您必須完成的問題/步驟,而 Nightwatch 將會執行安裝所有必要項目的繁重工作,或在需要時提供指示。

如果您計畫只進行行動應用程式測試,您也可以使用指令以應用程式模式啟動 Nightwatch 安裝

npm init nightwatch@latest <foldername> -- --app 

如果您選擇 Android,則需要注意 1 個重點。只有在您未安裝 SDK 時才選取預設選項,以避免重複下載 SDK。如果您已安裝 SDK,請在出現此問題時提供路徑

? Where do you want the Android SDK setup? Please give the path 
to your existing setup (if any): 
(/Users/vishal/Library/Android/sdk) 

就是這樣。Nightwatch 行動應用程式測試的設定已完成!

將行動應用程式測試新增至現有專案

Android

步驟 1
前往 Nightwatch 專案目錄並執行下列指令

npx @nightwatch/mobile-helper android --appium

步驟 2
根據您的需求回答問題。

如果您選擇 Android,則需要注意 1 個重點。只有在您未安裝 SDK 時才選取預設選項,以避免重複下載 SDK。如果您已安裝 SDK,請在出現此問題時提供路徑

? Where do you want the Android SDK setup? Please give the path 
to your existing setup (if any): 
(/Users/vishal/Library/Android/sdk) 
s

步驟 3
驗證後,如果未滿足所有需求或發生錯誤,請依照指示解決它們。

步驟 4
接下來,使用下列指令在您的專案中設定 Appium 2。

npm i appium@next --save-dev

步驟 5
為 Android 安裝 Appium UiAutomator2 驅動程式

npx appium driver install uiautomator2

步驟 6
下載範例 wikipedia 應用程式,並將其儲存在您專案的根目錄中 (與 nightwatch.conf.js 檔案並排)。

步驟 7 為 Android 模擬器和真實裝置新增 Nightwatch 環境。

nightwatch.conf.json
{
    ...
    'test_settings':{
        app: {
            selenium: {
                start_process: true,
                use_appium: true,
                host: 'localhost',
                port: 4723,
                server_path: '',
                // args to pass when starting the Appium server
                cli_args: [
                // automatically download the required chromedriver
                // '--allow-insecure=chromedriver_autodownload'
                ],
                // Remove below line if using Appium v1
                default_path_prefix: ''
            },
            webdriver: {
                timeout_options: {
                timeout: 150000,
                retry_attempts: 3
                },
                keep_alive: false,
                start_process: false
            }
        },
        'app.android.emulator': {
            extends: 'app',
            'desiredCapabilities': {
                // More capabilities can be found at https://github.com/appium/appium-uiautomator2-driver#capabilities
                browserName: null,
                platformName: 'android',
                // `appium:options` is not natively supported in Appium v1,but works with Nightwatch.
                // If copying these capabilities elsewhere while using Appium v1,make sure to remove `appium:options`
                // and add `appium:` prefix to each one of its capabilities,e.g. change 'app' to 'appium:app'.
                'appium:options': {
                automationName: 'UiAutomator2',
                // Android Virtual Device to run tests on
                avd: 'nightwatch-android-11',
                // While Appium v1 supports relative paths,it's more safe to use absolute paths instead.
                // Appium v2 does not support relative paths.
                app: `${__dirname}/wikipedia.apk`,
                appPackage: 'org.wikipedia',
                appActivity: 'org.wikipedia.main.MainActivity',
                appWaitActivity: 'org.wikipedia.onboarding.InitialOnboardingActivity',
                // chromedriver executable to use for testing web-views in hybrid apps.
                // add '.exe' at the end below (making it 'chromedriver.exe') if testing on windows.
                chromedriverExecutable: `${__dirname}/chromedriver-mobile/chromedriver`,
                newCommandTimeout: 0
                }
            }
        },
        'app.android.real': {
            extends: 'app',
            'desiredCapabilities': {
                // More capabilities can be found at https://github.com/appium/appium-uiautomator2-driver#capabilities
                browserName: null,
                platformName: 'android',
                // `appium:options` is not natively supported in Appium v1,but works with Nightwatch.
                // If copying these capabilities elsewhere while using Appium v1,make sure to remove `appium:options`
                // and add `appium:` prefix to each one of its capabilities,e.g. change 'app' to 'appium:app'.
                'appium:options': {
                    automationName: 'UiAutomator2',
                    // While Appium v1 supports relative paths,it's more safe to use absolute paths instead.
                    // Appium v2 does not support relative paths.
                    app: `${__dirname}/nightwatch/sample-apps/wikipedia.apk`,
                    appPackage: 'org.wikipedia',
                    appActivity: 'org.wikipedia.main.MainActivity',
                    appWaitActivity: 'org.wikipedia.onboarding.InitialOnboardingActivity',
                    // 'chromedriver' binary is required while testing hybrid mobile apps.
                    // 
                    // Set `chromedriverExecutable` to '' to use binary from `chromedriver` NPM package (if installed).
                    // Or,put '--allow-insecure=chromedriver_autodownload' in `cli_args` property of `selenium`
                    // config (see 'app' env above) to automatically download the required version of chromedriver
                    // (delete `chromedriverExecutable` capability below in that case).
                    chromedriverExecutable: '',
                    newCommandTimeout: 0,
                    // add device id of the device to run tests on,if multiple devices are online
                    // Run command: `$ANDROID_HOME/platform-tools/adb devices` to get all connected devices
                    // udid: '',
                }
            }
        },
    }
}

步驟 8nightwatch/examples/mobile-app-tests/wikipedia-android.js 檔案下新增下列範例測試檔案

nightwatch/examples/mobile-app-tests/wikipedia-android.js

describe('Wikipedia Android app test',function(){
    before(function(app) {
        app.click('id','org.wikipedia:id/fragment_onboarding_skip_button');
    });
    it('Search for BrowserStack',async function(app) {
        app
            .click('id','org.wikipedia:id/search_container')
            .sendKeys('id','org.wikipedia:id/search_src_text','browserstack')
            .click({selector: 'org.wikipedia:id/page_list_item_title',locateStrategy: 'id',index: 0})
            .waitUntil(async function() {
                // wait for webview context to be available
                const contexts = await this.appium.getContexts();
                
return contexts.includes('WEBVIEW_org.wikipedia'); }) .appium.setContext('WEBVIEW_org.wikipedia') .assert.textEquals('.pcs-edit-section-title','BrowserStack'); // command run in webview context }); });

完成!🎉 您的 Android 設定現在已完成。

iOS

步驟 1
前往 Nightwatch 專案目錄並執行下列指令

npx @nightwatch/mobile-helper ios --setups

步驟 2
根據您的需求回答問題。

步驟 3
驗證後,如果未滿足所有需求或發生錯誤,請依照指示解決它們。

步驟 4
之後,使用下列指令在您的專案中設定 Appium 2

npm i appium@next --save-dev

步驟 5
使用下列指令為 iOS 安裝 Appium XCUITest 驅動程式

npx appium driver install xcuitest

步驟 6
下載範例 wikipedia 應用程式,並將其儲存在您專案的根目錄中 (與 nightwatch.conf.js 檔案並排)。

步驟 7 為 iOS 模擬器和真實裝置新增 Nightwatch 環境

nightwatch.conf.json
{
    ...
    'test_settings':{
        // other envs above this line
        app: {
            selenium: {
                start_process: true,
                use_appium: true,
                host: 'localhost',
                port: 4723,
                server_path: '',
                // args to pass when starting the Appium server
                cli_args: [
                // automatically download the required chromedriver
                // '--allow-insecure=chromedriver_autodownload'
                ],
                // Remove below line if using Appium v1
                default_path_prefix: ''
            },
            webdriver: {
                timeout_options: {
                timeout: 150000,
                retry_attempts: 3
                },
                keep_alive: false,
                start_process: false
            }
        },
        
'app.ios.simulator': { extends: 'app', 'desiredCapabilities': { // More capabilities can be found at https://github.com/appium/appium-xcuitest-driver#capabilities browserName: null, platformName: 'ios', // `appium:options` is not natively supported in Appium v1,but works with Nightwatch. // If copying these capabilities elsewhere while using Appium v1,make sure to remove `appium:options` // and add `appium:` prefix to each one of its capabilities,e.g. change 'app' to 'appium:app'. 'appium:options': { automationName: 'XCUITest', // platformVersion: '15.5', deviceName: 'iPhone 13', // While Appium v1 supports relative paths,it's more safe to use absolute paths instead. // Appium v2 does not support relative paths. app: `${__dirname}/wikipedia.zip`, bundleId: 'org.wikimedia.wikipedia', newCommandTimeout: 0 } } },
'app.ios.real': { extends: 'app', 'desiredCapabilities': { // More capabilities can be found at https://github.com/appium/appium-xcuitest-driver#capabilities browserName: null, platformName: 'ios', // `appium:options` is not natively supported in Appium v1,but works with Nightwatch. // If copying these capabilities elsewhere while using Appium v1,make sure to remove `appium:options` // and add `appium:` prefix to each one of its capabilities,e.g. change 'app' to 'appium:app'. 'appium:options': { automationName: 'XCUITest', // While Appium v1 supports relative paths,it's more safe to use absolute paths instead. // Appium v2 does not support relative paths. app: `${__dirname}/wikipedia.zip`, bundleId: 'org.wikimedia.wikipedia', newCommandTimeout: 0, // add udid of the device to run tests on. Or,pass the id to `--deviceId` flag when running tests. // device id could be retrieved from Xcode > Window > 'Devices and Simulators' window. // udid: '00008030-00024C2C3453402E' } } }, } }

步驟 8nightwatch/examples/mobile-app-tests/wikipedia-ios.js 檔案下新增下列範例測試檔案

nightwatch/examples/mobile-app-tests/wikipedia-ios.js
describe('Wikipedia iOS app test',function() {
    before(function(app) {
        app.click('xpath','//XCUIElementTypeButton[@name="Skip"]');
    });
    it('Search for BrowserStack',async function(app) {
        app
            .useXpath()
            .click('//XCUIElementTypeSearchField[@name="Search Wikipedia"]')
            .sendKeys('//XCUIElementTypeSearchField[@name="Search Wikipedia"]','browserstack')
            .click('//XCUIElementTypeStaticText[@name="BrowserStack"]')
            .waitUntil(async function() {
            // wait for webview context to be available
            const contexts = await this.appium.getContexts();
            
return contexts.length > 1; },5000) .perform(async function() { // switch to webview context const contexts = await this.appium.getContexts();
await this.appium.setContext(contexts[1]); }) .useCss() .assert.textEquals('.pcs-edit-section-title','BrowserStack'); // command run in webview context }); });

恭喜,您的 iOS 設定已完成

驗證設定

安裝完成後,使用下列指令驗證設定,以在 Android 模擬器上執行範例測試

npx nightwatch nightwatch/examples/mobile-app-tests/wikipedia-android.js --env app.android.emulator

或使用下列指令在 iOS 模擬器上執行

npx nightwatch./nightwatch/examples/mobile-app-tests/wikipedia-ios.js --env app.ios.simulator

安裝 Appium Inspector

Appium Inspector 對於識別選取器和除錯測試非常有用。為了安裝 Appium Inspector,請前往 Appium Inspector 發行並下載最新版本。安裝後,只需開啟 Appium Inspector,即可開始使用。以下是應用程式在 Mac 上的外觀。

Appium Inspector

現在您了解行動應用程式測試如何與 Nightwatch 搭配使用,讓我們深入探討設定。我們建議您涵蓋以下列出的所有主題,以完整了解如何使用 Nightwatch 進行行動應用程式自動化測試。

撰寫測試以自動化原生應用程式
在虛擬裝置、真實裝置和雲端供應商上執行測試
除錯測試