2016-08-03 127 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 
})