消耗承诺链的Jest测试功能

时间:2017-07-31 08:16:45

标签: javascript reactjs es6-promise jest

我的测试未能等到消耗其中的promise链的方法。

这是方法

 export class UserService {
  static getUser(): void {
    const isFetching = getUserIsFetching(storeInstance.getState());
    if (isFetching) {
      return;
    }
    storeInstance.dispatch(fetchingUserActionCreator());
    HttpService.get<UserResponse>('/api/auth/user')
      .then(userResponse => {
        console.log('test 1');
        Promise.all([
          HttpService.get<Account>('/api/accounts'),
          HttpService.get<PersonalDetails>('/api/accounts/personal-details'),
        ]).then(responses => {
          console.log('test 2');
          storeInstance.dispatch(fetchingUserSuccessActionCreator(responses));
          console.log('test 3');
        })
      })
      .catch(error => {
        storeInstance.dispatch(fetchingUserFailActionCreator(error));
      })
  }
}

这是测试

test.only('should get the user', async () => {
      await UserService.getUser();
      expect(getSpy).toHaveBeenCalledTimes(3);
      expect(getSpy.mock.calls[0][0]).toBe('/api/auth/user');
      expect(getSpy.mock.calls[1][0]).toBe('/api/accounts');
      expect(getSpy.mock.calls[2][0]).toBe('/api/accounts/personal-details');
      expect(storeDispatchSpy).toHaveBeenCalledTimes(2);
    });

断言的第一个是正确的,问题是Promise.all的决心。测试从未到达那里。

我已经添加了一些控制台日志,以查看是否未调用promise all的解析,但是没有。返回了所有控制台日志。

然后我在我的测试中添加了一个控制台日志,就在await UserService.getUser()之后,这是测试后记录的内容。

 test 1 
 await finished
 test 2
 test 3

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

可能你没有在文件中包含Promise。