如何在分度規中獲取文本並置2個字符串


0

我有2個獲取文本的變量: locationDisplayed bindisplayed 。我想要第三個變量: expectedDescription 合併前兩個變量的文本。這是代碼:

let locationDisplayed = element(by.css('.badge-primary')).getText().then(function (text) {

        }); //location to be compared with Destination field

        let bindisplayed = element(by.css('.badge-info')).getText().then(function (text) {

        }); //bin to be compared with Destination field

        let expectedDescription = locationDisplayed + " "+bindisplayed;
        expectedDescription.getText().then(function(text){
            console.log(text);

        });

但是後來我得到了:ExpectedDescription.getText不是一個函數任何人都知道如何合併2個字符串,並獲得此串聯的字符串?

0

Function getText() could be called on a DOM element (https://www.protractortest.org/#/api?view=webdriver.WebElement.prototype.getText), but you're using this function on a string. That won't work.

If you just want to concatenate expectedDescription and locationDisplayed, you've actually done that already on this line: let expectedDescription = locationDisplayed + " "+bindisplayed;

Another way might be to use str.concat() function (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat).


1

I think you forgot the fact that everything is a promise in protractor.

In your code, you are not waiting for the promise to be resolved.

There are two ways :

First: Using await

Add the below line in your config file:

 SELENIUM_PROMISE_MANAGER: false

Then rewrite the code as below:

    let locationDisplayed = await element(by.css('.badge-primary')).getText()

    let bindisplayed = await element(by.css('.badge-info')).getText()

    let expectedDescription = locationDisplayed + " "+bindisplayed;

    console.log(text);

Here, the await ensures that the promise is resolved before it goes to the next line else each line will act asynchronously.

Second: Chaining promise

element(by.css('.badge-primary')).getText().then(function (locationDisplayed ) {

    element(by.css('.badge-info')).getText().then(function (bindisplayed ) {
    console.log(locationDisplayed+bindisplayed);
   });      

  });

The second option works only if the script has enough time for the call back to resolve. Try using await browser.sleep(3000) at the end