今天將介紹一款自動化測試套件名叫nightmare,他是一個基於phantomjs的測試框架,一個基於phantomjs之上為測試應用封裝的一套high level API。其API以goto, refresh, click, type…等簡單的常用e2e測試動作封裝,使得其語義清晰,簡潔。其官方在http://www.nightmarejs.org/.
如果你的項目測試不需要想需求和測試人員理解,那么基於nightmare測試或許是一個好的選擇,你的降低測試代碼的成本,以及測試套件的部署。我們可以選擇基於jasmine-node等作為測試套件集成。
安裝nightmare:
npm install nightmare
下面我們對比與遠程phantomjs的對比:
原phantomjs的代碼:
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open('http://yahoo.com', function (status) {
page.evaluate(function () {
var el =
document.querySelector('input[title="Search"]');
el.value = 'github nightmare';
}, function (result) {
page.evaluate(function () {
var el = document.querySelector('.searchsubmit');
var event = document.createEvent('MouseEvent');
event.initEvent('click', true, false);
el.dispatchEvent(event);
}, function (result) {
ph.exit();
});
});
});
});
});
nightmare代碼:
new Nightmare()
.goto('http://yahoo.com')
.type('input[title="Search"]', 'github nightmare')
.click('.searchsubmit')
.run();
一切顯而易見,不用多說。
nightmare同時也支持插件方式抽取公用邏輯,以供復用和提高測試代碼語意,如下例子:
/**
* Login to a Swiftly account.
*
* @param {String} email
* @param {String} password
*/
exports.login = function(email, password){
return function(nightmare) {
nightmare
.viewport(800, 1600)
.goto('https://swiftly.com/login')
.type('#username', email)
.type('#password', password)
.click('.button--primary')
.wait();
};
};
使用代碼很簡單:
var Swiftly = require('nightmare-swiftly');
new Nightmare()
.use(Swiftly.login(email, password))
.use(Swiftly.task(instructions, uploads, path))
.run();