2016-04-16 8 views
0

私はカルマジャスミンを使用しており、Vueコンポーネントをテストするためにbrowserifyしています。 1つのメソッドは、ロードイベントでイメージをリッスンします。しかし、イベントハンドラで呼び出されたスパイは正しい結果を得ていませんでした。スニペットに続いて、エラーを示していますジャスミンのスパイが画像のロードイベントで機能しない

ここ
let spy = jasmine.createSpy('spy') 
spy.and.returnValues({ 
    name: 'name' 
}) 

describe('example tests',() => { 
    it('should pass', (done) => { 
    var img = new Image() 
    img.onload = function() { 
     console.log('2', spy()) 
     done() 
    } 
    img.src = "http://dummyimage.com/100x100" 
    console.log('1', spy()) 
    }) 
}) 

我々は、位置1で、ログショー1ですが、2位で、ログは未定義を示しています。

答えて

1

スパイに連鎖している.and.returnValues関数は、一度指定されたオブジェクト、all subsequent calls to the spy will return undefinedを返します。

次の操作を実行した場合:その後、2オブジェクト{名:「名2」}:

let spy = jasmine.createSpy('spy') 
spy.and.returnValues({ 
    name: 'name'}, 
{name: 'name2'} 
) 

describe('example tests',() => { 
    it('should pass', (done) => { 
    var img = new Image() 
    img.onload = function() { 
    console.log('2', spy()) 
    done() 
    } 
    img.src = "http://dummyimage.com/100x100" 
    console.log('1', spy()) 
    }) 
}) 

コンソールは、「{名1オブジェクト名を 『』}」ログに記録されますことがわかります。あなたは、常に同じオブジェクトを返すためにスパイをしたい場合は

あなたは.and.returnValuesではなく.and.returnValueを使用する必要があります。

let spy = jasmine.createSpy('spy') 
spy.and.returnValue({ 
    name: 'name'}) 

describe('example tests',() => { 
    it('should pass', (done) => { 
    var img = new Image() 
    img.onload = function() { 
    console.log('2', spy()) 
    done() 
    } 
    img.src = "http://dummyimage.com/100x100" 
    console.log('1', spy()) 
    }) 
}) 
関連する問題