redux observable:为什么不能测试所有动作

时间:2017-01-06 13:31:03

标签: redux mocha rxjs sinon redux-observable

我正试图测试一部“可观察到的”#epicable 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应该为verifySesion调用epic:      错误:预期[{type:' auth / VERIFY_SESION' }]包含{token:' mitoken',输入:' auth / AUTHENTICATE' }"

注意

我确定条件令牌!== null传递

1 个答案:

答案 0 :(得分:0)

我要在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);
  });