2017-08-18 40 views
0

我想測試函數內多變的時間內變量的值。但是,每當我期望該變量的值時,它就是最新賦值的值。有沒有辦法檢查第一個值是什麼?Angular2單元測試 - 在函數中測試函數中的第一個變量值

這裏是我的TS碼:

public triggerLogin() { 
    this.loading = true; 
    this.requestsService.login(this.userEmail, this.password) 
     .subscribe(response => this.handleLogin(response)) 
    } 

    public handleLogin(response) { 
    if (_.isEqual(response, 'invalid')) { 
     this.invalid = true; 
    } else { 
     this.invalid = false; 
     this.tokenManager.store(response); 
    } 
    this.loading = false; 
    } 

這是我的測試,到目前爲止(這是失敗的:預期錯誤是truthy):

it('should start loading as soon as login is triggered', fakeAsync(() => { 
    spyOn(mockRequestsService, 'login').and.returnValue(Observable.of(token)); 
    component.triggerLogin(); 
    fixture.detectChanges(); 
    expect(component.loading).toBeTruthy(); 
    expect(mockRequestsService.login).toHaveBeenCalled(); 
    })); 

正如你所看到的可變載荷是第一設置爲true,但之後在requestsService的響應中將其設置爲false。這就是爲什麼測試期望值是錯誤的。但是,我想測試該變量的第一個賦值。

回答

0

單位(在這種情況下,它們是方法)應該單獨測試。只有被測試的單元應該是真實的,其餘的應該在必要時被嘲弄/殘留。

spyOn(component, 'login'); 
component.triggerLogin(handleLogin); 
expect(component.loading).toBe(true); 
expect(mockRequestsService.login).toHaveBeenCalledWith(...); 
expect(component.login).toHaveBeenCalledWith(token); 

因爲我們沒有測試這兩種方法怎麼繼續玩在一起(這可以在集成/端到端測試來補測),我們應該是一絲不苟。 toHaveBeenCalledtoHaveBeenCalledWith不包括所有可能出錯的事情。最好是還測試login被調用一次,並用適當的上下文(被稱爲像.subscribe(this.login)時,可能會失敗):

expect(component.login.calls.all()).toEqual([ 
    jasmine.objectContaining({ object: component, args: [token] }) 
]); 

然後原login可以在另一檢驗。

相關問題