2017-10-04 23 views
2

我正在使用茉莉花進行測試的項目。 我有一種方法不返回任何值,但它只是設置類屬性。我知道如何使用間諜方法返回一個值,但不知道如何在不返回任何值的方法上使用它。我在網上搜索,但找不到任何適當的資源。 和方法如下測試不返回任何值的方法(jasmine angular4)

updateDvStatus() { 
    this._http.get(this.functionControlUrl).subscribe(() => { 
    this._active = true; 
    }, (error) => { 
     this.errorStatusCode = error.status; 
     this.errorPageService.setStatusCode(this.errorStatusCode); 
    }) 
    } 

任何幫助,將不勝感激。

回答

1

如何測試不返回任何

下面的方法是檢測不返回任何一種方法的一個例子。

var serviceUnderTest = { 
    method: function() { 
    console.log('this function doesn't return anything'); 
    } 
}; 

it('should be called once', function() { 
    spyOn(serviceUnderTest, 'method'); 

    serviceUnderTest.method(); 

    expect(serviceUnderTest.method.calls.count()).toBe(1); 
    expect(serviceUnderTest.method).toHaveBeenCalledWith(); 
}); 

如何測試一個回調

我懷疑你真正的問題,雖然是測試要傳遞到subscribe()功能的功能做你的期望。如果是你真正要求的,那麼下面的內容可能會有所幫助(請注意,我把它寫在了我頭上,所以可能會有錯字)。

var serviceUnderTest = { 
    method: function() { 
    this.someOtherMethod(function() { this.active = true; }); 
    }, 
    someOtherMethod: function(func) { 
    func(); 
    } 
} 

it('should execute the callback, setting "active" to true', function() { 
    spyOn(serviceUnderTest, 'someOtherMethod'); 

    serviceUnderTest.method(); 

    expect(serviceUnderTest.someOtherMethod.calls.count()).toBe(1); 
    var args = serviceUnderTest.someOtherMethod.calls.argsFor(0); 
    expect(args.length).toBeGreaterThan(0); 
    var callback = args[0]; 
    expect(typeof callback).toBe('function'); 

    expect(serviceUnderTest.active).toBeUndefined(); 
    callback(); 
    expect(serviceUnderTest.active).toBe(true); 
}); 

您的方案

對不起,較舊的語法,我是從我的頭寫這個,所以我寧願它的工作,不是成爲很酷的,但有一些錯別字。另外,我還沒有使用過Observable,因此有可能有更好的方法來測試它們,而不是我將要展示給你的東西,這可能相當於創建一個新的Observable並監視訂閱。由於這是我的頭頂,我們將不得不做。

it('should subscribe with a function that sets _active to true', function() { 
    // Arrange 
    var observable = jasmine.createSpyObj('Observable', ['subscribe']); 
    spyOn(http, 'get').and.returnValue(observable); 

    // Act... (execute your function under test) 
    service.updateDvStatus(); 

    // Assert 
    expect(http.get.calls.count()).toBe(1); 
    expect(http.get).toHaveBeenCalledWith(service.functionControlUrl); 
    expect(observable.subscribe.calls.count()).toBe(1); 
    var args = observable.subscribe.calls.argsFor(0); 
    expect(args.length).toBeGreaterThan(0); 
    var callback = args[0]; 
    expect(typeof callback).toBe('function'); 

    service._active = false; 
    callback(); 
    expect(service._active).toBe(true); 
}); 
+0

碰到類似的問題。在問題中,函數定義不期望任何參數,它只是設置類屬性。有什麼方法可以測試這種情況嗎?你可以提供一個例子,如果這不是太多要求。 –

+0

以我的回調示例更新,但更貼近您的場景。 –