2016-09-23 150 views
1

我有幾個量角器/角度js它阻止重複我想放在函數中的同一位代碼。我只想調用這個函數,而不是一遍又一遍地重複這個。如何將嵌套函數中的變量傳遞給javascript

it('should move directly to Draft', function() { 
    posting_sum_page.locate_action_button.click(); 
    posting_action_page.move_action.filter(function(elem) { 
    return elem.getText().then(function(text) { 
     return text === 'Draft'; 
    }); 
    }).click(); 
}); 

這部分塊是我想創建函數的重複部分。我是新來的JavaScript,所以這是在我如何做到這一點。

return elem.getText().then(function(text) { 
     return text === 'Draft'; 
    }); 
    }).click(); 

我需要能夠用不同的變量替換'Draft'。我正在使用頁面對象的一部分,我不知道A)如何創建一個這樣的功能,並通過我的文字& B)如果它應該在規格端或頁面?這對大多數人來說可能是非常基本的。但是因爲我是JavaScript新手,所以我無法繞開這個問題。

回答

0

我會提取的整個過濾功能成「助手」模塊。

helpers.js:

var Helpers = function() { 
    this.filterByText = function (text) { 
     return function (elem) { 
      return elem.getText().then(function(actualText) { 
       return actualText === text; 
      }); 
     }; 
    } 
} 

module.exports = new Helpers(); 

使用測試:

var helpers = require("helpers"); 

describe("My Test", function() { 
    it('should move directly to Draft', function() { 
     posting_sum_page.locate_action_button.click(); 
     posting_action_page.move_action.filter(helpers.filterByText('Draft')).click(); 
    }); 
}); 
+0

感謝大家的意見。 alecxe您的解決方案效果最佳。非常感謝大家。 –

0

也許這樣?

describe('...something...', function() 
{ 
    var clickBtn; 


    beforeEach(function() 
    { 
    clickBtn = function(testText) 
    { 
     return posting_action_page.move_action.filter(function(elem) 
     { 
     return elem.getText().then(function(currentText) 
     { 
      return currentText === testText; 
     }); 
     }).click(); 
    }; 
    }); 


    it('should move directly to Draft', function() 
    { 
    posting_sum_page.locate_action_button.click(); 
    expect(clickBtn('Draft')).toEqual('...something...'); 
    }); 
}); 
0

如果你想返回塊重用只有

it('should move directly to' + targetText, function() { 
    posting_sum_page.locate_action_button.click(); 
    posting_action_page.move_action.filter(function(elem) { 
    checkSameText(elem, targetText); 
    }).click(); 
}); 

function checkSameText(el, targetText) { 
    return el.getText().then(function(text) { 
     return text === targetText; 
    }); 
} 
0

我不能確定什麼樣的頁面對象類型是posting_action_page.move_action但我認爲你正在尋找使用by.buttonText什麼或by.linkText

// html: <button>Draft</button> 
element(by.buttonText('Draft')).click(); 

// html: <a href="">Draft</button> 
element(by.linkText('Draft')).click(); 

還有其他定位器可能會有所幫助像by.partialButtonTextby.partialLinkText

相關問題