使用 Jasmine 使用异步 API 测试 Flux 存储



我正在尝试使用 Flux store 测试一些非常简单的功能,该功能在对发出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解决。

我不建议在商店内使用异步调用。它可能导致商店的不可预测状态。您可能遇到此错误:Flux Dispatch.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 和 Flux 获取数据的很好的简短文章: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
})

最新更新