簡體   English   中英

如何使用量角器中的函數重用另一個js文件中的代碼?

[英]How do I re-use code from another js file using function in protractor?

我有2個不同的js文件:abc.js和func_abc.js

以前,我將所有函數都寫在abc.js中,並從同一文件中調用它。 這樣沒有問題。

但是由於它越來越大,我正考慮將其管理在單獨的文件中,因為我也打算將其用於其他文件。

我不確定如何將我在func_abc.js中編寫的函數調用為abc.js

我嘗試使用export並要求,但是它說Title未定義。

文件func_abc.js:

function Title(title) {

    patient.titleselect.click().then(function () {
        element(by.cssContainingText('mat-option',title)).click().then(function () {
                console.log("Successfully select title");

            });
    });
};

function Gender(sex) {
     element(by.cssContainingText('mat-radio-button',sex)).click().then(function () {
     console.log("Successfully select gender");       
    })
};

文件abc.js:

it('Create new patient', function(){

    Title("Mr");
    Gender("M");
}

1)文件:func_abc.js

function Title(title) {

    patient.titleselect.click().then(function () {
        element(by.cssContainingText('mat-option',title)).click().then(function () {
                console.log("Successfully select title");

            });
    });
};

function Gender(sex) {
     element(by.cssContainingText('mat-radio-button',sex)).click().then(function () {
     console.log("Successfully select gender");       
    })
};

exports.Title = Title;
exports.Gender = Gender;

2)檔案:abc.js

const { Title, Gender } = require('./func_abc.js');

it('Create new patient', function(){

    Title("Mr");
    Gender("M");
}

除了@yong的答案外,建議使用頁面對象模式來更好地維護代碼。 除了直接導出方法外,還可以為應用程序中的各個頁面創建單獨的模塊,然后將類文件導出到相應的規范文件中。 查看下面的示例代碼。

ProfilePage.js

var profilePage = function() {

   this.Title = function(title) {
     element(by.cssContainingText('mat-option', title)).click().then(function(){
         console.log("Successfully select title");
     });
   }

   function Gender(sex) {
     element(by.cssContainingText('mat-radio-button',sex)).click().then(function () {
        console.log("Successfully select gender");       
     });
   };

}
module.exports = new profilePage();

spec.js

const profilePage = require('./profilePage.js');

it('Create new patient', function(){
   profilePage.Title("Mr");
   profilePage.Gender("M"); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM