2016-08-03 258 views
0

我試圖測試與流量儲存一些非常簡單的功能異步API測試流量商店在特定事件的呼叫服務,使http請求並返回Promise,店面看起來像:用茉莉花

case UserActions.FETCH_USER_BY_ID: 
    const userService = new UserService(); 
    userService.fetchUserById(action.id) 
     then(user => { 
     this.user = user; 
     this.emit(USER_FETCH_COMPLETED); 
     }); 

爲了測試我使用Jasmine,我的測試用例是這樣的:

it('should fetch user by id',() => { 
    const userStore = require('../stores/userStore'); 
    const mockUser = {name: 'test', id: 123}; 
    spyOn(UserService.prototype, 'fetchUserById') 
    .and.returnValue(Promise.resolve(mockUser)); 
    dispatchEvent(); 
    expect(userStore.user).toEqual(mockUser); 
}) 

正如所預期的這個測試,如果失敗了,因爲對Promise異步行爲,我瞭解這裏的問題,但我無法找到解決方案如何說測試等到PromiseuserService解決。

回答

1

我不會推薦在店內使用異步調用。它可能導致商店不可預知的狀態。也許你可能有這個錯誤:Flux Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch

取而代之,您的userService應該handleAction與用戶數據,一旦用戶提取。而你的商店應該更新用戶數據。

例如,

用戶服務:

userService.fetchUserById = function(userId) { 
    apiCall(userId).then(user => handleAction(UserActions.FETCH_USER_BY_ID, user)); 
} 

用戶存儲:

case UserActions.FETCH_USER_BY_ID: 
    this.user = payload.data; 
    this.emit(USER_FETCH_COMPLETED); 
    break; 

以下是有關的讀取與API和通量數據好淡文章: https://medium.com/@tribou/flux-getting-data-from-an-api-b73b6478c015#.vei6eq5gt

然後,您可以單獨編寫測試你的商店和服務:

存儲測試:

it('should fetch user by id',() => { 
    const userStore = require('../stores/userStore'); 
    const mockUser = {name: 'test', id: 123}; 
    handleAction(UserActions.FETCH_USER_BY_ID, mockUser) 
    expect(userStore.user).toEqual(mockUser); 
}) 

服務測試:

it('should fetch user by id', (done) => { 
    const userService = require('../service/userService'); 
    // userService.fetchUserById(userId); 
    // here you can add spyOn http service that you are using in the service 
    // and mock the response from that service 
    // and then validate that `handleAction` has been triggered 
})