2016-09-08 7 views
1

私は、プロトラクターからブラウザのメモリ値を読み込み、それらをグローバルオブジェクトに格納しようとしています。これを行うために、私はwindow.performance.memoryオブジェクトを取得して、各メモリ値を検査する約束を解決します。プロミスから返された値をグローバル変数に割り当てます

問題は、グローバル変数に値を割り当てることができないようです。私はかなりうまく動作していないように次のコードを、試してみた:

this.measureMemory = function() { 

    var HeapSizeLimit; 

    browser.driver.executeScript(function() { 
     return window.performance.memory; 
    }).then(function (memoryValues) { 
     HeapSizeLimit = memoryValues.jsHeapSizeLimit; 
     console.log('Variable within the promise: ' + HeapSizeLimit); 
    }); 
    console.log('Variable outside the promise: ' + HeapSizeLimit); 
}; 

はこれが返されます。

Variable outside the promise: undefined 
    Variable within the promise: 750780416 
+3

あなたは確かに '約'関数の中で約束の外の値に割り当てることができますが、 'then'関数が実際に実行された後に*時間順に設定することはできません。 – apsillers

+0

おかげさまで@apillers。この説明は、問題の内容を理解するのに非常に役立ちました。 – Tedi

答えて

4

console.log('Variable outside the promise: ' + HeapSizeLimit);HeapSizeLimit = memoryValues.jsHeapSizeLimit;前に実行されるため。それが約束の後の行にある場合、実行順序が同じであるとは限りません。あなたのテストで

+0

問題を理解していただきありがとうございます。 – Tedi

1
// a variable to hold a value 
var heapSize; 

// a promise that will assign a value to the variable 
// within the context of the protractor controlFlow 
var measureMemory = function() { 
    browser.controlFlow().execute(function() { 
     browser.driver.executeScript(function() { 
      heapSize = window.performance.memory.jsHeapSizeLimit; 
     }); 
    }); 
}; 

// a promise that will retrieve the value of the variable 
// within the context of the controlFlow 
var getStoredHeapSize = function() { 
    return browser.controlFlow().execute(function() { 
     return heapSize; 
    }); 
}; 

it('should measure the memory and use the value', function() { 
    // variable is not yet defined 
    expect(heapSize).toBe(undefined); 
    // this is deferred 
    expect(getStoredHeapSize).toBe(0); 

    // assign the variable outside the controlFlow 
    heapSize = 0; 
    expect(heapSize).toBe(0); 
    expect(getStoredHeapSize).toBe(0); 

    // assign the variable within the controlFlow 
    measureMemory(); 

    // this executes immediately 
    expect(heapSize).toBe(0); 
    // this is deferred 
    expect(getStoredHeapSize).toBeGreaterThan(0); 
}; 

価値は何も:あなたの変数を設定し、値を取得するには(分度器テスト内の延期の実行を経由して)同期(controlFlow外)または非同期的に起こるように見えることはできません。

+0

私はそれを以前の値と比較するために使用できるグローバル変数として必要とします。 – Tedi

+0

私はこの解決法を試しましたが、それは次の結果を返します: '0は0より大きいと予想されます。 – Tedi

関連する問題