2016-11-21 5 views
0

ジャスミンを使用してTypescriptでスパイを使用する方法を理解しようとしています。私は、メソッド作成したジャスミンを使用してTypescriptのスパイを理解する

describe("A spy", function() { 
    var foo, bar = null; 

    beforeEach(function() { 
    foo = { 
     setBar: function(value) { 
     bar = value; 
     } 
    }; 

    spyOn(foo, 'setBar').and.callThrough(); 
    }); 

    it("can call through and then stub in the same spec", function() { 
    foo.setBar(123); 
    expect(bar).toEqual(123); 

    foo.setBar.and.stub(); 
    bar = null; 

    foo.setBar(123); 
    expect(bar).toBe(null); 
    }); 
}); 

スパイを使用するには:

export class HelloClass { 
    hello() { 
     return "hello"; 
    } 
} 

を、私はそれをスパイしようとしています:私はthis documentation and this example発見した

import { HelloClass } from '../src/helloClass'; 

describe("hc", function() { 
    var hc = new HelloClass(); 

    beforeEach(function() { 
    spyOn(hc, "hello").and.throwError("quux"); 
    }); 

    it("throws the value", function() { 
    expect(function() { 
     hc.hello 
    }).toThrowError("quux"); 
    }); 
}); 

を、それは、その結果:

[17:37:31] Starting 'compile'... 
[17:37:31] Compiling TypeScript files using tsc version 2.0.6 
[17:37:33] Finished 'compile' after 1.9 s 
[17:37:33] Starting 'test'... 
F....... 
Failures: 
1) Calculator throws the value 
1.1) Expected function to throw an Error. 

8 specs, 1 failure 
Finished in 0 seconds 
[17:37:33] 'test' errored after 29 ms 
[17:37:33] Error in plugin 'gulp-jasmine' 
Message: 
    Tests failed 

答えて

0

あなたは実際にはhc.helloを呼び出すことはありません。したがって、決して投げられません。

テストとしてこれを試してみてください:ここで何が起こっている

it("throws the value", function() { 
    expect(hc.hello).toThrowError("quux"); 
}); 

expect(...).toThrowErrorは、呼び出されたときに、エラーがスローされます機能を期待されていることです。私はあなたがこれを知っていたと確信していますが、関数内で括弧を打ち切ったという事実に巻き込まれたばかりです。

関連する問題