2016-04-29 113 views
2

這可能有一個簡單的解決方案,但我只是沒有看到它。我正在寫一個量角器測試和設置頁面對象文件獲取「無法讀取屬性'[方法]'未定義」

newstate.js(頁面目標文件)

'use strict'; 

var newstate = function (url) { 
    browser.get(url); 
}; 

newstate.prototype = Object.create({}, { 
    dd: { select: function(state) { $('select option[value="'+state+'"]').click(); } } 
}); 

module.exports = newstate; 

的spec.js文件:

'use strict'; 

var newstate = require('newstate.js'); 

describe('Testing newstate', function() { 
    var statePage; 
    beforeAll(function() { 
     statePage = new newstate('http://localhost:8080'); 
    }); 

    it('should select a state', function() { 
     statePage.dd.select('AK'); 
    }) 
}) 

的conf.js文件:

exports.config = { 
    framework: 'jasmine', 
    specs: ['test-spec.js'], 
    useAllAngular2AppRoots: true, 
    jasmineNodeOpts: { 
     showColors: true 
    } 
}; 

當我運行量角器,我得到:

$ protractor conf.js 
Failures: 
1) Testing newstate should select a state 
    Message: 
    Failed: Cannot read property 'select' of undefined 

它啓動瀏覽器,打開網頁,就像它應該當我打電話給new newstate('...')但由於某種原因,它不想看到我的dd.select功能。我錯過了什麼或做錯了什麼?謝謝。

+1

作爲一個編碼約定,最好將構造函數聲明爲'function Newstate(...)' – OrangeDog

回答

2

您使用的方式Object.create不正確。你的情況正確的符號是:

var newstate = function (url) { 
    browser.get(url); 
}; 

newstate.prototype = Object.create({ 
    dd: { select: function(state) { $('select option[value="'+state+'"]').click(); } } 
}); 

爲什麼selectdd對象上未定義的原因是,第二個參數Object.createproperty descriptor object,不僅僅是屬性的對象喜歡你提供。

但是,在你的情況下,你根本不需要Object.create,因爲newstate.prototype.dd = function() { /*...*/ }就足夠了。

+0

我實際上有很多函數可以放入原型中。你會建議哪種方法最好? 'newstate.prototyp.dd = ...'或使用'Object.create()'方法? – Machtyn

+1

在這種情況下最好不要使用Object.create,因爲它通常意味着設置繼承,而不僅僅是原型。所以在這裏沒有任何好處。我只是使用'newstate.prototype = {構造函數:newstate,dd:function(){},另一個:function(){},...}'。 'constructor:newstate'用於確保'newstate'的實例具有指向原始構造函數的構造函數屬性,但這可能並不重要。 – dfsq

相關問題