2016-11-21 75 views
0

我想了解如何在使用Jasmine的Typescript中使用Spies。我發現this documentation and this example使用Jasmine在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"; 
    } 
} 

,我試圖窺探它:

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期待的是,在被調用時,會拋出異常的函數。我確信你知道這一點,但是剛剛陷入了這個事實,那就是你在功能上留下了遺物。