因爲測試資源緊張,以及人工測試覆蓋率有限。爲了規避因改動代碼而產生新的bug,最近項目要加自動化測試。通過組內有經驗的大哥介紹。推薦了今天的主角nightwatch.js。node
官網是這麼介紹的:git
Nightwatch.js is an automated testing framework for web applications and websites, written in Node.js and using the W3C WebDriver API (formerly Selenium WebDriver).github
It is a complete End-to-End testing solution which aims to simplify writing automated tests and setting up Continuous Integration. Nightwatch can also be used for writing Node.js unit and integration tests.web
大概意思是:Nightwatch.js是一個用於Web應用程序和網站的自動化測試框架,使用Node.js編寫並使用W3C WebDriver API(之前稱爲Selenium WebDriver)。chrome
它是一個完整的瀏覽器(端到端)測試解決方案,旨在簡化設置持續集成和編寫自動化測試的過程。 Nightwatch也可用於編寫Node.js單元測試。npm
首先要安裝相關依賴json
const chromedriverPath = require('chromedriver').path module.exports = { "src_folders" : ["test/e2e/specs"], "webdriver" : { "start_process": true, "server_path": chromedriverPath, "port": 9515, "log_path" : "test/e2e/reports" }, "test_settings" : { "default" : { "desiredCapabilities": { "browserName": "chrome", "chromeOptions": { "args": [ "--headlessss" ] } } } } }
測試代碼test/e2e/specs目錄下的***_specs.js。可支持多種的斷言風格。從 Nightwatch0.7 版本開始, 引入了新的 BDD風格的斷言庫,大大提高了靈活性和代碼的可讀性。
expect 斷言是 chai 框架 expect api 的子集,在此對元素類型也能使用。我僅僅用百度首頁作個測試例子。windows
const testUrl = 'https://www.baidu.com/' module.exports = { 'test for baidu' : function (browser) { browser .url(testUrl) .waitForElementVisible('body', 3000) .setValue('input[id=kw]', 'nightwatch') .waitForElementVisible('input[type=submit]', 1000) .click('input[type=submit]') .pause(1000) .waitForElementVisible('div[class=s_tab_inner]', 3000) .assert.containsText('.s_tab_inner', '網頁') .end(); } };
啓動測試 packae.jsonapi
"scripts": { "test": "nightwatch -c test/e2e/nightwatch.conf.js", "build": "node build/build.js" },
在項目根目錄下執行npm test便可。它會模擬界面操做,打開瀏覽器執行。控制檯信息以下。瀏覽器