【问题标题】:redux observable: Why don`t can get all actions in testredux observable:为什么不能在测试中获取所有操作
【发布时间】:2017-01-06 13:31:02
【问题描述】:

我正在尝试测试“redux observable epic”,但测试失败,因为并非所有操作都在 store.getActions() 中,奇怪的是 store.dispatch 函数运行。

史诗和动作

export const VERIFY_SESION = 'auth/VERIFY_SESION';
export const SET_POLICIES_ACCEPTED = 'auth/SET_POLICIES_ACCEPTED';
export const AUTHENTICATE = 'auth/AUTHENTICATE';
export function setPoliciesAccepted(wereAccepted: boolean) {
  return {
    wereAccepted,
    type: SET_POLICIES_ACCEPTED,
  };
}

export function verifySesion() {
  return {
    type: VERIFY_SESION,
  };
}

export function authenticate(token) {
  return {
    token,
    type: AUTHENTICATE,
  };
}

export function verifySesionEpic(action$, store) {
  return action$
    .ofType(VERIFY_SESION)
    .switchMap(async () => {
      try {
        store.dispatch(setBlockLoading(true));
        const token = await AsyncStorage.getItem('token');
        if (token !== null) {
          store.dispatch(setBlockLoading(false));
          return authenticate(token);
        }
        const policiesWereAccepted = await AsyncStorage.getItem('policiesWereAccepted');
        store.dispatch(setBlockLoading(false));
        return setPoliciesAccepted(policiesWereAccepted);
      } catch (error) {
        return setMessage(error.message);
      }
    });
}

测试

describe('actions/auth', () => {
  let store;
  const asyncStorageGetStub = stub(AsyncStorage, 'getItem');

  beforeEach(() => {
    store = mockStore();
  });

  afterEach(() => {
    asyncStorageGetStub.restore();
  });

  it('Should call authenticate if token', () => {
    const token = 'mitoken';
    asyncStorageGetStub.withArgs('token').returns(Promise.resolve(token));
    store.dispatch(verifySesion());
    expect(store.getActions()).toContain({ type: AUTHENTICATE, token });
  });
});

测试结果

1) "actions/auth 应该为 verifySession 调用史诗: 错误:预期 [{ type: 'auth/VERIFY_SESION' } ] 包含 { token: 'mitoken', type: 'auth/AUTHENTICATE' }"

注意

我确定条件标记 !== null 通过

【问题讨论】:

  • 由于您调用 dispatchexpect 同步,返回的第一个操作将是 VERIFY,稍后我们可能会添加 AUTHENTICATE 操作(取决于您的史诗般的需要完成)

标签: redux mocha.js rxjs sinon redux-observable


【解决方案1】:

我要在 getAction 之前添加超时,因为 'AUTHENTICATE' 操作是在之后添加的。

it('Should call authenticate if token', (done) => {
    const token = 'mitoken';
    asyncStorageGetStub.withArgs('token').returns(Promise.resolve(token));
    store.dispatch(verifySesion());
    setTimeout(() => {
      expect(store.getActions()).toContain({ type: AUTHENTICATE, token });
      done();
    }, 1000);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多