【问题标题】:Testing Flux store with async api using Jasmine使用 Jasmine 使用异步 api 测试 Flux 存储
【发布时间】:2016-12-09 14:31:15
【问题描述】:

我正在尝试使用 Flux 存储测试一些非常简单的功能,这些功能在特定事件调用服务时发出 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 的异步行为,我理解这里的问题,但我找不到解决方案如何说测试等到userServicePromise 解决。

【问题讨论】:

    标签: javascript unit-testing reactjs jasmine flux


    【解决方案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 和 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
    })
    

    【讨论】:

      猜你喜欢
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 2015-10-21
      相关资源
      最近更新 更多