柴测试.then内部引发的错误

时间:2019-05-24 02:20:39

标签: asynchronous error-handling promise chai

当来自salesforce的查询返回为空数组时,我们将其捕获在.then()内部,并引发错误,我可以使用console.log并在.catch()内部进行查看。但是,我很难测试该错误消息。

我已经尝试了chai-as-promise和to.eventually.equal('some string'),但是作为AssertionError回来了:期望未定义等于'当前时段没有活动。'

const authorizeEpic: Epic<ActionTypes, ActionTypes, RootState> = action$ =>
  action$.pipe(
    filter(isActionOf(actions.attemptLogin.request)), // or `ofType` from 'redux-observable'?
    switchMap(action => {
      if (action.payload) {
        try {
          const token: Auth.Token = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY) || "")
          if (!token) {
            throw new Error()
          }

          // return an observable that emits a single action...
          return of(actions.attemptLogin.success({
            token
          }))
        } catch (e) {
          // return an observable that emits a single action...
          return of(actions.attemptLogin.failure({
            error: {
              title: "Unable to decode JWT"
            }
          }))
        }
      }

      // return an observable that eventually emits one or more actions...
      return from(Auth.passwordGrant(
        {
          email: val.payload.email,
          password: val.payload.password,
          totp_passcode: ""
        },
        {
          url: "localhost:8088",
          noVersion: true,
          useHttp: true
        }
      )).pipe(
        mergeMap(response => response.ok
          ? of(
            actions.attemptLogin.success({ token: resp.value }),
            // action 2, etc...
          )
          : of(actions.attemptLogin.failure(resp))
        ),
      )
    }),
  )

测试

cosnt campaignMember = {

  getCampaignMembers: async () => {
    await login();
    return conn.sobject('CampaignMember')
      .select('*')
      .then((result) => {
        if (!result[0]) {
          throw Error('No campaigns for current period.');
        }
        return result;
      })
      .catch((err) => {
        log.error(`Could not get paid current campaigns ${err}`);
      });
  },
}
module.exports = campaignMember

我希望能够测试错误消息本身。

1 个答案:

答案 0 :(得分:0)

我通过另一个stackoverflow文章找到了一个解决方案,该文章带有指向github问题评论的链接。 https://github.com/chaijs/chai/issues/882#issuecomment-322131680 我还必须从异步getCampaignMembers方法中删除渔获。:

cosnt campaignMember = {

  getCampaignMembers: async () => {
    await login();
    return conn.sobject('CampaignMember')
      .select('*')
      .then((result) => {
        if (!result[0]) {
          throw Error('No campaigns for current period.');
        }
        return result;
      })
      .catch(err => throw Error(err));
  },
}
module.exports = campaignMember

测试

it('should pass', async () => {
  await otherAsyncMethod();

  await campaignMember. getCampaignMembers(currentParent).catch((err) => {
    expect(err).to.be.an('error').with.property('message', 'Error: No campaigns for current period.');
  });

});
相关问题